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

logger = logging.getLogger("Robot-1-4-Bike")
logging.basicConfig(level=logging.INFO)

BIKE_MAKES = [
    "HONDA", "YAMAHA", "KAWASAKI", "SUZUKI", "HARLEY-DAVIDSON", 
    "BMW", "DUCATI", "KTM", "TRIUMPH", "APRILIA", "MOTO GUZZI", "INDIAN"
]

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

    @classmethod
    async def run(cls):
        logger.info("🏍️ Robot 1.4 (Bike Hunter) indítása...")
        # 2026-tól 1970-ig pörgetjük a motorokat
        years = range(2026, 1969, -1)
        
        async with AsyncSessionLocal() as db:
            for year in years:
                for make in BIKE_MAKES:
                    try:
                        async with httpx.AsyncClient(timeout=20.0) as client:
                            resp = await client.get(cls.API_URL.format(make=make, year=year))
                            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()
                                # TISZTA SQL - Nincs Simon!
                                query = text("""
                                    INSERT INTO data.catalog_discovery 
                                    (make, model, vehicle_class, status, market, model_year, priority_score, source)
                                    VALUES (:make, :model, 'motorcycle', 'pending', 'USA_IMPORT', :year, 8, 'NHTSA-V1-BIKE')
                                    ON CONFLICT ON CONSTRAINT _make_model_market_year_uc DO NOTHING
                                """)
                                await db.execute(query, {"make": make, "model": model_name, "year": year})
                                inserted += 1
                            
                            if inserted > 0:
                                logger.info(f"🏍️ {make} ({year}): {inserted} új motor rögzítve.")
                            await db.commit()
                    except Exception as e:
                        logger.error(f"❌ Bike Error {make} ({year}): {e}")
                
                # Évjáratonként egy pici pihenő az API-nak
                await asyncio.sleep(0.5)

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