import asyncio
import os
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
from dotenv import load_dotenv

load_dotenv()

# Cím összeállítása (Ugyanaz a logika, mint a main.py-ban)
raw_url = os.getenv("DATABASE_URL")
if not raw_url:
    raw_url = "postgresql://admin:PASSWORD_111@postgres-db:5432/service_finder"
DATABASE_URL = raw_url.replace("postgresql://", "postgresql+asyncpg://").replace("/service_finder_db", "/service_finder")

async def init_db():
    print(f"🔌 Kapcsolódás ide: {DATABASE_URL}")
    engine = create_async_engine(DATABASE_URL)

    async with engine.begin() as conn:
        print("🏗️  Séma és Táblák létrehozása...")
        
        # 1. Séma létrehozása
        await conn.execute(text("CREATE SCHEMA IF NOT EXISTS ref;"))
        
        # 2. Márka tábla
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS ref.vehicle_makes (
                id SERIAL PRIMARY KEY,
                name VARCHAR(100) NOT NULL UNIQUE
            );
        """))
        
        # 3. Modell tábla
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS ref.vehicle_models (
                id SERIAL PRIMARY KEY,
                make_id INTEGER REFERENCES ref.vehicle_makes(id),
                model_name VARCHAR(100) NOT NULL,
                category VARCHAR(50)
            );
        """))

        print("🧹 Meglévő adatok törlése (Tiszta lap)...")
        await conn.execute(text("TRUNCATE TABLE ref.vehicle_models, ref.vehicle_makes RESTART IDENTITY CASCADE;"))

        print("🚗 Adatok beszúrása...")
        
        # Adatok
        makes = ["BMW", "Audi", "Mercedes-Benz", "Toyota", "Honda", "Suzuki", "Volkswagen"]
        
        models = [
            ("BMW", "3 Series", "Autó"), ("BMW", "5 Series", "Autó"), ("BMW", "X5", "Autó"), ("BMW", "R 1250 GS", "Motor"),
            ("Audi", "A3", "Autó"), ("Audi", "A4", "Autó"), ("Audi", "A6", "Autó"), ("Audi", "Q5", "Autó"),
            ("Mercedes-Benz", "C-Class", "Autó"), ("Mercedes-Benz", "E-Class", "Autó"), ("Mercedes-Benz", "S-Class", "Autó"), ("Mercedes-Benz", "G-Class", "Autó"),
            ("Toyota", "Corolla", "Autó"), ("Toyota", "Yaris", "Autó"), ("Toyota", "RAV4", "Autó"), ("Toyota", "Hilux", "Autó"),
            ("Honda", "Civic", "Autó"), ("Honda", "CR-V", "Autó"), ("Honda", "Africa Twin", "Motor"), ("Honda", "CB500X", "Motor"),
            ("Suzuki", "Swift", "Autó"), ("Suzuki", "Vitara", "Autó"), ("Suzuki", "S-Cross", "Autó"), ("Suzuki", "DL 650 V-Strom", "Motor"),
            ("Volkswagen", "Golf", "Autó"), ("Volkswagen", "Passat", "Autó"), ("Volkswagen", "Polo", "Autó"), ("Volkswagen", "Tiguan", "Autó")
        ]

        # Márkák beszúrása
        for make in makes:
            await conn.execute(text(f"INSERT INTO ref.vehicle_makes (name) VALUES ('{make}') ON CONFLICT DO NOTHING;"))
        
        # Modellek beszúrása (kicsit trükkös, mert kell a make_id)
        for brand, model, cat in models:
            # Megkeressük az ID-t
            result = await conn.execute(text(f"SELECT id FROM ref.vehicle_makes WHERE name = '{brand}'"))
            make_id = result.scalar()
            
            # Beszúrjuk a modellt
            await conn.execute(text(f"""
                INSERT INTO ref.vehicle_models (make_id, model_name, category) 
                VALUES ({make_id}, '{model}', '{cat}')
            """))

    print("✅ KÉSZ! Az adatbázis feltöltve.")
    await engine.dispose()

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