import asyncio
import httpx
import logging
import sys
from sqlalchemy import text
from app.database import AsyncSessionLocal

logger = logging.getLogger("Robot-1-5-Heavy-EU")
logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s [%(levelname)s] R1.5-Heavy: %(message)s',
    stream=sys.stdout
)

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 API Error: {e}")
                return []

    @classmethod
    async def run(cls):
        logger.info("🚛 Robot 1.5 (EU Heavy Duty) indítása...")
        
        # --- DB KAPCSOLÓDÁSI VÉDELEM (RETRY) ---
        db_connected = False
        for i in range(12): # 1 percig próbálkozik (12 * 5mp)
            try:
                async with AsyncSessionLocal() as db:
                    await db.execute(text("SELECT 1"))
                    db_connected = True
                    logger.info("✅ Adatbázis kapcsolat aktív!")
                    break
            except Exception:
                logger.warning(f"⏳ Adatbázis nem elérhető ({i+1}/12), várakozás 5mp...")
                await asyncio.sleep(5)
        
        if not db_connected:
            logger.error("💀 Nem sikerült kapcsolódni az adatbázishoz. Leállás.")
            return

        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

                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:
                    # JAVÍTÁS: Constraint név helyett konkrét mezők az ütközéshez
                    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 (make, model, vehicle_class) DO NOTHING
                    """)
                    try:
                        await db.execute(query, insert_data)
                        await db.commit()
                        logger.info(f"✅ {rdw_name}: {len(insert_data)} gép beküldve.")
                    except Exception as e:
                        logger.error(f"❌ Mentési hiba ({rdw_name}): {e}")
                        await db.rollback()

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