"""Coding queue API — dedicated endpoints for Gutachten classification workflow."""

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

from app.core.dependencies import require_admin
from app.database import get_db
from app.models.user import User
from app.schemas.case import CaseListResponse, CaseResponse, CodingUpdate
from app.services.coding_service import (
    batch_update_coding,
    get_coding_queue,
    update_coding,
)

router = APIRouter()


@router.get("/queue", response_model=CaseListResponse)
def coding_queue(
    fallgruppe: str | None = Query(None),
    jahr: int | None = Query(None),
    page: int = Query(1, ge=1),
    per_page: int = Query(50, ge=1, le=200),
    db: Session = Depends(get_db),
    user: User = Depends(require_admin),
):
    """Return cases that need coding (gutachten=True, gutachten_typ=NULL).

    Admin only. Supports optional fallgruppe and jahr filters with pagination.
    """
    cases, total = get_coding_queue(db, fallgruppe, jahr, page, per_page)
    return CaseListResponse(
        items=[CaseResponse.model_validate(c) for c in cases],
        total=total,
        page=page,
        per_page=per_page,
    )


@router.put("/{case_id}", response_model=CaseResponse)
def update_case_coding(
    case_id: int,
    data: CodingUpdate,
    db: Session = Depends(get_db),
    user: User = Depends(require_admin),
):
    """Set Gutachten classification and therapy-change coding for a single case.

    Admin only. Validates gutachten_typ and therapieaenderung values.
    """
    case = update_coding(
        db,
        case_id,
        data.gutachten_typ,
        data.therapieaenderung,
        data.ta_diagnosekorrektur,
        data.ta_unterversorgung,
        data.ta_uebertherapie,
        user_id=user.id,
    )
    return CaseResponse.model_validate(case)


@router.post("/batch")
def batch_coding(
    updates: list[dict],
    db: Session = Depends(get_db),
    user: User = Depends(require_admin),
):
    """Batch update coding for multiple cases at once.

    Admin only. Accepts a list of dicts, each containing at minimum:
    ``case_id``, ``gutachten_typ``, ``therapieaenderung``.

    Returns a summary with ``updated`` count and ``errors`` list.
    """
    result = batch_update_coding(db, updates, user_id=user.id)
    return result
