from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session
from typing import List, Dict, Any

from ..database import get_db
from ..models import SystemConfig
from ..schemas import SystemConfigBase, SystemConfigResponse

router = APIRouter(prefix="/api/admin/systemconfigs", tags=["admin"])

def get_current_admin(request: Request, db: Session = Depends(get_db)):
    """依赖项：验证管理员权限"""
    from .auth import verify_token
    auth_header = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="未提供认证令牌")
    token = auth_header.split(" ")[1]
    user = verify_token(token, db)
    if user.role != "admin":
        raise HTTPException(status_code=403, detail="需要管理员权限")
    return user

@router.get("", response_model=List[SystemConfigResponse])
def list_system_configs(
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """获取所有系统配置（键值对列表）"""
    configs = db.query(SystemConfig).all()
    # 将 value 解析为 JSON（如果是 JSON 字符串）
    result = []
    for c in configs:
        resp = SystemConfigResponse.model_validate(c)
        # 尝试解析 value 为 JSON
        if c.value:
            try:
                import json
                resp.value = json.loads(c.value)
            except Exception:
                pass  # 保持原字符串
        result.append(resp)
    return result

@router.get("/{config_key}", response_model=SystemConfigResponse)
def get_system_config(
    config_key: str,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """获取单个系统配置"""
    config = db.query(SystemConfig).filter(SystemConfig.key == config_key).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
    resp = SystemConfigResponse.model_validate(config)
    if config.value:
        try:
            import json
            resp.value = json.loads(config.value)
        except Exception:
            pass
    return resp

@router.post("", response_model=SystemConfigResponse)
def create_system_config(
    config_data: SystemConfigBase,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """创建或更新系统配置（UPSERT）"""
    # key 是主键，如果已存在则更新
    existing = db.query(SystemConfig).filter(SystemConfig.key == config_data.key).first()
    if existing:
        # 若已存在，更新字段
        if config_data.value is not None:
            # 若 value 是 dict/list，转为 JSON 字符串存储
            if isinstance(config_data.value, (dict, list)):
                import json
                existing.value = json.dumps(config_data.value, ensure_ascii=False)
            else:
                existing.value = str(config_data.value)
        if config_data.description is not None:
            existing.description = config_data.description
        db.commit()
        db.refresh(existing)
        resp = SystemConfigResponse.model_validate(existing)
        if existing.value:
            try:
                import json
                resp.value = json.loads(existing.value)
            except Exception:
                pass
        return resp
    else:
        # 新建
        data = config_data.model_dump()
        # 将 value 转为字符串（如果是复杂类型则 JSON）
        if isinstance(data.get('value'), (dict, list)):
            import json
            data['value'] = json.dumps(data['value'], ensure_ascii=False)
        config = SystemConfig(**data)
        db.add(config)
        db.commit()
        db.refresh(config)
        resp = SystemConfigResponse.model_validate(config)
        if config.value:
            try:
                import json
                resp.value = json.loads(config.value)
            except Exception:
                pass
        return resp

@router.delete("/{config_key}")
def delete_system_config(
    config_key: str,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """删除系统配置"""
    config = db.query(SystemConfig).filter(SystemConfig.key == config_key).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
    db.delete(config)
    db.commit()
    return {"message": "删除成功"}
