import asyncio, logging, random
from playwright.async_api import async_playwright
from sqlalchemy import text
from app.database import AsyncSessionLocal

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

async def run_r0():
    url = "https://www.auto-data.net/en/allbrands"
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()
        logger.info(f"Márkák gyűjtése innen: {url}")
        
        await page.goto(url, wait_until="networkidle")
        # Robusztus linkgyűjtés: minden <a> aminek a href-jében benne van a 'brand-'
        links = await page.eval_on_selector_all("a[href*='brand-']", 
            "nodes => nodes.map(n => ({ 'name': n.innerText.trim(), 'url': n.href }))")
        
        async with AsyncSessionLocal() as db:
            count = 0
            for link in links:
                if not link['name'] or 'brand' not in link['url']: continue
                
                query = text("""
                    INSERT INTO vehicle.auto_data_crawler_queue (url, level, name, status)
                    VALUES (:url, 'brand', :name, 'pending')
                    ON CONFLICT (url) DO NOTHING
                """)
                res = await db.execute(query, {"url": link['url'], "name": link['name']})
                if res.rowcount > 0: count += 1
            
            await db.commit()
            logger.info(f"✅ Kész! {count} új márkát találtam és mentettem el.")
        
        await browser.close()

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