#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations


import database
from flask import jsonify, request
from routes.admin_api import admin_api_bp
from routes.decorators import admin_required
from services.state import safe_clear_user_logs, safe_remove_user_accounts


# ==================== 用户管理/统计（管理员） ====================


def _parse_optional_pagination(default_limit: int = 50, max_limit: int = 500) -> tuple[int | None, int]:
    limit_raw = request.args.get("limit")
    offset_raw = request.args.get("offset")
    if (limit_raw is None) and (offset_raw is None):
        return None, 0

    try:
        limit = int(limit_raw if limit_raw is not None else default_limit)
    except (TypeError, ValueError):
        limit = default_limit
    limit = max(1, min(limit, max_limit))

    try:
        offset = int(offset_raw if offset_raw is not None else 0)
    except (TypeError, ValueError):
        offset = 0
    offset = max(0, offset)
    return limit, offset


@admin_api_bp.route("/users", methods=["GET"])
@admin_required
def get_all_users():
    """获取所有用户"""
    limit, offset = _parse_optional_pagination()
    if limit is None:
        users = database.get_all_users()
        return jsonify(users)

    users = database.get_all_users(limit=limit, offset=offset)
    total = database.get_users_count()
    return jsonify({"items": users, "total": total, "limit": limit, "offset": offset})


@admin_api_bp.route("/users/pending", methods=["GET"])
@admin_required
def get_pending_users():
    """获取待审核用户"""
    limit, offset = _parse_optional_pagination(default_limit=30, max_limit=200)
    if limit is None:
        users = database.get_pending_users()
        return jsonify(users)

    users = database.get_pending_users(limit=limit, offset=offset)
    total = database.get_users_count(status="pending")
    return jsonify({"items": users, "total": total, "limit": limit, "offset": offset})


@admin_api_bp.route("/users/<int:user_id>/approve", methods=["POST"])
@admin_required
def approve_user_route(user_id):
    """审核通过用户"""
    if database.approve_user(user_id):
        return jsonify({"success": True})
    return jsonify({"error": "审核失败"}), 400


@admin_api_bp.route("/users/<int:user_id>/reject", methods=["POST"])
@admin_required
def reject_user_route(user_id):
    """拒绝用户"""
    if database.reject_user(user_id):
        return jsonify({"success": True})
    return jsonify({"error": "拒绝失败"}), 400


@admin_api_bp.route("/users/<int:user_id>", methods=["DELETE"])
@admin_required
def delete_user_route(user_id):
    """删除用户"""
    if database.delete_user(user_id):
        safe_remove_user_accounts(user_id)
        safe_clear_user_logs(user_id)
        return jsonify({"success": True})
    return jsonify({"error": "删除失败"}), 400


# ==================== VIP 管理（管理员） ====================


@admin_api_bp.route("/vip/config", methods=["GET"])
@admin_required
def get_vip_config_api():
    """获取VIP配置"""
    config = database.get_vip_config()
    return jsonify(config)


@admin_api_bp.route("/vip/config", methods=["POST"])
@admin_required
def set_vip_config_api():
    """设置默认VIP天数"""
    data = request.json or {}
    days = data.get("default_vip_days", 0)

    if not isinstance(days, int) or days < 0:
        return jsonify({"error": "VIP天数必须是非负整数"}), 400

    database.set_default_vip_days(days)
    return jsonify({"message": "VIP配置已更新", "default_vip_days": days})


@admin_api_bp.route("/users/<int:user_id>/vip", methods=["POST"])
@admin_required
def set_user_vip_api(user_id):
    """设置用户VIP"""
    data = request.json or {}
    days = data.get("days", 30)

    valid_days = [7, 30, 365, 999999]
    if days not in valid_days:
        return jsonify({"error": "VIP天数必须是 7/30/365/999999 之一"}), 400

    if database.set_user_vip(user_id, days):
        vip_type = {7: "一周", 30: "一个月", 365: "一年", 999999: "永久"}[days]
        return jsonify({"message": f"VIP设置成功: {vip_type}"})
    return jsonify({"error": "设置失败,用户不存在"}), 400


@admin_api_bp.route("/users/<int:user_id>/vip", methods=["DELETE"])
@admin_required
def remove_user_vip_api(user_id):
    """移除用户VIP"""
    if database.remove_user_vip(user_id):
        return jsonify({"message": "VIP已移除"})
    return jsonify({"error": "移除失败"}), 400


@admin_api_bp.route("/users/<int:user_id>/vip", methods=["GET"])
@admin_required
def get_user_vip_info_api(user_id):
    """获取用户VIP信息(管理员)"""
    vip_info = database.get_user_vip_info(user_id)
    return jsonify(vip_info)
