# /opt/docker/dev/service_finder/backend/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):
        async with AsyncSessionLocal() as db:
            query = text("SELECT DISTINCT make FROM vehicle.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 - Kötegelt mód...")
        
        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

            # A hálózati kliens a cikluson KÍVÜL van, így újrahasznosítja a kapcsolatokat!
            async with httpx.AsyncClient(timeout=20.0) as client:
                for year in range(2026, 1950, -1):
                    async with AsyncSessionLocal() as db:
                        for make in target_makes:
                            try:
                                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", [])
                                if not models: continue

                                # Gyors lista generálás a kötegelt mentéshez
                                insert_data = []
                                for m in models:
                                    model_name = m.get("Model_Name").upper().strip()
                                    insert_data.append({"make": make, "model": model_name, "year": year})

                                if insert_data:
                                    query = text("""
                                        INSERT INTO vehicle.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
                                    """)
                                    # Egyetlen SQL hívás a teljes listára!
                                    await db.execute(query, insert_data)
                                    await db.commit()
                                    logger.info(f"✅ {make} ({year}): {len(insert_data)} variáns dúsítva az USA-ból.")
                            except Exception as e:
                                logger.error(f"❌ Hiba: {make} {year}: {e}")
                            await asyncio.sleep(0.1)  # Kisebb pihenő is elég, mert hatékonyabbak vagyunk

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