# /opt/docker/dev/service_finder/backend/app/workers/vehicle/vehicle_robot_1_5_heavy_eu1.0.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_URL = "https://opendata.rdw.nl/resource/m9d7-ebf2.json"
    
    @classmethod
    async def fetch_rdw_heavy(cls, vehicle_type: str):
        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 - Kötegelt mód...")
        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)
                
                if not data: continue

                # A 10.000 adatot egyetlen listába gyűjtjük
                insert_data = []
                for item in data:
                    make = item.get('merk', '').upper().strip()
                    model = item.get('handelsbenaming', '').upper().strip()
                    if make and model:
                        insert_data.append({"make": make, "model": model, "v_class": internal_class})

                if insert_data:
                    query = text("""
                        INSERT INTO vehicle.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
                    """)
                    # Egyetlen SQL hívással beszúrjuk akár a 10.000 sort is!
                    await db.execute(query, insert_data)
                    await db.commit()
                    logger.info(f"✅ {rdw_name}: {len(insert_data)} EU-s nagygép beküldve kötegelve.")

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