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

from ..database import get_db
from ..models import TaskLog
from ..schemas import TaskLogBase, TaskLogResponse

router = APIRouter(prefix="/api/admin/tasklogs", 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[TaskLogResponse])
def list_task_logs(
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin),
    topic_id: Optional[str] = None,
    task_name: Optional[str] = None,
    status: Optional[str] = None
):
    """获取任务日志列表（可过滤）"""
    query = db.query(TaskLog)
    if topic_id:
        query = query.filter(TaskLog.topic_id == topic_id)
    if task_name:
        query = query.filter(TaskLog.task_name == task_name)
    if status:
        query = query.filter(TaskLog.status == status)
    logs = query.order_by(TaskLog.started_at.desc()).all()
    return [TaskLogResponse.model_validate(l) for l in logs]

@router.get("/{log_id}", response_model=TaskLogResponse)
def get_task_log(
    log_id: int,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """获取单个任务日志详情"""
    log = db.query(TaskLog).filter(TaskLog.id == log_id).first()
    if not log:
        raise HTTPException(status_code=404, detail="日志不存在")
    return log

@router.post("", response_model=TaskLogResponse)
def create_task_log(
    log_data: TaskLogBase,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """创建任务日志（用于手动记录）"""
    log = TaskLog(**log_data.model_dump())
    db.add(log)
    db.commit()
    db.refresh(log)
    return log

@router.put("/{log_id}", response_model=TaskLogResponse)
def update_task_log(
    log_id: int,
    log_update: TaskLogBase,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """更新任务日志"""
    log = db.query(TaskLog).filter(TaskLog.id == log_id).first()
    if not log:
        raise HTTPException(status_code=404, detail="日志不存在")
    update_data = log_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(log, field, value)
    db.commit()
    db.refresh(log)
    return log

@router.delete("/{log_id}")
def delete_task_log(
    log_id: int,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """删除任务日志"""
    log = db.query(TaskLog).filter(TaskLog.id == log_id).first()
    if not log:
        raise HTTPException(status_code=404, detail="日志不存在")
    db.delete(log)
    db.commit()
    return {"message": "删除成功"}
