from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import List

from app.db.session import get_db
from app.api import deps
from app.models.user import User, UserRole
from app.models.system_settings import SystemSetting  # ÚJ import
from app.models.gamification import PointRule, LevelConfig, RegionalSetting
from app.models.translation import Translation
from app.services.translation_service import TranslationService

router = APIRouter()

def check_admin_access(current_user: User, required_roles: List[UserRole]):
    if current_user.role not in required_roles:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Nincs jogosultságod ehhez a művelethez."
        )

# --- ⚙️ ÚJ: DINAMIKUS RENDSZERBEÁLLÍTÁSOK (Pl. Jármű limit) ---

@router.get("/settings", response_model=List[dict])
async def get_all_system_settings(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(deps.get_current_user)
):
    """Az összes globális rendszerbeállítás listázása."""
    check_admin_access(current_user, [UserRole.SUPERUSER])
    result = await db.execute(select(SystemSetting))
    settings = result.scalars().all()
    return [{"key": s.key, "value": s.value, "description": s.description} for s in settings]

@router.put("/settings/{key}")
async def update_system_setting(
    key: str, 
    new_value: int, # Később lehet JSON is, ha komplexebb a beállítás
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(deps.get_current_user)
):
    """Egy adott beállítás (pl. FREE_VEHICLE_LIMIT) módosítása."""
    check_admin_access(current_user, [UserRole.SUPERUSER])
    
    result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
    setting = result.scalar_one_or_none()
    
    if not setting:
        raise HTTPException(status_code=404, detail="Beállítás nem található")
    
    setting.value = new_value
    await db.commit()
    return {"status": "success", "key": key, "new_value": new_value}


# --- 🌍 FORDÍTÁSOK KEZELÉSE (Meglévő kódod) ---

@router.post("/translations", status_code=status.HTTP_201_CREATED)
async def add_translation_draft(
    key: str, lang: str, value: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(deps.get_current_user)
):
    check_admin_access(current_user, [UserRole.SUPERUSER, UserRole.REGIONAL_ADMIN])
    new_t = Translation(key=key, lang_code=lang, value=value, is_published=False)
    db.add(new_t)
    await db.commit()
    return {"message": "Fordítás piszkozatként mentve. Ne felejtsd el publikálni!"}

@router.post("/translations/publish")
async def publish_translations(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(deps.get_current_user)
):
    check_admin_access(current_user, [UserRole.SUPERUSER, UserRole.REGIONAL_ADMIN])
    await TranslationService.publish_all(db)
    return {"message": "Sikeres publikálás! A változások minden szerveren élesedtek."}
    