"""admin 看广告金币审计:只读对账,核对发奖金币是否按公式计算。

任意已登录 admin 可看(只读,不涉及资金操作)。复算逻辑在 app/admin/repositories/ad_audit.py。
"""
from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, Query

from app.admin.deps import AdminDb, get_current_admin
from app.admin.repositories import ad_audit
from app.admin.schemas.ad_audit import AdCoinAuditOut, AdCoinAuditRow, AdCoinFormulaOut
from app.core.rewards import cn_today

router = APIRouter(
    prefix="/admin/api/ad-coin-audit",
    tags=["admin-ad-coin-audit"],
    dependencies=[Depends(get_current_admin)],
)


@router.get("", response_model=AdCoinAuditOut, summary="看广告金币公式审计(复算对比)")
def get_ad_coin_audit(
    db: AdminDb,
    date: Annotated[str | None, Query(description="北京时间 YYYY-MM-DD,默认今天")] = None,
    user_id: Annotated[int | None, Query(description="只看某用户;不传=全部用户")] = None,
    scene: Annotated[
        str | None, Query(description="reward_video / feed / draw;不传=全部")
    ] = None,
    limit: Annotated[int, Query(ge=1, le=500)] = 100,
    only_mismatch: Annotated[
        bool, Query(description="只看不一致(✗)行;统计数仍按全量,不受影响")
    ] = False,
) -> AdCoinAuditOut:
    audit_date = date or cn_today().isoformat()
    result = ad_audit.ad_coin_audit(
        db, date=audit_date, user_id=user_id, scene=scene, limit=limit,
        only_mismatch=only_mismatch,
    )
    return AdCoinAuditOut(
        date=audit_date,
        formula=AdCoinFormulaOut(**ad_audit.formula_snapshot()),
        total=result["total"],
        mismatch_count=result["mismatch_count"],
        truncated=result["truncated"],
        items=[AdCoinAuditRow(**r) for r in result["items"]],
    )
