import psycopg2
from psycopg2.extras import RealDictCursor
import os
from dotenv import load_dotenv

load_dotenv()

def get_connection():
    db_host = os.getenv("POSTGRES_HOST", "localhost")
    if db_host == "postgres-db":
        db_host = "localhost"
    
    return psycopg2.connect(
        dbname=os.getenv("POSTGRES_DB", "service_finder"),
        user=os.getenv("POSTGRES_USER", "kincses"),
        password=os.getenv("POSTGRES_PASSWORD", "PASSWORD"),
        host=db_host,
        port=os.getenv("POSTGRES_PORT", "5432")
    )

def seed_system():
    conn = None
    try:
        conn = get_connection()
        cur = conn.cursor(cursor_factory=RealDictCursor)
        print("🚀 Kapcsolat aktív. Adatok szinkronizálása...")

        # 1. MÁRKÁK SZINKRONIZÁLÁSA
        brands = [
            {'name': 'Volkswagen', 'slug': 'volkswagen', 'origin': 'Germany'},
            {'name': 'Audi', 'slug': 'audi', 'origin': 'Germany'},
            {'name': 'BMW', 'slug': 'bmw', 'origin': 'Germany'},
            {'name': 'Skoda', 'slug': 'skoda', 'origin': 'Czech Republic'},
            {'name': 'Toyota', 'slug': 'toyota', 'origin': 'Japan'}
        ]

        for b in brands:
            # Megnézzük, létezik-e már
            cur.execute("SELECT id FROM data.vehicle_brands WHERE name = %s", (b['name'],))
            row = cur.fetchone()
            
            if row:
                # Frissítés (Update), ha már létezik
                cur.execute("""
                    UPDATE data.vehicle_brands 
                    SET slug = COALESCE(slug, %s), 
                        country_of_origin = %s 
                    WHERE id = %s
                """, (b['slug'], b['origin'], row['id']))
            else:
                # Beszúrás (Insert), ha új
                cur.execute("""
                    INSERT INTO data.vehicle_brands (name, slug, country_of_origin)
                    VALUES (%s, %s, %s)
                """, (b['name'], b['slug'], b['origin']))

        # 2. MOTOROK SZINKRONIZÁLÁSA
        engines = [
            ('CAGA', 'diesel', 105, 15000),
            ('DADA', 'petrol', 110, 30000),
            ('B47D20', 'diesel', 140, 25000)
        ]
        
        for code, fuel, kw, interval in engines:
            cur.execute("SELECT id FROM data.engine_specs WHERE engine_code = %s", (code,))
            if not cur.fetchone():
                cur.execute("""
                    INSERT INTO data.engine_specs (engine_code, fuel_type, power_kw, default_service_interval_km)
                    VALUES (%s, %s, %s, %s)
                """, (code, fuel, kw, interval))

        conn.commit()
        print("✅ Szinkronizálás sikeres! Az adatbázis naprakész.")

    except Exception as e:
        print(f"❌ Hiba: {e}")
        if conn: conn.rollback()
    finally:
        if conn: conn.close()

if __name__ == "__main__":
    seed_system()