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

from functools import wraps

from flask import jsonify, redirect, request, session, url_for

from services.runtime import get_logger


def admin_required(f):
    """管理员权限装饰器（不改变原有接口/行为）。"""

    @wraps(f)
    def decorated_function(*args, **kwargs):
        try:
            logger = get_logger()
        except Exception:
            import logging

            logger = logging.getLogger("app")
        logger.debug(f"[admin_required] 检查会话，admin_id存在: {'admin_id' in session}")
        if "admin_id" not in session:
            logger.warning(f"[admin_required] 拒绝访问 {request.path} - session中无admin_id")
            is_api = (
                request.blueprint in {"admin_api", "admin_security", "admin_security_yuyx"}
                or request.path.startswith("/yuyx/api")
                or request.path.startswith("/api/admin")
            )
            if is_api:
                return jsonify({"error": "需要管理员权限"}), 403
            return redirect(url_for("pages.admin_login_page"))
        logger.debug(f"[admin_required] 管理员 {session.get('admin_username')} 访问 {request.path}")
        return f(*args, **kwargs)

    return decorated_function
