import sys
import os

# Ensure project root is in path
sys.path.append(os.getcwd())

from app import create_app
from app.extensions import db
from sqlalchemy.schema import CreateTable
from sqlalchemy.dialects import mysql

# Import all models to ensure they are registered in metadata
# Importing the package should trigger imports in __init__.py
import app.core.models
import app.modules.crm.models
import app.modules.erp.models
import app.modules.hris.models
import app.modules.collaboration.models

def generate_ddl():
    """Generates MariaDB schema from SQLAlchemy models."""
    app = create_app()

    # Use MySQL dialect for MariaDB compatibility
    dialect = mysql.dialect()

    with app.app_context():
        # Get sorted tables to handle foreign keys properly
        tables = db.metadata.sorted_tables

        with open('database.sql', 'w') as f:
            f.write("-- AKSARA Enterprise Modular Core System Schema\n")
            f.write("-- Generated by SQLAlchemy for MariaDB\n\n")
            f.write("SET FOREIGN_KEY_CHECKS=0;\n\n")

            for table in tables:
                # Compile table creation SQL
                # Note: compile(dialect) returns a Compiled object, convert to string
                create_sql = CreateTable(table).compile(dialect=dialect)

                # Append semicolon and newline
                f.write(str(create_sql).strip())
                f.write(";\n\n")

            f.write("SET FOREIGN_KEY_CHECKS=1;\n")

        print(f"Successfully generated database.sql with {len(tables)} tables: {[t.name for t in tables]}")

if __name__ == "__main__":
    generate_ddl()
