#!/usr/bin/env python3
"""
Ellenőrzi, hogy a #179-es issue séma változtatásai sikeresen alkalmazva lettek-e.
- branch_id és relocation_performed oszlopok az assets táblában
- verified_purchase_date oszlop az asset_financials táblában
"""

import asyncio
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "postgresql+asyncpg://postgres:postgres@postgres:5432/service_finder"

async def check_columns():
    """Ellenőrzi a hiányzó oszlopokat."""
    engine = create_async_engine(DATABASE_URL, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as session:
        # 1. assets tábla oszlopai
        result = await session.execute(text("""
            SELECT column_name, data_type, is_nullable
            FROM information_schema.columns
            WHERE table_schema = 'vehicle' AND table_name = 'assets'
            AND column_name IN ('branch_id', 'relocation_performed')
            ORDER BY column_name;
        """))
        assets_cols = {row[0]: row for row in result.fetchall()}
        
        # 2. asset_financials tábla oszlopai
        result = await session.execute(text("""
            SELECT column_name, data_type, is_nullable
            FROM information_schema.columns
            WHERE table_schema = 'vehicle' AND table_name = 'asset_financials'
            AND column_name = 'verified_purchase_date';
        """))
        financials_cols = {row[0]: row for row in result.fetchall()}
        
        print("=== #179 SCHEMA ELLENŐRZÉS ===")
        print("1. vehicle.assets tábla:")
        if 'branch_id' in assets_cols:
            col = assets_cols['branch_id']
            print(f"   ✅ branch_id: {col[1]} (nullable: {col[2]})")
        else:
            print("   ❌ branch_id oszlop HIÁNYZIK!")
            
        if 'relocation_performed' in assets_cols:
            col = assets_cols['relocation_performed']
            print(f"   ✅ relocation_performed: {col[1]} (nullable: {col[2]})")
        else:
            print("   ❌ relocation_performed oszlop HIÁNYZIK!")
            
        print("\n2. vehicle.asset_financials tábla:")
        if 'verified_purchase_date' in financials_cols:
            col = financials_cols['verified_purchase_date']
            print(f"   ✅ verified_purchase_date: {col[1]} (nullable: {col[2]})")
        else:
            print("   ❌ verified_purchase_date oszlop HIÁNYZIK!")
        
        # 3. Foreign key ellenőrzés (opcionális)
        result = await session.execute(text("""
            SELECT tc.constraint_name, tc.constraint_type
            FROM information_schema.table_constraints tc
            JOIN information_schema.key_column_usage kcu
                ON tc.constraint_name = kcu.constraint_name
            WHERE tc.table_schema = 'vehicle' AND tc.table_name = 'assets'
                AND kcu.column_name = 'branch_id'
                AND tc.constraint_type = 'FOREIGN KEY';
        """))
        fk = result.fetchone()
        if fk:
            print(f"\n3. Foreign key meglétének ellenőrzése: ✅ {fk[0]}")
        else:
            print("\n3. Foreign key meglétének ellenőrzése: ⚠️  Nincs foreign key constraint (lehet, hogy nem kötelező)")
        
        # 4. Default érték ellenőrzés relocation_performed-re
        result = await session.execute(text("""
            SELECT column_default
            FROM information_schema.columns
            WHERE table_schema = 'vehicle' AND table_name = 'assets'
                AND column_name = 'relocation_performed';
        """))
        default = result.scalar()
        if default and 'false' in default.lower():
            print(f"4. Default érték relocation_performed: ✅ {default}")
        else:
            print(f"4. Default érték relocation_performed: ⚠️  {default}")
        
        # Összegzés
        missing = []
        if 'branch_id' not in assets_cols:
            missing.append('branch_id')
        if 'relocation_performed' not in assets_cols:
            missing.append('relocation_performed')
        if 'verified_purchase_date' not in financials_cols:
            missing.append('verified_purchase_date')
        
        if not missing:
            print("\n🎉 ÖSSZES SÉMA VÁLTOZTATÁS SIKERESEN ALKALMAZVA!")
            return True
        else:
            print(f"\n❌ HIÁNYZÓ OSZLOPOK: {', '.join(missing)}")
            return False

async def main():
    try:
        success = await check_columns()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"Hiba történt: {e}")
        sys.exit(1)

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