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

from app.database import get_db
from app.models import Player

router = APIRouter(prefix="/ranks", tags=["ranks"])

# Mirrors RANK_DATA in spacewar/menu/main_menu.gd — keep the tier names (and
# ideally thresholds) in sync if either side changes.
_TIERS: list[tuple[int, str]] = [
    (0, "CADET"),
    (1000, "PILOT"),
    (1400, "ACE"),
    (1800, "COMMANDER"),
    (2200, "ADMIRAL"),
    (2600, "LEGEND"),
]


def _tier_for(mmr: int) -> str:
    tier = _TIERS[0][1]
    for threshold, name in _TIERS:
        if mmr >= threshold:
            tier = name
    return tier


@router.get("/{callsign}")
async def get_rank(callsign: str, db: AsyncSession = Depends(get_db)) -> dict:
    player = (await db.execute(select(Player).where(Player.callsign == callsign))).scalars().first()
    if player is None:
        raise HTTPException(status_code=404, detail="Player not found")
    return {"callsign": player.callsign, "mmr": player.mmr, "rank": _tier_for(player.mmr)}
