# generate_table_columns.py

import json

from src.connector import Connector

# TODO improve Sql2Code. We prefer only Sql2Code to generate those structures.

connection = Connector.connect(schema_name="INFORMATION_SCHEMA")
try:
    tables_and_columns = {}
    cursor = connection.cursor()
    query = """SELECT TABLE_NAME, COLUMN_NAME
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA <> 'information_schema'"""

    # Execute the query
    cursor.execute(query)
    result = cursor.fetchall()

    # Process the results and group by table name
    for row in result:
        table_name, column_name = row
        if table_name not in tables_and_columns:
            tables_and_columns[table_name] = []
        tables_and_columns[table_name].append(column_name)
        print(f"Table: {table_name}, Column: {column_name}")

    print(f"\n {len(tables_and_columns)} tables found (the minimum should be at least 1332).\n")
    print(f"{sum(len(columns) for columns in tables_and_columns.values())} columns found (the minimun should be at least 16122).\n")

    table_columns_json = json.dumps(tables_and_columns, indent=4).replace("[", "(").replace("]", ")")
    with open("src/table_columns.py", "w") as f:
        # TODO Add date time to the 1st f.write()
        f.write("# Generated by generate_table_columns.py from MySQL system tables. unlike table_definition which generated from our applicative table in the database (should be generated by Sql2Code in the future\n\n")
        f.write(f"table_columns = {table_columns_json}\n")
    print("Table columns have been generated and saved to table_columns.py")
finally:
    connection.close()
