"""admin 用户管理:列表 + 360 详情(读)+ 封禁/解封 + 手动调金币(写,带审计)。"""
from __future__ import annotations

from datetime import datetime
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query, Request

from app.admin.audit import write_audit
from app.admin.deps import AdminDb, get_client_ip, get_current_admin, require_role
from app.admin.repositories import mutations, queries
from app.admin.schemas.common import CursorPage, OkResponse
from app.admin.schemas.user import (
    AdminUserListItem,
    AdminUserOverview,
    GrantCashRequest,
    GrantCoinsRequest,
    SetDebugTraceRequest,
    SetUserRiskRequest,
    SetUserStatusRequest,
    UserCoinRecord,
    UserRewardStats,
)
from app.models.admin import AdminUser
from app.repositories import user as user_repo
from app.repositories import wallet as wallet_repo

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


@router.get("", response_model=CursorPage[AdminUserListItem], summary="用户列表(筛选+排序+分页)")
def list_users(
    db: AdminDb,
    phone: Annotated[str | None, Query()] = None,
    register_channel: Annotated[str | None, Query()] = None,
    status: Annotated[str | None, Query()] = None,
    nickname: Annotated[str | None, Query(max_length=100)] = None,
    created_from: Annotated[datetime | None, Query()] = None,
    created_to: Annotated[datetime | None, Query()] = None,
    last_login_from: Annotated[datetime | None, Query()] = None,
    last_login_to: Annotated[datetime | None, Query()] = None,
    # 最近活跃(登录/发起比价/发起领券取最大,见 queries._last_active_expr)筛选与排序
    last_active_from: Annotated[datetime | None, Query()] = None,
    last_active_to: Annotated[datetime | None, Query()] = None,
    sort_by: Annotated[
        str, Query(pattern="^(id|created_at|last_login_at|last_active_at)$")
    ] = "id",
    sort_order: Annotated[str, Query(pattern="^(asc|desc)$")] = "desc",
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    cursor: Annotated[int | None, Query()] = None,
) -> CursorPage[AdminUserListItem]:
    items, next_cursor, total = queries.list_users(
        db, phone=phone, register_channel=register_channel, status=status,
        nickname=nickname, created_from=created_from, created_to=created_to,
        last_login_from=last_login_from, last_login_to=last_login_to,
        last_active_from=last_active_from, last_active_to=last_active_to,
        sort_by=sort_by, sort_order=sort_order, limit=limit, cursor=cursor,
    )
    return CursorPage(
        items=[AdminUserListItem.model_validate(u) for u in items],
        next_cursor=next_cursor,
        total=total,
    )


@router.get("/{user_id}", response_model=AdminUserOverview, summary="用户 360 详情")
def get_user(user_id: int, db: AdminDb) -> AdminUserOverview:
    overview = queries.get_user_overview(db, user_id)
    if overview is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    return AdminUserOverview.model_validate(overview)


@router.get(
    "/{user_id}/reward-stats",
    response_model=UserRewardStats,
    summary="用户提现/看广告统计(提现详情用,按时间窗口)",
)
def get_user_reward_stats(
    user_id: int,
    db: AdminDb,
    date_from: Annotated[datetime | None, Query()] = None,
    date_to: Annotated[datetime | None, Query()] = None,
    withdraw_source: Annotated[
        str | None, Query(pattern="^(coin_cash|invite_cash)$")
    ] = None,
    app_env: Annotated[str | None, Query(pattern="^(prod|test)$")] = None,
    revenue_scope: Annotated[str, Query(pattern="^(business|all)$")] = "all",
    feed_scene: Annotated[
        str | None, Query(pattern="^(comparison|coupon|welfare)$")
    ] = None,
) -> UserRewardStats:
    """提现详情抽屉「用户统计区」。date_from/date_to 都不传 = 注册至今(全量)。"""
    if not user_repo.user_exists(db, user_id):
        raise HTTPException(status_code=404, detail="用户不存在")
    return UserRewardStats(
        **queries.user_reward_stats(
            db,
            user_id,
            date_from=date_from,
            date_to=date_to,
            withdraw_source=withdraw_source,
            app_env=app_env,
            revenue_scope=revenue_scope,
            feed_scene=feed_scene,
        )
    )


@router.get(
    "/{user_id}/coin-records",
    response_model=CursorPage[UserCoinRecord],
    summary="用户金币发放记录(提现详情底部表,按时间窗口分页)",
)
def get_user_coin_records(
    user_id: int,
    db: AdminDb,
    date_from: Annotated[datetime | None, Query()] = None,
    date_to: Annotated[datetime | None, Query()] = None,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    cursor: Annotated[int | None, Query()] = None,
) -> CursorPage[UserCoinRecord]:
    items, next_cursor, total = queries.user_coin_records(
        db, user_id, date_from=date_from, date_to=date_to, limit=limit, cursor=cursor,
    )
    return CursorPage(
        items=[UserCoinRecord(**r) for r in items], next_cursor=next_cursor, total=total,
    )


@router.post("/{user_id}/status", response_model=OkResponse, summary="封禁/解封用户")
def set_user_status(
    user_id: int,
    body: SetUserStatusRequest,
    request: Request,
    admin: Annotated[AdminUser, Depends(require_role("operator"))],
    db: AdminDb,
) -> OkResponse:
    user = user_repo.get_user_by_id(db, user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    if user.status == "deleted":
        raise HTTPException(status_code=400, detail="已注销账号不可改状态")
    before = user.status
    # 业务写 + 审计写同一事务(commit=False),最后一起 commit:改了就有痕、有痕就真改了
    mutations.set_user_status(db, user, status=body.status, commit=False)
    write_audit(
        db, admin, action="user.status.set", target_type="user", target_id=user_id,
        detail={"before": before, "after": body.status}, ip=get_client_ip(request), commit=False,
    )
    db.commit()
    return OkResponse()


@router.post("/{user_id}/risk", response_model=OkResponse, summary="设置人工高风险标记与备注")
def set_user_risk(
    user_id: int,
    body: SetUserRiskRequest,
    request: Request,
    admin: Annotated[
        AdminUser, Depends(require_role("operator", "finance"))
    ],
    db: AdminDb,
) -> OkResponse:
    user = user_repo.get_user_by_id(db, user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    before = {
        "is_high_risk": user.is_high_risk,
        "high_risk_note": user.high_risk_note,
    }
    mutations.set_user_risk(
        db,
        user,
        is_high_risk=body.is_high_risk,
        note=body.note,
        commit=False,
    )
    write_audit(
        db,
        admin,
        action="user.risk.set",
        target_type="user",
        target_id=user_id,
        detail={
            "before": before,
            "after": {
                "is_high_risk": user.is_high_risk,
                "high_risk_note": user.high_risk_note,
            },
        },
        ip=get_client_ip(request),
        commit=False,
    )
    db.commit()
    return OkResponse()


@router.post("/{user_id}/debug-trace", response_model=OkResponse, summary="开关调试链接权限")
def set_user_debug_trace(
    user_id: int,
    body: SetDebugTraceRequest,
    request: Request,
    admin: Annotated[AdminUser, Depends(require_role("operator"))],
    db: AdminDb,
) -> OkResponse:
    user = user_repo.get_user_by_id(db, user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    before = user.debug_trace_enabled
    # 业务写 + 审计写同一事务(commit=False),最后一起 commit(同 set_user_status)
    mutations.set_user_debug_trace(db, user, enabled=body.enabled, commit=False)
    write_audit(
        db, admin, action="user.debug_trace.set", target_type="user", target_id=user_id,
        detail={"before": before, "after": body.enabled}, ip=get_client_ip(request), commit=False,
    )
    db.commit()
    return OkResponse()


@router.post("/{user_id}/coins", response_model=OkResponse, summary="手动增减/设值金币(带审计)")
def grant_user_coins(
    user_id: int,
    body: GrantCoinsRequest,
    request: Request,
    admin: Annotated[AdminUser, Depends(require_role("finance"))],
    db: AdminDb,
) -> OkResponse:
    user = user_repo.get_user_by_id(db, user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    # set=设为目标值:读当前余额算出要写的差值,仍复用 grant_coins 写一笔流水(沿用原子/审计/扣负保护)
    if body.mode == "set":
        if body.amount < 0:
            raise HTTPException(status_code=400, detail="目标金币值不能为负")
        # lock=True:锁账户行,防连点/并发各读同一 before 算同一 delta 双写,余额错位
        before = wallet_repo.get_or_create_account(db, user_id, commit=False, lock=True).coin_balance
        delta = body.amount - before
        if delta == 0:
            raise HTTPException(status_code=400, detail=f"当前金币已为 {body.amount},无需调整")
    else:
        if body.amount == 0:
            raise HTTPException(status_code=400, detail="amount 不能为 0")
        delta = body.amount
        # 负数扣减时不允许扣成负余额(运营误操作保护);lock=True 防并发扣穿
        if delta < 0:
            acc_now = wallet_repo.get_or_create_account(db, user_id, commit=False, lock=True)
            if acc_now.coin_balance + delta < 0:
                raise HTTPException(
                    status_code=400, detail=f"扣减后金币为负(当前余额 {acc_now.coin_balance})"
                )
    biz_type = "admin_grant" if delta > 0 else "admin_deduct"
    # grant_coins 只 flush 不 commit;审计同 commit=False;最后一起 commit → 原子(改钱+留痕)
    acc, _ = wallet_repo.grant_coins(
        db, user_id, delta, biz_type=biz_type, remark=f"admin:{body.reason}"[:128],
    )
    detail = {"amount": delta, "balance_after": acc.coin_balance, "reason": body.reason}
    if body.mode == "set":
        detail.update({"mode": "set", "target": body.amount, "before": before})
    write_audit(
        db, admin, action="user.coins.grant", target_type="user", target_id=user_id,
        detail=detail, ip=get_client_ip(request), commit=False,
    )
    db.commit()
    return OkResponse()


@router.post("/{user_id}/cash", response_model=OkResponse, summary="手动增减/设值现金(带审计)")
def grant_user_cash(
    user_id: int,
    body: GrantCashRequest,
    request: Request,
    admin: Annotated[AdminUser, Depends(require_role("finance"))],
    db: AdminDb,
) -> OkResponse:
    """给指定用户增/减或设值现金(分)。delta:正=发放、负=扣减;set:直接设为目标值。
    account=coin_cash(金币兑现金)/ invite_cash(邀请奖励金):两本账物理隔离、各调各的。
    主要用于让无现金用户直接测试提现。"""
    user = user_repo.get_user_by_id(db, user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    # 按目标账户选「余额字段 + 变动入口」(grant_invite_cash 与 grant_cash 同构)
    is_invite = body.account == "invite_cash"
    balance_attr = "invite_cash_balance_cents" if is_invite else "cash_balance_cents"
    grant_fn = wallet_repo.grant_invite_cash if is_invite else wallet_repo.grant_cash
    acct_label = "邀请奖励金" if is_invite else "现金"
    before: int | None = None
    # set=设为目标值:读当前余额算差值,仍复用 grant 写一笔流水(沿用原子/审计/扣负保护)
    if body.mode == "set":
        if body.amount_cents < 0:
            raise HTTPException(status_code=400, detail=f"目标{acct_label}值不能为负")
        # lock=True:锁账户行,防连点/并发各读同一 before 算同一 delta 双写,余额错位
        acc_locked = wallet_repo.get_or_create_account(db, user_id, commit=False, lock=True)
        before = getattr(acc_locked, balance_attr)
        delta = body.amount_cents - before
        if delta == 0:
            raise HTTPException(
                status_code=400, detail=f"当前{acct_label}已为 {body.amount_cents} 分,无需调整"
            )
    else:
        if body.amount_cents == 0:
            raise HTTPException(status_code=400, detail="amount_cents 不能为 0")
        delta = body.amount_cents
        # 负数扣减时不允许扣成负余额(运营误操作保护);lock=True 防并发扣穿
        if delta < 0:
            acc_now = wallet_repo.get_or_create_account(db, user_id, commit=False, lock=True)
            if getattr(acc_now, balance_attr) + delta < 0:
                raise HTTPException(
                    status_code=400,
                    detail=f"扣减后{acct_label}为负(当前余额 {getattr(acc_now, balance_attr)} 分)",
                )
    biz_type = "admin_grant" if delta > 0 else "admin_deduct"
    # grant 只 flush 不 commit;审计同 commit=False;最后一起 commit → 原子(改钱+留痕)
    acc, _ = grant_fn(
        db, user_id, delta, biz_type=biz_type, remark=f"admin:{body.reason}"[:128],
    )
    detail = {
        "account": body.account,
        "amount_cents": delta,
        "balance_after_cents": getattr(acc, balance_attr),
        "reason": body.reason,
    }
    if body.mode == "set":
        detail.update({"mode": "set", "target_cents": body.amount_cents, "before_cents": before})
    write_audit(
        db, admin, action="user.cash.grant", target_type="user", target_id=user_id,
        detail=detail, ip=get_client_ip(request), commit=False,
    )
    db.commit()
    return OkResponse()
