from typing import Any

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from . import models, schemas
from ..auth import dependencies, models as auth_models

router = APIRouter()


@router.get("/me", response_model=schemas.Profile)
def read_profile_me(
    db: Session = Depends(dependencies.get_db),
    current_user: auth_models.User = Depends(dependencies.get_current_active_user),
) -> Any:
    """Get my profile."""
    profile = db.query(models.Profile).filter(models.Profile.user_id == current_user.id).first()
    if not profile:
        raise HTTPException(status_code=404, detail="Profile not found")
    return profile


@router.put("/me", response_model=schemas.Profile)
def update_profile_me(
    *,
    db: Session = Depends(dependencies.get_db),
    profile_in: schemas.ProfileUpdate,
    current_user: auth_models.User = Depends(dependencies.get_current_active_user),
) -> Any:
    """Update my profile."""
    profile = db.query(models.Profile).filter(models.Profile.user_id == current_user.id).first()
    if not profile:
        profile = models.Profile(user_id=current_user.id)
        db.add(profile)
    
    update_data = profile_in.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(profile, field, value)
    
    db.commit()
    db.refresh(profile)
    return profile
