"""
Production Tracking API routes.
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from uuid import UUID

from app.core.database import get_db
from app.core.security import get_current_user
from app.models.core_models import LoginUsers
from . import schemas, service

from app.modules.station_work.routes import ensure_station_access

router = APIRouter()


# ── Scan ──────────────────────────────────────────────────
@router.post("/scan", response_model=schemas.ScanResponse)
async def scan_chassis(
    req: schemas.ScanRequest,
    db: AsyncSession = Depends(get_db),
    user: LoginUsers = Depends(get_current_user),
):
    """Scan chassis QR at a station — auto-detects ARRIVAL or COMPLETION."""
    await ensure_station_access(db, user, req.station_id, 'OPERATOR')
    return await service.scan_chassis(db, req, user.user_id)


# ── Dashboard ─────────────────────────────────────────────
@router.get("/dashboard", response_model=schemas.DashboardResponse)
async def get_dashboard(
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    """Production manager dashboard with KPIs, station pipeline, live timers."""
    return await service.get_dashboard(db)


# ── Chassis Timeline ─────────────────────────────────────
@router.get("/chassis/{chassis_no}/timeline", response_model=List[schemas.TimelineEntry])
async def get_timeline(
    chassis_no: str,
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    """Full station journey for a specific chassis."""
    return await service.get_chassis_timeline(db, chassis_no)


# ── Overdue ───────────────────────────────────────────────
@router.get("/overdue", response_model=List[schemas.OverdueEntry])
async def get_overdue(
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    """All chassis currently exceeding cycle time at their station."""
    return await service.get_overdue_chassis(db)


# ── Delay Logging ─────────────────────────────────────────
@router.post("/delay/{log_id}")
async def log_delay(
    log_id: UUID,
    req: schemas.DelayLogRequest,
    db: AsyncSession = Depends(get_db),
    user: LoginUsers = Depends(get_current_user),
):
    """Log delay reason on an overdue chassis station log."""
    return await service.log_delay(db, log_id, req, user.user_id)


# ── Holds ─────────────────────────────────────────────────
@router.post("/holds", response_model=schemas.HoldOut, status_code=201)
async def create_hold(
    req: schemas.HoldCreate,
    db: AsyncSession = Depends(get_db),
    user: LoginUsers = Depends(get_current_user),
):
    """Raise a production hold on a chassis."""
    return await service.create_hold(db, req, user.user_id)


@router.put("/holds/{hold_id}/resolve", response_model=schemas.HoldOut)
async def resolve_hold(
    hold_id: UUID,
    req: schemas.HoldResolve,
    db: AsyncSession = Depends(get_db),
    user: LoginUsers = Depends(get_current_user),
):
    """Resolve an active hold."""
    return await service.resolve_hold(db, hold_id, req, user.user_id)


@router.get("/holds", response_model=List[schemas.HoldOut])
async def list_holds(
    status: Optional[str] = Query(None, description="Filter by ACTIVE or RESOLVED"),
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    """List production holds, optionally filtered by status."""
    return await service.list_holds(db, status)


# ── Station Live View ─────────────────────────────────────
@router.get("/station/{station_id}/live", response_model=schemas.StationLiveView)
async def station_live(
    station_id: UUID,
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    """Live view of a specific station — chassis at station with timers."""
    return await service.get_station_live(db, station_id)


# ── Delay Reason Codes (CRUD) ─────────────────────────────
@router.get("/reason-codes", response_model=List[schemas.DelayReasonOut])
async def list_reason_codes(
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    return await service.list_reason_codes(db)


@router.post("/reason-codes", response_model=schemas.DelayReasonOut, status_code=201)
async def create_reason_code(
    req: schemas.DelayReasonCreate,
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    return await service.create_reason_code(db, req)


@router.put("/reason-codes/{reason_id}", response_model=schemas.DelayReasonOut)
async def update_reason_code(
    reason_id: UUID,
    req: schemas.DelayReasonUpdate,
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    return await service.update_reason_code(db, reason_id, req)


@router.delete("/reason-codes/{reason_id}", status_code=204)
async def delete_reason_code(
    reason_id: UUID,
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    await service.delete_reason_code(db, reason_id)


# ── Analytics ─────────────────────────────────────────────
@router.get("/analytics/bottleneck", response_model=List[schemas.StationBottleneck])
async def bottleneck_analytics(
    db: AsyncSession = Depends(get_db),
    _=Depends(get_current_user),
):
    """Average time per station, most delayed stations."""
    return await service.get_bottleneck_analytics(db)
