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

logger = logging.getLogger("Robot-1-5-Heavy-EU")
logging.basicConfig(level=logging.INFO)

class HeavyEUHunter:
    # RDW Open Data - Hollandia az EU kapuja
    RDW_URL = "https://opendata.rdw.nl/resource/m9d7-ebf2.json"
    
    @classmethod
    async def fetch_rdw_heavy(cls, vehicle_type: str):
        """
        vehicle_type: 'Vrachtwagen' (Teher), 'Bus', 'Kampeerauto' (Lakóautó)
        """
        # Lekérjük az összes egyedi márka-típus párost
        query_url = f"{cls.RDW_URL}?voertuigsoort={vehicle_type}&$select=merk,handelsbenaming&$limit=10000"
        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                resp = await client.get(query_url)
                return resp.json() if resp.status_code == 200 else []
            except Exception as e:
                logger.error(f"❌ RDW Error: {e}")
                return []

    @classmethod
    async def run(cls):
        logger.info("🚛 Robot 1.5 (EU Heavy Duty) indítása...")
        # Definíciók: RDW név -> Mi kategóriánk
        job_list = {
            "Vrachtwagen": "truck",
            "Bus": "bus",
            "Kampeerauto": "rv"
        }

        async with AsyncSessionLocal() as db:
            for rdw_name, internal_class in job_list.items():
                logger.info(f"📥 {rdw_name} adatok letöltése...")
                data = await cls.fetch_rdw_heavy(rdw_name)
                
                inserted = 0
                for item in data:
                    make = item.get('merk', '').upper().strip()
                    model = item.get('handelsbenaming', '').upper().strip()
                    
                    if not make or not model: continue

                    # Szűrés a kért EU márkákra + amik jönnek az RDW-ből
                    query = text("""
                        INSERT INTO data.catalog_discovery 
                        (make, model, vehicle_class, status, market, priority_score, source)
                        VALUES (:make, :model, :v_class, 'pending', 'EU', 20, 'RDW-HEAVY')
                        ON CONFLICT ON CONSTRAINT _make_model_market_year_uc DO NOTHING
                    """)
                    res = await db.execute(query, {"make": make, "model": model, "v_class": internal_class})
                    if res.rowcount > 0: inserted += 1
                
                await db.commit()
                logger.info(f"✅ {rdw_name}: {inserted} új EU-s nagygép rögzítve.")

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