# /app/app/workers/vehicle/vehicle_robot_1_2_nhtsa_fetcher.py
import asyncio
import httpx
import logging
from sqlalchemy import text
from app.database import AsyncSessionLocal

logger = logging.getLogger("Robot-1-2-NHTSA-EU-Only")
logging.basicConfig(level=logging.INFO)

class NHTSAFetcher:
    API_URL = "https://vpic.nhtsa.dot.gov/api/vehicles/GetModelsForMakeYear/make/{make}/modelyear/{year}?format=json"

    @classmethod
    async def get_eu_makes(cls):
        """Lekéri azokat a márkákat, amik már benne vannak az adatbázisban EU-s forrásból."""
        async with AsyncSessionLocal() as db:
            # Csak azokat a márkákat keressük az USA-ban, amiket az EU-ban (RDW) már láttunk
            query = text("SELECT DISTINCT make FROM data.catalog_discovery WHERE market = 'EU' OR source = 'RDW'")
            res = await db.execute(query)
            return [row[0] for row in res.fetchall()]

    @classmethod
    async def run(cls):
        logger.info("🚀 Robot 1.2 (EU-Guided NHTSA) indítása...")
        
        while True:
            target_makes = await cls.get_eu_makes()
            if not target_makes:
                logger.warning("⚠️ Még nincs EU-s márka az adatbázisban. Várakozás...")
                await asyncio.sleep(60)
                continue

            # 2026-tól megyünk vissza a múltba
            for year in range(2026, 1950, -1):
                async with AsyncSessionLocal() as db:
                    for make in target_makes:
                        try:
                            async with httpx.AsyncClient(timeout=20.0) as client:
                                url = cls.API_URL.format(make=make, year=year)
                                resp = await client.get(url)
                                if resp.status_code != 200: continue
                                
                                models = resp.json().get("Results", [])
                                inserted = 0
                                for m in models:
                                    model_name = m.get("Model_Name").upper().strip()
                                    # USA_IMPORT jelölés, de csak EU-s márkákhoz!
                                    query = text("""
                                        INSERT INTO data.catalog_discovery 
                                        (make, model, vehicle_class, status, market, model_year, priority_score, source)
                                        VALUES (:make, :model, 'car', 'pending', 'USA_IMPORT', :year, 5, 'NHTSA-EU-FILTERED')
                                        ON CONFLICT ON CONSTRAINT _make_model_market_year_uc DO NOTHING
                                    """)
                                    res = await db.execute(query, {"make": make, "model": model_name, "year": year})
                                    if res.rowcount > 0: inserted += 1
                                
                                if inserted > 0:
                                    logger.info(f"✅ {make} ({year}): {inserted} variáns dúsítva az USA-ból.")
                                await db.commit()
                        except Exception as e:
                            logger.error(f"❌ Hiba: {make} {year}: {e}")
                    await asyncio.sleep(0.5)

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