"""``/api/admin/validate-provider`` — NPI + Tax ID liveness probe (SP20).

Pure read-only endpoint that runs the local NPI Luhn + EIN format checks
without touching the DB. Useful for:
- operators vetting a new provider before adding them to the registry,
- the dashboard's "validate" button on a Provider row,
- smoke-testing the SP20 checks after a deploy.

Both query params are optional; omitting one just skips that check.
Returns the per-check result dict so the caller can distinguish "bad
format" from "bad checksum".
"""
from __future__ import annotations

from fastapi import APIRouter, Query

from cyclone.npi import is_valid_npi, is_valid_tax_id, normalize_tax_id


router = APIRouter()


@router.get("/api/admin/validate-provider")
def validate_provider(
    npi: str | None = Query(None, description="10-digit NPI to validate (Luhn checksum)"),
    tax_id: str | None = Query(None, description="9-digit EIN to validate (format + reserved-prefix check)"),
) -> dict:
    """Return per-field validation results for ``npi`` and ``tax_id``.

    Each field's payload is the same shape:

    * ``valid`` — bool, the operator's "yes/no" answer
    * ``normalized`` — for ``tax_id``: the 9-digit plain form, or null
      if the input is unparseable

    An empty/unset query param returns ``{"valid": None, "skipped": true}``
    so the caller can render "no check performed" rather than treating
    ``None`` as a hard fail.
    """
    result: dict = {}

    if npi is None or npi == "":
        result["npi"] = {"valid": None, "skipped": True}
    else:
        result["npi"] = {
            "valid": is_valid_npi(npi),
            "skipped": False,
        }

    if tax_id is None or tax_id == "":
        result["tax_id"] = {"valid": None, "skipped": True, "normalized": None}
    else:
        normalized = normalize_tax_id(tax_id)
        result["tax_id"] = {
            "valid": is_valid_tax_id(tax_id),
            "skipped": False,
            "normalized": normalized,
        }

    return result