# /opt/docker/dev/service_finder/backend/app/workers/vehicle/bike/bike_R0_brand_hunter.py
import asyncio, logging
from playwright.async_api import async_playwright
from sqlalchemy import text
from app.database import AsyncSessionLocal

logging.basicConfig(level=logging.INFO, format='%(asctime)s [BIKE-R0] %(message)s')
logger = logging.getLogger("R0")

SOURCES = [
    {
        "name": "AutoEvolution",
        "url": "https://www.autoevolution.com/moto/",
        # Robusztusabb szelektor a márkákhoz
        "selector": ".brand a, .all-brands a, .moto-brand a",
        "category": "bike"
    }
]

async def run_r0():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/122.0.0.0")
        
        async with AsyncSessionLocal() as db:
            for src in SOURCES:
                page = await context.new_page()
                try:
                    logger.info(f"Márkák kinyerése: {src['name']}...")
                    await page.goto(src['url'], wait_until="networkidle", timeout=60000)
                    
                    # Ha a szelektor nem talál semmit, begyűjtjük az összes /moto/ linket
                    links = await page.eval_on_selector_all("a[href*='/moto/']", 
                        "nodes => nodes.map(n => ({ 'name': n.innerText.trim(), 'url': n.href }))")
                    
                    # Szűrés: csak a tiszta márka-linkek (pl. .../moto/aprilia/)
                    # A márka linkek általában 5 perjelből állnak (https:// + domain + moto + márka + /)
                    brand_links = [l for l in links if l['url'].count('/') == 5 and not l['url'].endswith('.html')]

                    count = 0
                    for link in brand_links:
                        if len(link['name']) < 2: continue
                        await db.execute(text("""
                            INSERT INTO vehicle.auto_data_crawler_queue (url, level, name, status, category)
                            VALUES (:url, 'brand', :name, 'pending', 'bike')
                            ON CONFLICT (url) DO NOTHING
                        """), {"url": link['url'], "name": link['name']})
                        count += 1
                    
                    await db.commit()
                    logger.info(f"✅ [{src['name']}] kész: {count} márkát találtam.")
                except Exception as e:
                    logger.error(f"❌ Hiba: {e}")
                finally:
                    await page.close()
        await browser.close()

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