from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from core.database import get_db
from models.algorithm import Algorithm
from schemas.algorithm import (
    AlgorithmCreate, 
    AlgorithmUpdate, 
    AlgorithmResponse, 
    AlgorithmListResponse
)

router = APIRouter()

@router.post("/", response_model=AlgorithmResponse, summary="创建算法")
async def create_algorithm(
    algorithm: AlgorithmCreate,
    db: Session = Depends(get_db)
):
    """创建新的算法"""
    db_algorithm = Algorithm(**algorithm.dict())
    db.add(db_algorithm)
    db.commit()
    db.refresh(db_algorithm)
    return db_algorithm

@router.get("/", response_model=AlgorithmListResponse, summary="获取算法列表")
async def get_algorithms(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回记录数"),
    name: Optional[str] = Query(None, description="算法名称"),
    status: Optional[str] = Query(None, description="算法状态"),
    is_enabled: Optional[bool] = Query(None, description="是否启用"),
    db: Session = Depends(get_db)
):
    """获取算法列表，支持分页和筛选"""
    query = db.query(Algorithm)
    
    if name:
        query = query.filter(Algorithm.name.contains(name))
    if status:
        query = query.filter(Algorithm.status == status)
    if is_enabled is not None:
        query = query.filter(Algorithm.is_enabled == is_enabled)
    
    total = query.count()
    algorithms = query.offset(skip).limit(limit).all()
    
    return AlgorithmListResponse(
        algorithms=algorithms,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{algorithm_id}", response_model=AlgorithmResponse, summary="获取算法详情")
async def get_algorithm(
    algorithm_id: int,
    db: Session = Depends(get_db)
):
    """根据ID获取算法详情"""
    algorithm = db.query(Algorithm).filter(Algorithm.id == algorithm_id).first()
    if not algorithm:
        raise HTTPException(status_code=404, detail="算法不存在")
    return algorithm

@router.put("/{algorithm_id}", response_model=AlgorithmResponse, summary="更新算法")
async def update_algorithm(
    algorithm_id: int,
    algorithm: AlgorithmUpdate,
    db: Session = Depends(get_db)
):
    """更新算法信息"""
    db_algorithm = db.query(Algorithm).filter(Algorithm.id == algorithm_id).first()
    if not db_algorithm:
        raise HTTPException(status_code=404, detail="算法不存在")
    
    update_data = algorithm.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_algorithm, field, value)
    
    db.commit()
    db.refresh(db_algorithm)
    return db_algorithm

@router.delete("/{algorithm_id}", summary="删除算法")
async def delete_algorithm(
    algorithm_id: int,
    db: Session = Depends(get_db)
):
    """删除算法"""
    algorithm = db.query(Algorithm).filter(Algorithm.id == algorithm_id).first()
    if not algorithm:
        raise HTTPException(status_code=404, detail="算法不存在")
    
    db.delete(algorithm)
    db.commit()
    return {"message": "算法删除成功"}

@router.patch("/{algorithm_id}/status", response_model=AlgorithmResponse, summary="更新算法状态")
async def update_algorithm_status(
    algorithm_id: int,
    status: str = Query(..., description="新状态"),
    db: Session = Depends(get_db)
):
    """更新算法状态"""
    algorithm = db.query(Algorithm).filter(Algorithm.id == algorithm_id).first()
    if not algorithm:
        raise HTTPException(status_code=404, detail="算法不存在")
    
    algorithm.status = status
    db.commit()
    db.refresh(algorithm)
    return algorithm

@router.patch("/{algorithm_id}/enable", response_model=AlgorithmResponse, summary="启用/禁用算法")
async def toggle_algorithm_enabled(
    algorithm_id: int,
    enabled: bool = Query(..., description="是否启用"),
    db: Session = Depends(get_db)
):
    """启用或禁用算法"""
    algorithm = db.query(Algorithm).filter(Algorithm.id == algorithm_id).first()
    if not algorithm:
        raise HTTPException(status_code=404, detail="算法不存在")
    
    algorithm.is_enabled = enabled
    db.commit()
    db.refresh(algorithm)
    return algorithm 