from fastapi import FastAPI
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import text
import os
from dotenv import load_dotenv

load_dotenv()

app = FastAPI(title="Service Finder API")

# --- A DUPLA JAVÍTÁS ---
raw_url = os.getenv("DATABASE_URL")

if not raw_url:
    # Vészhelyzeti fallback (ha nem lenne .env)
    raw_url = "postgresql://admin:PASSWORD_111@postgres-db:5432/service_finder"

# 1. Javítás: Driver csere (asyncpg)
fixed_url = raw_url.replace("postgresql://", "postgresql+asyncpg://")

# 2. Javítás: Adatbázis név csere (Ha véletlenül _db a vége, levágjuk)
fixed_url = fixed_url.replace("/service_finder_db", "/service_finder")

print(f"🔧 VÉGLEGES ADATBÁZIS CÍM: {fixed_url}")

# Kapcsolódás a javított címmel
engine = create_async_engine(fixed_url)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

@app.get("/")
async def root():
    return {"message": "Service Finder API működik! 🚀"}

@app.get("/vehicles")
async def get_vehicles():
    async with AsyncSessionLocal() as session:
        try:
            query = text("""
                SELECT m.name as brand, vm.model_name, vm.category 
                FROM ref.vehicle_models vm 
                JOIN ref.vehicle_makes m ON vm.make_id = m.id
                ORDER BY m.name, vm.model_name
            """)
            result = await session.execute(query)
            vehicles = result.fetchall()
            return [{"brand": r.brand, "model": r.model_name, "category": r.category} for r in vehicles]
        except Exception as e:
            return {"error": str(e)}
