from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc
from typing import Optional

from app.database import get_db
from app.models.equipment import Equipment, EquipmentMaintenance, EquipmentStatus
from app.schemas.equipment import (
    EquipmentCreate, EquipmentUpdate, EquipmentOut,
    MaintenanceCreate, MaintenanceOut
)
from app.schemas.common import Response, PageResponse
from app.services.auth_service import get_current_user

router = APIRouter()


@router.get("/", response_model=Response[PageResponse[EquipmentOut]])
async def list_equipment(
    page: int = 1,
    page_size: int = 20,
    name: Optional[str] = None,
    status: Optional[str] = None,
    category: Optional[str] = None,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    query = select(Equipment).order_by(Equipment.code)
    if name:
        query = query.where(Equipment.name.ilike(f"%{name}%"))
    if status:
        try:
            query = query.where(Equipment.status == EquipmentStatus(status))
        except ValueError:
            pass
    if category:
        query = query.where(Equipment.category == category)

    total = (await db.execute(select(func.count()).select_from(query.subquery()))).scalar()
    result = await db.execute(query.offset((page - 1) * page_size).limit(page_size))
    items = [EquipmentOut.model_validate(e) for e in result.scalars()]
    return Response.ok(PageResponse(total=total, page=page, page_size=page_size, items=items))


@router.post("/", response_model=Response[EquipmentOut])
async def create_equipment(
    body: EquipmentCreate,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    existing = await db.execute(select(Equipment).where(Equipment.code == body.code))
    if existing.scalar_one_or_none():
        raise HTTPException(status_code=400, detail="设备编号已存在")
    equip = Equipment(**body.model_dump())
    db.add(equip)
    await db.flush()
    return Response.ok(EquipmentOut.model_validate(equip))


@router.get("/{equip_id}", response_model=Response[EquipmentOut])
async def get_equipment(equip_id: int, db: AsyncSession = Depends(get_db), _ = Depends(get_current_user)):
    result = await db.execute(select(Equipment).where(Equipment.id == equip_id))
    equip = result.scalar_one_or_none()
    if not equip:
        raise HTTPException(status_code=404, detail="设备不存在")
    return Response.ok(EquipmentOut.model_validate(equip))


@router.put("/{equip_id}", response_model=Response[EquipmentOut])
async def update_equipment(
    equip_id: int,
    body: EquipmentUpdate,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    result = await db.execute(select(Equipment).where(Equipment.id == equip_id))
    equip = result.scalar_one_or_none()
    if not equip:
        raise HTTPException(status_code=404, detail="设备不存在")
    for k, v in body.model_dump(exclude_none=True).items():
        setattr(equip, k, v)
    await db.flush()
    return Response.ok(EquipmentOut.model_validate(equip))


@router.get("/{equip_id}/maintenance", response_model=Response[PageResponse[MaintenanceOut]])
async def list_maintenance(
    equip_id: int,
    page: int = 1,
    page_size: int = 20,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    query = select(EquipmentMaintenance).where(
        EquipmentMaintenance.equipment_id == equip_id
    ).order_by(desc(EquipmentMaintenance.start_time))
    total = (await db.execute(select(func.count()).select_from(query.subquery()))).scalar()
    result = await db.execute(query.offset((page - 1) * page_size).limit(page_size))
    items = [MaintenanceOut.model_validate(m) for m in result.scalars()]
    return Response.ok(PageResponse(total=total, page=page, page_size=page_size, items=items))


@router.post("/maintenance", response_model=Response[MaintenanceOut])
async def create_maintenance(
    body: MaintenanceCreate,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    record = EquipmentMaintenance(**body.model_dump())
    db.add(record)
    await db.flush()
    return Response.ok(MaintenanceOut.model_validate(record))
