from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from datetime import datetime, date

from app.database import get_db
from app.models.material import Coil, CoilStatus
from app.models.production import ProductionRecord
from app.models.downtime import DowntimeRecord
from app.models.equipment import Equipment, EquipmentStatus
from app.schemas.common import Response
from app.services.auth_service import get_current_user

router = APIRouter()


@router.get("/summary", response_model=Response[dict])
async def get_summary(db: AsyncSession = Depends(get_db), _ = Depends(get_current_user)):
    today = datetime.combine(date.today(), datetime.min.time())

    # 今日产量
    prod_result = await db.execute(
        select(func.count(), func.sum(ProductionRecord.process_weight))
        .where(ProductionRecord.start_time >= today)
    )
    prod_count, prod_weight = prod_result.one()

    # 在线钢卷数
    online_result = await db.execute(
        select(func.count()).where(Coil.status == CoilStatus.ON_LINE)
    )
    online_coils = online_result.scalar()

    # 今日停机时长
    downtime_result = await db.execute(
        select(func.sum(DowntimeRecord.duration))
        .where(DowntimeRecord.start_time >= today)
    )
    total_downtime = downtime_result.scalar() or 0

    # 设备状态统计
    equip_result = await db.execute(
        select(Equipment.status, func.count()).group_by(Equipment.status)
    )
    equip_stats = {str(row[0]): row[1] for row in equip_result}

    return Response.ok({
        "today_production": {
            "coil_count": prod_count or 0,
            "weight_kg": float(prod_weight or 0),
        },
        "online_coils": online_coils or 0,
        "today_downtime_min": float(total_downtime),
        "equipment_status": equip_stats,
    })
