"""Assets, parts and technicians - the pick-lists the capture screen needs."""

from __future__ import annotations

from fastapi import APIRouter, Depends, Query
from sqlalchemy import or_, select
from sqlalchemy.orm import Session

from app.db import get_db
from app.models import schemas
from app.models.tables import Asset, Part, Technician
from app.services.assets import match_asset

router = APIRouter(tags=["catalog"])


@router.get("/api/assets", response_model=list[schemas.AssetOut])
def list_assets(
    q: str | None = Query(default=None, max_length=128),
    limit: int = Query(default=50, ge=1, le=200),
    db: Session = Depends(get_db),
) -> list[Asset]:
    stmt = select(Asset)
    if q:
        term = f"%{q.strip()}%"
        stmt = stmt.where(
            or_(
                Asset.description.ilike(term),
                Asset.equipment_no.ilike(term),
                Asset.line.ilike(term),
            )
        )
    stmt = stmt.order_by(Asset.description).limit(limit)
    return list(db.scalars(stmt))


@router.get("/api/assets/match", response_model=schemas.AssetMatch | None)
def match_spoken_asset(
    text: str = Query(..., max_length=8000),
    db: Session = Depends(get_db),
) -> schemas.AssetMatch | None:
    """Guess which asset a spoken description refers to. Always a suggestion."""
    result = match_asset(db, text)
    if result is None:
        return None
    asset, score, matched_on = result
    return schemas.AssetMatch(
        asset=schemas.AssetOut.model_validate(asset),
        score=round(score, 3),
        matched_on=matched_on,
    )


@router.get("/api/parts", response_model=list[schemas.PartOut])
def list_parts(
    q: str | None = Query(default=None, max_length=128),
    limit: int = Query(default=50, ge=1, le=200),
    db: Session = Depends(get_db),
) -> list[Part]:
    stmt = select(Part)
    if q:
        term = f"%{q.strip()}%"
        stmt = stmt.where(
            or_(
                Part.part_name.ilike(term),
                Part.part_number.ilike(term),
                Part.barcode.ilike(term),
            )
        )
    stmt = stmt.order_by(Part.part_name).limit(limit)
    return list(db.scalars(stmt))


@router.get("/api/technicians", response_model=list[schemas.TechnicianOut])
def list_technicians(db: Session = Depends(get_db)) -> list[Technician]:
    return list(
        db.scalars(
            select(Technician)
            .where(Technician.active.is_(True))
            .order_by(Technician.name)
        )
    )
