import json
import sys
import getopt
import requests

def print_help():
    print("Usage: python script.py <baseDir>")
    print("Options:")
    print("  -h, --help\t\tDisplay this help message")

try:
    opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
except getopt.GetoptError as err:
    print(str(err))
    print_help()
    sys.exit(2)

for opt, arg in opts:
    if opt in ("-h", "--help"):
        print_help()
        sys.exit()

if len(args) == 0:
    print("Error: baseDir argument is missing.")
    print_help()
    sys.exit(2)

baseDir = args[0]

typesDict = {
    "BIGINT": "long",
    "DOUBLE": "double",
    "FLOAT": "float",
    "INT": "int",
    "INTEGER": "int",
    "BOOLEAN": "boolean",
    "BOOL": "boolean",
    "VARCHAR": "string",
    "CHAR": "char",
    "SMALLINT": "short",
    "TINYINT": "byte",
    "DATETIME": "timestamp"
}

print("### working in ", baseDir)
print("---")

if not baseDir.endswith("/"):
    baseDir = baseDir + "/"
metaJsonFile = baseDir + "metadata.json"
print("### metafile ", metaJsonFile)

# Detect if baseDir is a local directory or HTTP directory
if baseDir.startswith("http"):
    # Fetch metadata.json from HTTP directory
    response = requests.get(metaJsonFile)
    metadata = json.loads(response.text)

    databaseJson = baseDir + metadata['database']

    # Fetch database JSON from HTTP directory
    response = requests.get(databaseJson)
    ddata = json.loads(response.text)
else:
    with open(metaJsonFile) as mf:
        metadata = json.load(mf)

    database = metadata['database']
    databaseJson = baseDir + database

    with open(databaseJson) as df:
        ddata = json.load(df)

databaseName = ddata['database']
print("name:", databaseName)
datbaseID = '"#' + databaseName + '"'
print('"@id":', datbaseID)
databaseDescr = ddata.get('description', 'No database description available')
print("description:", databaseDescr)
print("### databaseDescr", databaseDescr)

print("### database JSON ", databaseJson)
tables = metadata['tables']
print("tables:")

for table in tables:
    tableJson = baseDir + table['schema']
    print("### table: ", tableJson)

    # Detect if tableJson is a local file or HTTP resource
    if tableJson.startswith("http"):
        response = requests.get(tableJson)
        tdata = json.loads(response.text)
    else:
        with open(tableJson) as tf:
            tdata = json.load(tf)

    tablename = tdata["table"]
    tableDescr = tdata.get("description", "No table description available")
    print("### tablename", tablename)
    print("- name:", tablename)
    tableID = '"#' + tablename + '"'
    print('  "@id":', tableID)
    print("  description:", tableDescr)
    print("### tableDescr", tableDescr)
    print("  columns:")
    cols = tdata['schema']

    for col in cols:
        colName = col['name']
        print("  - name:", colName)
        colID = '"#' + tablename + '.' + colName + '"'
        colType = col['type']
        print('    "@id":', colID)
        print("### Name:", col['name'])
        print("### Type:", col['type'])

        mysqltype = colType.split()[0]
        print("### mySQLType:", mysqltype)
        votype = ""
        stringL = ""

        if colType.lower().startswith('varchar'):
            datatype = "string"
            stringL = colType.replace('VARCHAR(', '').replace(')', '')
            votype = typesDict["VARCHAR"]
        elif colType.lower().startswith('char'):
            datatype = "char"
            stringL = colType.replace('CHAR(', '').replace(')', '')
            votype = typesDict["CHAR"]
        elif colType.lower().startswith('datetime'):
            datatype = "string"
            stringL = colType.replace('DATETIME(', '').replace(')', '')
            votype = typesDict["DATETIME"]
        elif colType.lower().startswith('int('):
            datatype = "int"
            stringL = colType.replace('INT(', '').replace(')', '')
            votype = typesDict["INT"]
            mysqltype=mysqltype.upper()
        else:
            votype = typesDict[mysqltype]

        print('    datatype:', votype)
        print('    description:', colName)

        if votype == 'string' or votype == 'char':
            print('    length:', stringL)
        print('    mysql:datatype:', mysqltype)
        print("### types", mysqltype, votype)
