"""
API endpoints for clinical laboratory worksheets and parameter result entries.
"""

from uuid import UUID

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

from app.core.auth_deps import require_permission
from app.core.dependencies import get_db
from app.core.exceptions import NotFoundException
from app.core.permissions import PermissionCode
from app.core.responses import SuccessResponse
from app.models.user import User
from app.repositories.order_repository import OrderRepository
from app.repositories.sample_repository import SampleRepository
from app.schemas.result import (
    OrderResultEntryRequest,
    OrderResultEntryResponse,
    OrderWorksheetResponse,
)
from app.services.result_service import ResultService

router = APIRouter(prefix="/orders", tags=["Results & Clinical Entry"])
service = ResultService()


async def _resolve_order_id(
    order_identifier: str,
    db: AsyncSession,
    current_user: User,
) -> UUID:
    """
    Resolve an order identifier that can be either a UUID order_id,
    a human-readable order_number (e.g. 'ORD260001'),
    or a specimen barcode/sample code (e.g. 'SAM-20261001-000001').
    Returns the canonical UUID order_id.
    """
    cleaned = order_identifier.strip()

    # Try as UUID first (order_id or sample_id)
    try:
        uid = UUID(cleaned)
        order = await OrderRepository().get_by_id(db, uid)
        if order:
            return uid
        sample = await SampleRepository().get_by_id(db, uid)
        if sample:
            return sample.order_id
    except Exception:  # noqa: BLE001, S110
        pass  # order_identifier is not a UUID; fall through

    # Try as order_number string (e.g. ORD26000004)
    order = await OrderRepository().get_by_number(
        db, cleaned, None if current_user.is_superadmin else current_user.lab_id
    )
    if order:
        return order.id

    # Try as specimen tube barcode or sample code
    sample = await SampleRepository().get_by_barcode(
        db, cleaned, None if current_user.is_superadmin else current_user.lab_id
    )
    if sample:
        return sample.order_id

    raise NotFoundException(f"Order not found: {order_identifier}")


@router.get(
    "/results/worksheet",
    response_model=SuccessResponse[OrderWorksheetResponse],
    summary="Get clinical entry worksheet by query parameter",
)
async def get_worksheet_query(
    order_identifier: str = Query(..., description="UUID order_id or order_number (e.g. ORD260001)"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission(PermissionCode.RESULT_READ)),
) -> SuccessResponse[OrderWorksheetResponse]:
    """
    Retrieve laboratory worksheet with ordered tests, diagnostic analytes,
    and patient-tailored biological reference ranges. Accepts query param to support
    slash-formatted order numbers without path encoding issues.
    """
    order_id = await _resolve_order_id(order_identifier, db, current_user)
    res = await service.get_worksheet(db, order_id=order_id, current_user=current_user)
    return SuccessResponse(data=res)


@router.post(
    "/results",
    response_model=SuccessResponse[OrderResultEntryResponse],
    summary="Enter clinical test results by query parameter",
)
async def enter_results_query(
    payload: OrderResultEntryRequest,
    order_identifier: str = Query(..., description="UUID order_id or order_number (e.g. ORD260001)"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission(PermissionCode.RESULT_WRITE)),
) -> SuccessResponse[OrderResultEntryResponse]:
    """
    Record clinical analyte observations via query parameter.
    """
    order_id = await _resolve_order_id(order_identifier, db, current_user)
    res = await service.enter_results(
        db=db,
        order_id=order_id,
        data=payload,
        current_user=current_user,
    )
    return SuccessResponse(data=res)


@router.get(
    "/{order_identifier}/results/worksheet",
    response_model=SuccessResponse[OrderWorksheetResponse],
    summary="Get clinical entry worksheet",
)
async def get_worksheet(
    order_identifier: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission(PermissionCode.RESULT_READ)),
) -> SuccessResponse[OrderWorksheetResponse]:
    """
    Retrieve laboratory worksheet with ordered tests, diagnostic analytes,
    and patient-tailored biological reference ranges (age and gender specific).
    Accepts either a UUID order_id or a human-readable order_number.
    """
    order_id = await _resolve_order_id(order_identifier, db, current_user)
    res = await service.get_worksheet(db, order_id=order_id, current_user=current_user)
    return SuccessResponse(data=res)


@router.post(
    "/{order_identifier}/results",
    response_model=SuccessResponse[OrderResultEntryResponse],
    summary="Enter clinical test results",
)
async def enter_results(
    order_identifier: str,
    payload: OrderResultEntryRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission(PermissionCode.RESULT_WRITE)),
) -> SuccessResponse[OrderResultEntryResponse]:
    """
    Record clinical analyte observations, perform auto-flagging against
    biological reference intervals (Normal/Low/High/Abnormal), and update
    the report draft.
    Accepts either a UUID order_id or a human-readable order_number.
    """
    order_id = await _resolve_order_id(order_identifier, db, current_user)
    res = await service.enter_results(
        db=db,
        order_id=order_id,
        data=payload,
        current_user=current_user,
    )
    return SuccessResponse(data=res)
