"""比价战绩里程碑 endpoint(福利页「记录比价战绩」)。

路由前缀 `/api/v1/compare`:
  GET  /milestones                进度与各档领取状态
  POST /milestones/{milestone}/claim  领取某档奖励

**均需鉴权**。解锁进度 = 该用户 status='success' 的 comparison_record 条数;每档领一次。
"""
from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, status

from app.api.deps import CurrentUser, DbSession
from app.repositories import comparison_milestone as crud_milestone
from app.schemas.compare_record import (
    MilestoneClaimResultOut,
    MilestoneStateOut,
    MilestoneStatusOut,
)

logger = logging.getLogger("shagua.compare_milestone")

router = APIRouter(prefix="/api/v1/compare", tags=["compare-milestone"])


@router.get(
    "/milestones",
    response_model=MilestoneStatusOut,
    summary="比价战绩里程碑进度",
)
def get_milestones(user: CurrentUser, db: DbSession) -> MilestoneStatusOut:
    st = crud_milestone.get_status(db, user.id)
    return MilestoneStatusOut(
        success_count=st.success_count,
        claimable_count=st.claimable_count,
        milestones=[
            MilestoneStateOut(milestone=m.milestone, coin=m.coin, state=m.state)
            for m in st.milestones
        ],
    )


@router.post(
    "/milestones/{milestone}/claim",
    response_model=MilestoneClaimResultOut,
    summary="领取比价战绩里程碑奖励",
)
def claim_milestone(
    milestone: int, user: CurrentUser, db: DbSession
) -> MilestoneClaimResultOut:
    try:
        coin, balance = crud_milestone.claim(db, user.id, milestone)
    except crud_milestone.UnknownMilestoneError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="unknown milestone"
        ) from e
    except crud_milestone.MilestoneLockedError as e:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT, detail="milestone locked"
        ) from e
    except crud_milestone.AlreadyClaimedError as e:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT, detail="milestone already claimed"
        ) from e

    logger.info(
        "compare milestone claimed user_id=%d milestone=%d coin=%d",
        user.id,
        milestone,
        coin,
    )
    return MilestoneClaimResultOut(
        milestone=milestone, coin_awarded=coin, coin_balance=balance
    )
