# /opt/docker/dev/service_finder/backend/app/workers/alchemist_v2_2.py
import asyncio
import logging
from sqlalchemy import select, update, func, and_, case
from app.db.session import AsyncSessionLocal
from app.models.vehicle_definitions import VehicleModelDefinition
from app.services.ai_service import AIService

logger = logging.getLogger("Robot-Alchemist-v2.2")

class AlchemistBot:
    def __init__(self):
        self.batch_size = 5
        self.delay_between_records = 12 # P4000 hűtési ciklus

    async def synthesize_vehicle(self, vehicle_id: int):
        """ AI dúsítás végrehajtása az MDM logikája szerint. """
        async with AsyncSessionLocal() as db:
            res = await db.execute(select(VehicleModelDefinition).where(VehicleModelDefinition.id == vehicle_id))
            v = res.scalar_one_or_none()
            
            if not v or not v.raw_search_context:
                logger.warning(f"⚠️ Nincs feldolgozható kontextus ID:{vehicle_id}")
                return

            make, model = v.make, v.marketing_name
            logger.info(f"🧪 Alkimista munka indul: {make} {model}")
            
            # Munkaterület lefoglalása
            v.status = 'ai_synthesis_in_progress'
            await db.commit()

        # AI hívás (Kívül a DB tranzakción a timeout elkerülésére)
        gold_data = await AIService.get_gold_data_from_research(make, model, v.raw_search_context)

        async with AsyncSessionLocal() as db:
            if gold_data:
                # MDM Arany adatok rögzítése
                await db.execute(
                    update(VehicleModelDefinition)
                    .where(VehicleModelDefinition.id == vehicle_id)
                    .values(
                        marketing_name=gold_data.get("marketing_name", model)[:50],
                        technical_code=gold_data.get("technical_code") or v.technical_code,
                        engine_capacity=gold_data.get("ccm"),
                        power_kw=gold_data.get("kw"),
                        specifications=gold_data, # Teljes specifikáció JSONB
                        status='gold_enriched',
                        updated_at=func.now()
                    )
                )
                logger.info(f"✨ GOLD DATA GENERÁLVA: {make} {model}")
            else:
                await db.execute(
                    update(VehicleModelDefinition)
                    .where(VehicleModelDefinition.id == vehicle_id)
                    .values(status='awaiting_ai_synthesis', attempts=v.attempts + 1)
                )
                logger.warning(f"⚠️ AI hiba, visszatéve a sorba: {make} {model}")
            
            await db.commit()

    async def run(self):
        logger.info("🚀 Robot 2.2 (Alchemist) ONLINE")
        while True:
            async with AsyncSessionLocal() as db:
                # Prioritás: Autók (Suzuki, Toyota...) -> Többi autó -> Motorok -> Egyéb
                priorities = case(
                    (and_(VehicleModelDefinition.vehicle_type == 'car', 
                          VehicleModelDefinition.make.in_(['SUZUKI', 'TOYOTA', 'SKODA', 'VOLKSWAGEN', 'OPEL'])), 1),
                    (VehicleModelDefinition.vehicle_type == 'car', 2),
                    (and_(VehicleModelDefinition.vehicle_type == 'motorcycle', 
                          VehicleModelDefinition.make.in_(['HONDA', 'YAMAHA', 'SUZUKI', 'KAWASAKI'])), 3),
                    else_=4
                )

                stmt = select(VehicleModelDefinition.id).where(
                    VehicleModelDefinition.status == 'awaiting_ai_synthesis'
                ).order_by(priorities, VehicleModelDefinition.updated_at.asc()).limit(self.batch_size)
                
                res = await db.execute(stmt)
                ids = [r[0] for r in res.fetchall()]

            if not ids:
                await asyncio.sleep(20)
                continue

            for vid in ids:
                await self.synthesize_vehicle(vid)
                await asyncio.sleep(self.delay_between_records)

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