#/opt/docker/dev/service_finder/backend/app/api/v1/endpoints/users.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Dict, Any

from app.api.deps import get_db, get_current_user
from app.schemas.user import UserResponse, UserUpdate
from app.models.identity import User
from app.services.trust_engine import TrustEngine

router = APIRouter()
trust_engine = TrustEngine()

@router.get("/me", response_model=UserResponse)
async def read_users_me(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """Visszaadja a bejelentkezett felhasználó profilját"""
    return current_user

@router.get("/me/trust")
async def get_user_trust(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    force_recalculate: bool = False,
) -> Dict[str, Any]:
    """
    Visszaadja a felhasználó Gondos Gazda Index (Trust Score) értékét.
    
    A számítás dinamikusan betölti a paramétereket a SystemParameter rendszerből
    (Global/Country/Region/User hierarchia).
    
    Paraméterek:
    - force_recalculate: Ha True, akkor újraszámolja a trust score-t
      (alapértelmezetten cache-elt értéket ad vissza, ha kevesebb mint 24 órája számoltuk)
    """
    trust_data = await trust_engine.calculate_user_trust(
        db=db,
        user_id=current_user.id,
        force_recalculate=force_recalculate
    )
    return trust_data


@router.patch("/me/preferences", response_model=UserResponse)
async def update_user_preferences(
    update_data: UserUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """
    Update user preferences (ui_mode, preferred_language, etc.)
    """
    # Filter out None values
    update_dict = update_data.dict(exclude_unset=True)
    if not update_dict:
        raise HTTPException(status_code=400, detail="No fields to update")
    
    # Validate ui_mode if present
    if "ui_mode" in update_dict:
        if update_dict["ui_mode"] not in ["personal", "fleet"]:
            raise HTTPException(status_code=422, detail="ui_mode must be 'personal' or 'fleet'")
    
    # Update user fields
    for field, value in update_dict.items():
        if hasattr(current_user, field):
            setattr(current_user, field, value)
        else:
            raise HTTPException(status_code=400, detail=f"Invalid field: {field}")
    
    await db.commit()
    await db.refresh(current_user)
    return current_user
