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

from ..database import get_db
from ..models import LLMConfig
from ..schemas import LLMConfigBase, LLMConfigResponse

router = APIRouter(prefix="/api/admin/llmconfigs", 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[LLMConfigResponse])
def list_llm_configs(
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """获取 LLM 配置列表"""
    configs = db.query(LLMConfig).all()
    return [LLMConfigResponse.model_validate(c) for c in configs]

@router.get("/{config_id}", response_model=LLMConfigResponse)
def get_llm_config(
    config_id: int,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """获取单个 LLM 配置详情"""
    config = db.query(LLMConfig).filter(LLMConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
    return config

@router.post("", response_model=LLMConfigResponse)
def create_llm_config(
    config_data: LLMConfigBase,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """创建 LLM 配置"""
    config = LLMConfig(**config_data.model_dump())
    db.add(config)
    db.commit()
    db.refresh(config)
    return config

@router.put("/{config_id}", response_model=LLMConfigResponse)
def update_llm_config(
    config_id: int,
    config_update: LLMConfigBase,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """更新 LLM 配置"""
    config = db.query(LLMConfig).filter(LLMConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
    update_data = config_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(config, field, value)
    db.commit()
    db.refresh(config)
    return config

@router.delete("/{config_id}")
def delete_llm_config(
    config_id: int,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """删除 LLM 配置"""
    config = db.query(LLMConfig).filter(LLMConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
    db.delete(config)
    db.commit()
    return {"message": "删除成功"}
