# /opt/docker/dev/service_finder/backend/app/scripts/link_catalog_to_mdm.py
import asyncio
from sqlalchemy import select, update
from app.db.session import SessionLocal
from app.models import AssetCatalog
from app.models import VehicleModelDefinition, VehicleType

async def link_catalog_to_mdm():
    """ Összefűzi a technikai katalógust a központi Master Definíciókkal. """
    async with SessionLocal() as db:
        try:
            print("🔍 Master-Híd építése indul...")
            
            # 1. Típusok betöltése
            type_res = await db.execute(select(VehicleType))
            types = {t.code: t.id for t in type_res.scalars().all()}

            # 2. Egyedi variánsok lekérése
            stmt = select(AssetCatalog.make, AssetCatalog.model, AssetCatalog.vehicle_class).distinct()
            raw_data = await db.execute(stmt)
            unique_models = raw_data.all()

            linked_count = 0
            for make, model, v_class in unique_models:
                t_code = v_class if v_class in types else "car"
                t_id = types.get(t_code)

                # Master rekord keresése vagy létrehozása
                master_stmt = select(VehicleModelDefinition).where(
                    VehicleModelDefinition.make == make,
                    VehicleModelDefinition.marketing_name == model
                )
                master = (await db.execute(master_stmt)).scalar_one_or_none()

                if not master:
                    master = VehicleModelDefinition(
                        make=make,
                        technical_code=model.replace(" ", "-").lower(),
                        marketing_name=model,
                        vehicle_type=t_code,
                        vehicle_type_id=t_id,
                        status="unverified",
                        source="linking_process"
                    )
                    db.add(master)
                    await db.flush()

                # Összekötés
                await db.execute(
                    update(AssetCatalog)
                    .where(AssetCatalog.make == make, AssetCatalog.model == model)
                    .values(master_definition_id=master.id)
                )
                linked_count += 1

            await db.commit()
            print(f"✅ Sikeresen összekötve: {linked_count} modell.")
        except Exception as e:
            await db.rollback()
            print(f"❌ Hiba: {e}")

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