"""Reject Swagger/Postman placeholder path IDs before they become opaque 404s."""

from __future__ import annotations

from fastapi import HTTPException, status

# Values Swagger UI / OpenAPI tools often send when no real example is set,
# or leftover demo placeholders that are not real resources.
_PLACEHOLDERS = frozenset(
    {
        "string",
        "null",
        "undefined",
        "interview_id",
        ":interview_id",
        "int-demo-001",
        "from-sessions-start",
        "<from-sessions-start>",
        "report_id",
        ":report_id",
        "from-evaluation-pdf",
        "<from-evaluation-pdf>",
        "version_id",
        ":version_id",
        "ver-acme-001",
        "from-version-draft",
        "<from-version-draft>",
        "clone_id",
        ":clone_id",
        "clone-acme-001",
        "from-manager-clone",
        "<from-manager-clone>",
        "3fa85f64-5717-4562-b3fc-2c963f66afa6",  # common OpenAPI sample UUID
    }
)


def is_placeholder_id(value: str | None) -> bool:
    if value is None:
        return True
    v = str(value).strip()
    if not v:
        return True
    if v in _PLACEHOLDERS:
        return True
    if v.startswith(":") or v.startswith("<"):
        return True
    # OpenAPI / Swagger Try-it-out demo prefixes (example-personaId, …)
    low = v.lower()
    if low.startswith("example-") or low.startswith("example_"):
        return True
    return False


def blank_if_placeholder(value: str | None) -> str | None:
    """Return None when value is a Swagger/OpenAPI placeholder."""
    if value is None:
        return None
    cleaned = str(value).strip()
    if not cleaned or is_placeholder_id(cleaned):
        return None
    return cleaned


def reject_placeholder_id(
    value: str,
    *,
    kind: str,
    hint: str,
) -> str:
    """Return stripped value or raise HTTP 400 with a workflow hint."""
    cleaned = (value or "").strip()
    if is_placeholder_id(cleaned):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=(
                f"Invalid {kind} path/query value {cleaned!r}. {hint}"
            ),
        )
    return cleaned


def coerce_placeholder(
    value: str | None,
    *,
    resolved: str | None,
    kind: str,
    hint: str,
) -> str:
    """If value is a Swagger placeholder, use `resolved` when available; else 400."""
    cleaned = (value or "").strip()
    if not is_placeholder_id(cleaned):
        return cleaned
    if resolved:
        return resolved
    raise HTTPException(
        status_code=status.HTTP_400_BAD_REQUEST,
        detail=f"Invalid {kind} path/query value {cleaned!r}. {hint}",
    )
