import re
import os
import sys
from datetime import datetime
def studly_case(name):
    parts = re.split(r'[_\W]+', name.lower())
    return ''.join(word.capitalize() for word in parts if word)
# -----------------------------
# Converte tipos SQL → Laravel
# -----------------------------
def map_type(sql_type):
    sql_type = sql_type.lower()

    if "int" in sql_type:
        return "integer"
    if "bigint" in sql_type:
        return "bigInteger"
    if "varchar" in sql_type:
        return "string"
    if "char" in sql_type:
        return "char"
    if "text" in sql_type:
        return "text"
    if "mediumtext" in sql_type:
        return "mediumText"
    if "longtext" in sql_type:
        return "longText"
    if "datetime" in sql_type:
        return "dateTime"
    if "timestamp" in sql_type:
        return "timestamp"
    if "date" in sql_type:
        return "date"
    if "time" in sql_type:
        return "time"
    if "decimal" in sql_type:
        return "decimal"
    if "float" in sql_type:
        return "float"
    if "double" in sql_type:
        return "double"
    if "tinyint(1)" in sql_type:
        return "boolean"

    return "string"  # fallback


# -----------------------------
# Gera linha de migration
# -----------------------------
def create_column_line(name, col_type, attributes):
    laravel_type = map_type(col_type)

    line = f"$table->{laravel_type}('{name}')"

    if "unsigned" in col_type:
        line += "->unsigned()"
    if "not null" not in attributes.lower():
        line += "->nullable()"
    if "auto_increment" in attributes.lower():
        line = f"$table->increments('{name}')"

    # -----------------------------
    # DEFAULT e TIMESTAMP
    # -----------------------------

    attrs_lower = attributes.lower()

    # ON UPDATE CURRENT_TIMESTAMP
    if "on update current_timestamp" in attrs_lower:
        line += "->useCurrentOnUpdate()"

    # DEFAULT CURRENT_TIMESTAMP
    if "default current_timestamp" in attrs_lower:
        line += "->useCurrent()"
    else:
        # DEFAULT normal (null, número, string)
        default_match = re.search(
            r"default\s+(null|'[^']*'|[0-9.]+)",
            attributes,
            re.IGNORECASE
        )

        if default_match:
            default = default_match.group(1)

            if default.lower() == "null":
                line += "->default(null)"
            else:
                line += f"->default({default})"
    return line + ";"


# -----------------------------
# Cria arquivo migration
# -----------------------------
def create_migration(table, columns):
    timestamp = datetime.now().strftime("%Y_%m_%d_%H%M%S")
    filename = f"{timestamp}_create_{table}_table.php"

    content = "<?php\n\nuse Illuminate\\Database\\Migrations\\Migration;\n"
    content += "use Illuminate\\Database\\Schema\\Blueprint;\n"
    content += "use Illuminate\\Support\\Facades\\Schema;\n\n"
    class_name = studly_case(table)
    content += f"class Create{class_name}Table extends Migration\n{{\n"
    content += "    public function up()\n    {\n"
    content += f"        Schema::create('{table}', function (Blueprint $table) {{\n"

    for col in columns:
        content += f"            {col}\n"

    content += "        });\n    }\n\n"
    content += "    public function down()\n    {\n"
    content += f"        Schema::dropIfExists('{table}');\n"
    content += "    }\n}\n"

    return filename, content


# -----------------------------
# Parser do arquivo SQL
# -----------------------------
def parse_sql(sql_text):
    tables = {}

    create_table_regex = r"CREATE TABLE `([^`]+)` \((.*?)\);"
    matches = re.findall(create_table_regex, sql_text, re.DOTALL | re.IGNORECASE)

    for table, body in matches:
        lines = body.split(",\n")
        columns = []
        seen_columns = set()

        for line in lines:
            line = line.strip()

            # Ignora chaves e índices
            if line.upper().startswith((
                "PRIMARY KEY",
                "KEY ",
                "INDEX ",
                "UNIQUE ",
                "CONSTRAINT",
                "FOREIGN KEY"
            )):
                continue

            col_match = re.match(r"`([^`]+)`\s+([^\s]+)(.*)", line)
            if not col_match:
                continue

            name, col_type, attributes = col_match.groups()

            # Evita colunas duplicadas
            if name in seen_columns:
                continue

            seen_columns.add(name)
            columns.append(create_column_line(name, col_type, attributes))

        tables[table] = columns

    return tables



# -----------------------------
# MAIN
# -----------------------------
def main():
    if len(sys.argv) < 3:
        print("Uso: python sql_to_laravel_migrations.py arquivo.sql output_dir/")
        sys.exit(1)

    sql_file = sys.argv[1]
    output_dir = sys.argv[2]

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    with open(sql_file, "r", encoding="utf8") as f:
        sql_text = f.read()

    tables = parse_sql(sql_text)

    for table, columns in tables.items():
        filename, content = create_migration(table, columns)
        path = os.path.join(output_dir, filename)

        with open(path, "w", encoding="utf8") as f:
            f.write(content)

        print("Gerado:", filename)


if __name__ == "__main__":
    main()

