"""Routing query specifications — Phase 10.6."""
from __future__ import annotations

from dataclasses import dataclass
from uuid import UUID

from sqlalchemy import Select, asc, desc, or_
from sqlalchemy.sql import ColumnElement

from app.models.routing import OptimizationRun, RoutePlan
from app.models.types import OptimizationRunStatus, RoutePlanStatus

ROUTE_SORT = frozenset({"created_at", "updated_at", "code", "status"})
OPT_SORT = frozenset({"created_at", "updated_at", "status"})


@dataclass(frozen=True, slots=True)
class RoutePlanListSpec:
    status: RoutePlanStatus | None = None
    organization_id: UUID | None = None
    driver_id: UUID | None = None
    q: str | None = None
    sort_by: str = "created_at"
    sort_dir: str = "desc"

    def filter_clauses(self) -> list[ColumnElement]:
        clauses: list[ColumnElement] = []
        if self.status is not None:
            clauses.append(RoutePlan.status == self.status)
        if self.organization_id is not None:
            clauses.append(RoutePlan.organization_id == self.organization_id)
        if self.driver_id is not None:
            clauses.append(RoutePlan.driver_id == self.driver_id)
        if self.q:
            term = f"%{self.q.strip()}%"
            clauses.append(RoutePlan.code.ilike(term))
        return clauses

    def apply(self, stmt: Select) -> Select:
        clauses = self.filter_clauses()
        if clauses:
            stmt = stmt.where(*clauses)
        sort_key = self.sort_by if self.sort_by in ROUTE_SORT else "created_at"
        column = getattr(RoutePlan, sort_key)
        order = desc(column) if self.sort_dir.lower() != "asc" else asc(column)
        return stmt.order_by(order)


@dataclass(frozen=True, slots=True)
class OptimizationRunListSpec:
    route_plan_id: UUID | None = None
    status: OptimizationRunStatus | None = None
    sort_by: str = "created_at"
    sort_dir: str = "desc"

    def filter_clauses(self) -> list[ColumnElement]:
        clauses: list[ColumnElement] = []
        if self.route_plan_id is not None:
            clauses.append(OptimizationRun.route_plan_id == self.route_plan_id)
        if self.status is not None:
            clauses.append(OptimizationRun.status == self.status)
        return clauses

    def apply(self, stmt: Select) -> Select:
        clauses = self.filter_clauses()
        if clauses:
            stmt = stmt.where(*clauses)
        sort_key = self.sort_by if self.sort_by in OPT_SORT else "created_at"
        column = getattr(OptimizationRun, sort_key)
        order = desc(column) if self.sort_dir.lower() != "asc" else asc(column)
        return stmt.order_by(order)
