"""
Generates schema.sql — the full MySQL CREATE TABLE statements for every model,
compiled directly from models.py without needing a live MySQL connection.
Import the resulting file into phpMyAdmin (or `mysql < schema.sql`) against
an already-created, empty database (cPanel > MySQL Databases).

Re-run this any time models.py changes, before your next deploy:

    python generate_schema.py

After importing schema.sql on the server, run `python init_db.py` once
(via SSH/Terminal in the activated virtualenv) to create your admin login —
it's safe to run against tables that already exist.
"""
from sqlalchemy.schema import CreateTable
from sqlalchemy.dialects import mysql

from app import create_app
from extensions import db

app = create_app()

with app.app_context():
    dialect = mysql.dialect()
    lines = [
        "-- Auto-generated by generate_schema.py — do not edit by hand.",
        "-- Import into an already-created, empty MySQL database via phpMyAdmin.",
        "SET FOREIGN_KEY_CHECKS=0;",
        "",
    ]
    for table in db.metadata.sorted_tables:
        ddl = str(CreateTable(table).compile(dialect=dialect)).strip()
        if not ddl.endswith(';'):
            ddl = ddl.rstrip() + ';'
        # Compiled DDL doesn't include engine/charset by default — pin both explicitly.
        ddl = ddl[:-1] + " ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"
        lines.append(ddl)
        lines.append("")
    lines.append("SET FOREIGN_KEY_CHECKS=1;")

    with open('schema.sql', 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines) + '\n')

    print(f"Wrote schema.sql with {len(db.metadata.sorted_tables)} table(s).")
