"""Optimization run APIs — Phase 10.6."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.api.permissions import require_permissions
from app.commands.routing import RoutingCommands
from app.models.types import OptimizationRunStatus
from app.permissions.definitions import OPTIMIZATION_RUNS_CREATE, OPTIMIZATION_RUNS_VIEW
from app.queries.routing import RoutingQueries
from app.schemas.routing import (
    OptimizationRunCreate,
    OptimizationRunListResponse,
    OptimizationRunRead,
)
from app.specifications.routing import OptimizationRunListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    route_plan_id: UUID | None = Query(default=None),
    status_filter: OptimizationRunStatus | None = Query(default=None, alias="status"),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> OptimizationRunListSpec:
    return OptimizationRunListSpec(
        route_plan_id=route_plan_id,
        status=status_filter,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("/runs", response_model=OptimizationRunRead, status_code=status.HTTP_201_CREATED)
async def start_optimization(
    body: OptimizationRunCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(OPTIMIZATION_RUNS_CREATE)),
):
    return await RoutingCommands(db).start_optimization(tenant_id, body, actor=user)


@router.get("/runs", response_model=OptimizationRunListResponse)
async def list_optimization_runs(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: OptimizationRunListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(OPTIMIZATION_RUNS_VIEW)),
):
    items, total = await RoutingQueries(db).list_optimization_runs(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return OptimizationRunListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/runs/{run_id}", response_model=OptimizationRunRead)
async def get_optimization_run(
    run_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(OPTIMIZATION_RUNS_VIEW)),
):
    return await RoutingQueries(db).get_optimization_run(tenant_id, run_id)
