from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.schemas.user import UserResponse, UserUpdate, UserStats
from app.routers.auth import get_current_user
from app.crud.user import get_user_by_id
from app.crud.bet import get_user_bets
from app.models import User, BetStatus
from app.utils.exceptions import UserNotFoundError

router = APIRouter(prefix="/api/v1/users", tags=["users"])


@router.get("/{user_id}", response_model=UserResponse)
async def get_user(
    user_id: int,
    db: AsyncSession = Depends(get_db)
):
    user = await get_user_by_id(db, user_id)
    if not user:
        raise UserNotFoundError()
    return user


@router.put("/me", response_model=UserResponse)
async def update_current_user(
    user_data: UserUpdate,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    if user_data.display_name is not None:
        current_user.display_name = user_data.display_name
    if user_data.avatar_url is not None:
        current_user.avatar_url = user_data.avatar_url
    if user_data.bio is not None:
        current_user.bio = user_data.bio

    await db.commit()
    await db.refresh(current_user)
    return current_user


@router.get("/{user_id}/stats", response_model=UserStats)
async def get_user_stats(
    user_id: int,
    db: AsyncSession = Depends(get_db)
):
    user = await get_user_by_id(db, user_id)
    if not user:
        raise UserNotFoundError()

    # Get active bets count
    user_bets = await get_user_bets(db, user_id)
    active_bets = sum(1 for bet in user_bets if bet.status in [BetStatus.MATCHED, BetStatus.IN_PROGRESS])

    return UserStats(
        total_bets=user.total_bets,
        wins=user.wins,
        losses=user.losses,
        win_rate=user.win_rate,
        active_bets=active_bets,
    )
