import asyncio
import logging
import sys
import datetime
from sqlalchemy import select, and_, text, update
from sqlalchemy.orm import joinedload
from app.db.session import SessionLocal
from app.models.asset import Asset, AssetCatalog
from app.services.ai_service import AIService

logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] Auditor: %(message)s', stream=sys.stdout)
logger = logging.getLogger("VIN-Auditor-v1.3.0")

class VINAuditor:
    """
    VIN Auditor v1.3.0
    - Alvázszám alapú hitelesítés és MDM szinkron.
    """

    @classmethod
    async def audit_asset(cls, asset_id: int):
        # 1. ADATGYŰJTÉS ÉS SESSION ZÁRÁS
        async with SessionLocal() as db:
            stmt = select(Asset).options(joinedload(Asset.catalog)).where(Asset.id == asset_id)
            asset = (await db.execute(stmt)).scalar_one_or_none()
            if not asset or not asset.vin: return
            make, vin, current_kw = asset.catalog.make, asset.vin, asset.catalog.power_kw

        # 2. AI FÁZIS (Izolált hívás)
        try:
            logger.info(f"🛡️ VIN Audit indul: {vin}")
            truth = await AIService.get_clean_vehicle_data(make, vin, "vin_audit", {"vin": vin})
            
            if truth and truth.get("kw"):
                # 3. MENTÉSI FÁZIS (Új session)
                async with SessionLocal() as db:
                    real_kw = int(truth["kw"])
                    if abs(real_kw - (current_kw or 0)) >= 5:
                        # Új variáns mentése
                        new_v = AssetCatalog(make=make.upper(), model=truth.get("marketing_name", "Unknown"), power_kw=real_kw)
                        db.add(new_v)
                        await db.flush()
                        await db.execute(update(Asset).where(Asset.id == asset_id).values(catalog_id=new_v.id, is_verified=True))
                    else:
                        await db.execute(update(Asset).where(Asset.id == asset_id).values(is_verified=True))
                    
                    await db.commit()
                    logger.info(f"✅ Audit sikeres: {vin}")
        except Exception as e:
            logger.error(f"🚨 Auditor hiba: {e}")

    async def run(self):
        logger.info("🛡️ Auditor v1.3.0 ONLINE")
        while True:
            try:
                async with SessionLocal() as db:
                    stmt = select(Asset.id).where(and_(Asset.is_verified == False, Asset.vin.isnot(None))).limit(1)
                    aid = (await db.execute(stmt)).scalar_one_or_none()
                if aid: await self.audit_asset(aid)
                else: await asyncio.sleep(60)
            except: await asyncio.sleep(30)

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