from typing import Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.user import User
from app.schemas.common import ResponseModel, ListResponse
from app.services import alert_service
from app.api.deps import get_current_user, require_admin

router = APIRouter()


@router.post("/init-rules")
def init_alert_rules(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    alert_service.init_builtin_alert_rules(db)
    return ResponseModel(message="初始化完成")


@router.post("/check")
def check_alerts(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    records = alert_service.check_alerts(db)
    return ResponseModel(data={"alerts_created": len(records)})


@router.get("/records")
def list_alert_records(
    status: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=500),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    query = db.query(alert_service.AlertRecord)
    if status:
        query = query.filter(alert_service.AlertRecord.status == status)
    total = query.count()
    items = query.order_by(alert_service.AlertRecord.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
    return ListResponse(
        data=[{
            "id": r.id,
            "rule_id": r.rule_id,
            "title": r.title,
            "content": r.content,
            "severity": r.severity,
            "status": r.status,
            "created_at": r.created_at.isoformat() if r.created_at else None,
        } for r in items],
        total=total,
        page=page,
        page_size=page_size,
    )


@router.post("/work-orders")
def create_work_order(
    alert_id: int,
    title: str,
    description: str = "",
    assignee_id: Optional[int] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    wo = alert_service.create_work_order(db, alert_id, title, description, assignee_id)
    return ResponseModel(data={"id": wo.id})


@router.get("/work-orders")
def list_work_orders(
    status: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=500),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    from app.models.alert import WorkOrder
    query = db.query(WorkOrder)
    if status:
        query = query.filter(WorkOrder.status == status)
    total = query.count()
    items = query.order_by(WorkOrder.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
    return ListResponse(
        data=[{
            "id": w.id,
            "alert_id": w.alert_id,
            "title": w.title,
            "status": w.status,
            "assignee_name": w.assignee.username if w.assignee else None,
            "created_at": w.created_at.isoformat() if w.created_at else None,
        } for w in items],
        total=total,
        page=page,
        page_size=page_size,
    )


@router.post("/work-orders/{wo_id}/status")
def update_work_order(
    wo_id: int,
    status: str,
    resolution: str = "",
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    wo = alert_service.update_work_order_status(db, wo_id, status, resolution or None)
    if not wo:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="工单不存在")
    return ResponseModel(data={"id": wo.id, "status": wo.status})
