# /opt/docker/dev/service_finder/backend/app/tests_internal/diagnostics/compare_schema.py
import asyncio
import sys
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import inspect
from app.database import Base
from app.core.config import settings

try:
    import app.models 
except ImportError as e:
    print(f"❌ KRITIKUS IMPORT HIBA: {e}")
    sys.exit(1)

async def compare():
    """ Diagnosztika minden sémára: identity, data, system. """
    print(f"🔗 Kapcsolódás az adatbázishoz...")
    engine = create_async_engine(str(settings.SQLALCHEMY_DATABASE_URI))
    
    def get_diff(connection):
        inspector = inspect(connection)
        # Ezeket a sémákat ellenőrizzük
        schemas = ["identity", "data", "system"]
        all_db_schemas = inspector.get_schema_names()
        
        mismatches = 0
        for sc in schemas:
            if sc not in all_db_schemas:
                print(f"❌ HIBA: A(z) '{sc}' séma nem létezik!")
                continue

            db_tables = inspector.get_table_names(schema=sc)
            # Begyűjtjük a modelleket, amik ehhez a sémához tartoznak
            model_tables = [t.name for t in Base.metadata.sorted_tables if t.schema == sc]
            
            print(f"\n--- 🔍 DIAGNOSZTIKA: '{sc}' séma ({len(db_tables)} tábla a DB-ben) ---")
            
            for mt in model_tables:
                if mt not in db_tables:
                    print(f"❌ HIÁNYZÓ TÁBLA: {sc}.{mt}")
                    mismatches += 1
                else:
                    db_cols = {c['name']: c for c in inspector.get_columns(mt, schema=sc)}
                    # Kikeressük a modellt a metadata-ból
                    table_key = f"{sc}.{mt}"
                    model_cols = Base.metadata.tables[table_key].columns
                    
                    missing_cols = [m.name for m in model_cols if m.name not in db_cols]
                    if missing_cols:
                        print(f"⚠️  {mt:25} | HIÁNYZÓ OSZLOPOK: {missing_cols}")
                        mismatches += 1
                    else:
                        print(f"✅ {mt:25} | Rendben.")
        return mismatches

    try:
        async with engine.connect() as conn:
            err_count = await conn.run_sync(get_diff)
            print(f"\n--- Összegzés: {err_count} eltérés található. ---\n")
    except Exception as e:
        print(f"❌ HIBA: {e}")
    finally:
        await engine.dispose()

if __name__ == "__main__":
    asyncio.run(compare())