{
  "openapi": "3.1.0",
  "info": {
    "title": "Auth57 API",
    "version": "1.0.0",
    "summary": "Verified prior-authorization rule data for all 51 US states.",
    "description": "Auth57 is a commercial REST API returning human-verified, source-linked prior-authorization (PA) rules across all 51 states, 7 programs, 20 service categories, and 20 drug classes.\n\nData is continuously updated via the Watch pipeline and benchmarked against CMS-0057-F and CMS-0062-P. Every response includes the source URL and `last_verified` date for citable use in clinical, compliance, and benefits workflows.\n\n## Authentication\n\nAll requests require an API key passed as `x-api-key`. Keys are issued per subscription. Request a paid key at https://auth57.io/subscribe-api or free demo access via https://auth57.io/book.\n\n## Rate limits\n\n- `/v1/pauth-lookup`: 10,000 requests per hour per API key\n- `/v1/compare`: 2,000 requests per hour per API key\n\nExceeding the limit returns HTTP 429 with a `Retry-After` header. Admin keys bypass limits.\n\n## Latency\n\nMost requests complete in under 200ms via the edge static fast path. The `served_from` field in the response tells you which path handled your call (`static` = edge CDN, `edge` = live Supabase query).\n\n## Support\n\nEmail hello@auth57labs.com or book a 30-min call at https://auth57.io/book.",
    "contact": {
      "name": "Auth57 Labs",
      "email": "hello@auth57labs.com",
      "url": "https://auth57labs.com"
    },
    "license": {
      "name": "Commercial",
      "url": "https://auth57.io/terms"
    },
    "termsOfService": "https://auth57.io/terms"
  },
  "servers": [
    { "url": "https://api.auth57.io", "description": "Production" }
  ],
  "security": [
    { "ApiKeyAuth": [] }
  ],
  "tags": [
    { "name": "Lookup", "description": "Single-state PA rule lookup." },
    { "name": "Compare", "description": "Cross-state PA rule comparison." },
    { "name": "Metadata", "description": "State-level coverage and flags." },
    { "name": "Discovery", "description": "Public capability descriptors. No authentication required." }
  ],
  "paths": {
    "/v1/pauth-lookup": {
      "get": {
        "summary": "Look up a PA rule for one state / program / drug or service.",
        "description": "Returns the verified prior-authorization rule for a given (state, program, drug_or_service) combination. Specify exactly one of `drug` or `service`.\n\nResponses include the full rule plus a `next_steps` array of actionable items for the requestor (documentation to gather, submission target, expected turnaround).\n\nRate limit: 10,000 requests per hour per API key.\n\n`/v1/pa-lookup` is a deprecated alias for this endpoint and returns the same response.",
        "operationId": "pauthLookup",
        "tags": ["Lookup"],
        "parameters": [
          { "$ref": "#/components/parameters/State" },
          { "$ref": "#/components/parameters/Program" },
          { "$ref": "#/components/parameters/Drug" },
          { "$ref": "#/components/parameters/Service" }
        ],
        "responses": {
          "200": {
            "description": "Rule found. Returns the verified PA rule plus actionable next steps.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/PaLookupResponse" },
                "example": {
                  "state": "TX",
                  "program": "medicaid_mco",
                  "query": { "drug_class": "glp1_weight_loss" },
                  "result": {
                    "pa_required": true,
                    "pa_type": "full",
                    "confidence": 0.9,
                    "notes": "GLP-1 agonists require PA for T2DM (HbA1c >=7.5%, failed metformin). Weight-loss-only indication has very limited coverage in TX Medicaid.",
                    "source_url": "https://www.txvendordrug.com/formulary/prior-authorization",
                    "last_verified": "2026-04-22",
                    "federal_override": false
                  },
                  "next_steps": [
                    {
                      "step": 1,
                      "title": "Gather clinical documentation",
                      "items": ["HbA1c >=7.5%", "failed metformin", "Document prior treatment failure (step therapy required)"]
                    },
                    {
                      "step": 2,
                      "title": "Submit PA request",
                      "items": ["Submit to: Enrollee's MCO plan"]
                    },
                    {
                      "step": 3,
                      "title": "Expected turnaround",
                      "items": ["Standard: 14 days", "Expedited: 72 hours"]
                    }
                  ],
                  "served_from": "static",
                  "timestamp": "2026-04-23T15:42:01.891Z"
                }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "429": { "$ref": "#/components/responses/RateLimit" }
        }
      }
    },
    "/v1/compare": {
      "get": {
        "summary": "Compare a PA rule across multiple states.",
        "description": "Returns the verified PA rules for the same (program, drug_or_service) combination across up to 10 states in a single call. Response includes a divergence summary flagging outliers.\n\nRequires a Compare subscription or Compare add-on on your account. Specify exactly one of `drug` or `service`.\n\nRate limit: 2,000 requests per hour per API key.",
        "operationId": "compare",
        "tags": ["Compare"],
        "parameters": [
          {
            "name": "states",
            "in": "query",
            "required": true,
            "description": "Comma-separated list of 2-10 USPS state abbreviations.",
            "schema": { "type": "string", "pattern": "^[A-Z]{2}(,[A-Z]{2}){1,9}$", "example": "TX,CA,OH,NY,FL" }
          },
          { "$ref": "#/components/parameters/Program" },
          { "$ref": "#/components/parameters/Drug" },
          { "$ref": "#/components/parameters/Service" }
        ],
        "responses": {
          "200": {
            "description": "Compare succeeded. Returns per-state results plus divergence summary.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/CompareResponse" },
                "example": {
                  "states": ["TX", "CA", "OH", "NY", "FL"],
                  "program": "medicaid_mco",
                  "query": { "drug_class": "glp1_weight_loss" },
                  "summary": {
                    "total": 5,
                    "require_pa": 4,
                    "no_pa": 1,
                    "divergence": true,
                    "divergence_summary": "4 of 5 states require PA. OH is an outlier."
                  },
                  "results": [
                    {
                      "state_abbr": "TX",
                      "pa_required": true,
                      "pa_type": "full",
                      "confidence": 0.9,
                      "notes": "GLP-1s require PA for T2DM...",
                      "source_url": "https://www.txvendordrug.com/formulary/prior-authorization",
                      "last_verified": "2026-04-22"
                    }
                  ],
                  "served_from": "api",
                  "timestamp": "2026-04-23T15:44:12.103Z"
                }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "429": { "$ref": "#/components/responses/RateLimit" }
        }
      }
    },
    "/v1/manifest": {
      "get": {
        "summary": "Dataset capability descriptor.",
        "description": "Returns a one-shot machine-readable description of what's available in the Auth57 corpus: total verified rule count, supported states / programs / drug classes / service categories, dataset version, last verification date, upcoming federal mandates, and pointers to other endpoints and documentation.\n\nIntentionally public (no `x-api-key` required) so SDKs and clients can discover capabilities before purchasing a subscription. Mirrors the well-known-endpoint pattern used by OAuth.\n\nCached at the edge for 1 hour (`s-maxage=3600`, `stale-while-revalidate=86400`).",
        "operationId": "manifest",
        "tags": ["Discovery"],
        "security": [],
        "responses": {
          "200": {
            "description": "Capability descriptor.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ManifestResponse" },
                "example": {
                  "service": "Auth57",
                  "version": "1",
                  "dataset": {
                    "verified_rules": 1734,
                    "service_rules": 612,
                    "drug_rules": 1122,
                    "last_verified": "2026-04-22"
                  },
                  "coverage": {
                    "states": ["AL", "AK", "AZ", "AR", "CA"],
                    "states_count": 51,
                    "programs": ["medicaid_ffs", "medicaid_mco", "medicare_advantage", "medicare_traditional", "dual_eligible", "part_d", "chip"],
                    "service_categories": ["advanced_imaging", "inpatient_hospital", "outpatient_surgery"],
                    "drug_classes": ["biosimilars", "glp1_weight_loss", "specialty_biologics"]
                  },
                  "mandates": {
                    "cms_0057_f": { "effective": "2027-01-01", "status": "final" },
                    "cms_0062_p": { "effective": "2027-10-01", "status": "proposed" }
                  },
                  "endpoints": {
                    "pa_lookup":      "GET /v1/pa-lookup?state&program&drug|service",
                    "compare":        "GET /v1/compare?states&program&drug|service",
                    "states":         "GET /v1/states[?state=XX]",
                    "manifest":       "GET /v1/manifest",
                    "lookup_options": "GET /v1/lookup-options?state&program"
                  },
                  "docs": {
                    "openapi": "https://auth57labs.com/openapi.json",
                    "reference": "https://auth57labs.com/api-reference",
                    "sdk": "https://www.npmjs.com/package/@auth57labs/sdk"
                  }
                }
              }
            }
          }
        }
      }
    },
    "/v1/states": {
      "get": {
        "summary": "State-level PA coverage metadata.",
        "description": "Without `state` parameter: returns a list of all 51 states with rule counts, PA-required percentage, and policy flags (Medicaid expansion, FFS-dominant, WISER).\n\nWith `state` parameter: returns a detailed breakdown for one state including flags, summary (totals, programs covered, PA-type histogram, federal-protected drug classes, last-verified date), per-service-category PA counts, and per-drug-class PA counts.\n\nNo authentication required. Cached at the edge for 1 hour (`s-maxage=3600`).",
        "operationId": "states",
        "tags": ["Discovery"],
        "security": [],
        "parameters": [
          {
            "name": "state",
            "in": "query",
            "required": false,
            "description": "Optional USPS 2-letter state abbreviation. Omit for the list of all 51 states; supply for a single-state breakdown.",
            "schema": { "type": "string", "pattern": "^[A-Z]{2}$", "example": "TX" }
          }
        ],
        "responses": {
          "200": {
            "description": "State summary. Returns the list form when `state` is omitted, the detail form when `state` is supplied.",
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    { "$ref": "#/components/schemas/StatesListV1Response" },
                    { "$ref": "#/components/schemas/StateSummaryResponse" }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid state code.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/Error" },
                "example": { "error": "Invalid state" }
              }
            }
          }
        }
      }
    },
    "/v1/lookup-options": {
      "get": {
        "summary": "Available drug classes and service categories for a (state, program) pair.",
        "description": "Returns the subset of `drug_class_code` and `service_category` values that actually have published rules for the given (state, program) combination, each paired with a human-readable label suitable for dropdown UIs.\n\nUse this to populate dependent selectors — pick a state and program first, then call this endpoint to know which drug/service options will resolve in `/v1/pa-lookup`.\n\nNo authentication required. Cached at the edge for 5 minutes (`s-maxage=300`).",
        "operationId": "lookupOptions",
        "tags": ["Discovery"],
        "security": [],
        "parameters": [
          {
            "name": "state",
            "in": "query",
            "required": true,
            "description": "USPS 2-letter state abbreviation.",
            "schema": { "type": "string", "pattern": "^[A-Z]{2}$", "example": "TX" }
          },
          { "$ref": "#/components/parameters/Program" }
        ],
        "responses": {
          "200": {
            "description": "Available options. Both arrays may be empty if no rules are published for the (state, program) pair.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/LookupOptionsResponse" },
                "example": {
                  "drugs": [
                    { "val": "glp1_weight_loss", "label": "GLP-1 — Weight Loss" },
                    { "val": "diabetes_insulin", "label": "Insulin / Diabetes" }
                  ],
                  "services": [
                    { "val": "advanced_imaging", "label": "Advanced Imaging" },
                    { "val": "inpatient_hospital", "label": "Inpatient Hospital" }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Missing or invalid `state` / `program`.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/Error" },
                "example": { "error": "state and program required" }
              }
            }
          }
        }
      }
    },
    "/v1/topics": {
      "get": {
        "summary": "List cross-state pivot topics (drug classes, code families, services, regulations).",
        "description": "Returns the catalog of approved Auth57 topics — each one is a matcher across the bulletin-event corpus that lets you ask 'what's every state doing on X?'. Use the returned `slug` with `/v1/topics/{slug}` to get the per-state position grid.\n\nTopics are anchored where possible to standard taxonomies (RxNorm VA classes, ATC drug classes) — the `taxonomy_link` field shows the anchor. Match counts reflect the live corpus and grow as more state bulletins are extracted.",
        "operationId": "listTopics",
        "tags": ["Topics"],
        "security": [{ "ApiKeyAuth": [] }],
        "responses": {
          "200": {
            "description": "List of approved topics with live match counts.",
            "content": {
              "application/json": {
                "example": {
                  "topics": [
                    { "slug": "glp1", "display_name": "GLP-1 receptor agonists", "kind": "drug_class", "description": "GLP-1 receptor agonists used for type 2 diabetes and weight management.", "taxonomy_link": "rxnorm:A10BJ", "match_count": 1, "jurisdiction_count": 1 },
                    { "slug": "biologic-asthma", "display_name": "Biologic asthma therapies", "kind": "drug_class", "description": "Targeted biologics for severe asthma (anti-IgE, anti-IL-5, anti-IL-4Rα, anti-TSLP).", "taxonomy_link": null, "match_count": 2, "jurisdiction_count": 1 },
                    { "slug": "wiser-model", "display_name": "CMS WISeR Model", "kind": "regulation", "description": "Wasteful and Inappropriate Service Reduction Model — live in 6 states (AZ/NJ/OH/OK/TX/WA) effective Jan 5 2026.", "taxonomy_link": null, "match_count": 0, "jurisdiction_count": 0 }
                  ]
                }
              }
            }
          },
          "401": { "description": "Missing or invalid `x-api-key`.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/v1/topics/{slug}": {
      "get": {
        "summary": "Topic detail: 51-state position grid for a given topic.",
        "description": "Returns the topic definition plus a per-jurisdiction summary: event count, latest issued/effective/compliance dates, and a status hint (`expanding`, `contracting`, `rule_change`, `rate_change`, `active`, `no_data`). Includes up to 50 sample events with `matched_on` reasons explaining why each event was tagged for this topic.",
        "operationId": "getTopic",
        "tags": ["Topics"],
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "slug",
            "in": "path",
            "required": true,
            "description": "Topic slug (lowercase, hyphens). Use `/v1/topics` to discover slugs.",
            "schema": { "type": "string", "pattern": "^[a-z0-9-]+$", "example": "glp1" }
          }
        ],
        "responses": {
          "200": {
            "description": "Topic detail with per-jurisdiction grid and sample events.",
            "content": {
              "application/json": {
                "example": {
                  "topic": { "slug": "glp1", "display_name": "GLP-1 receptor agonists", "kind": "drug_class", "description": "GLP-1 receptor agonists for type 2 diabetes and weight management.", "taxonomy_link": "rxnorm:A10BJ" },
                  "by_jurisdiction": {
                    "OK": { "count": 1, "latest_event_at": "2025-04-25", "latest_effective_at": "2025-05-01", "latest_compliance_at": null, "latest_event_kind": "payer_responsibility_clarification", "status_hint": "active" },
                    "TX": { "count": 0, "latest_event_at": null, "latest_effective_at": null, "latest_compliance_at": null, "latest_event_kind": null, "status_hint": "no_data" }
                  },
                  "states_with_data": ["OK"],
                  "states_without_data": ["AL", "AK", "AZ", "..."],
                  "total_matches": 1,
                  "sample_events": [
                    {
                      "id": 365,
                      "jurisdiction": "OK",
                      "event_kind": "payer_responsibility_clarification",
                      "event_title": "SoonerSelect Service Process Change to Remove GLP1 Medications From Drug Maintenance List",
                      "issued_at": "2025-04-25",
                      "effective_at": "2025-05-01",
                      "mmc_compliance_at": null,
                      "comment_deadline": null,
                      "pa_relevant": true,
                      "source_url": null,
                      "matched_on": ["term:GLP1"]
                    }
                  ]
                }
              }
            }
          },
          "400": { "description": "Invalid slug." },
          "401": { "description": "Missing or invalid `x-api-key`." },
          "404": { "description": "Topic not found or not in `approved` status." }
        }
      }
    },
    "/v1/pa-lookup": {
      "get": {
        "summary": "Deprecated alias for /v1/pauth-lookup.",
        "description": "Returns the same payload as `/v1/pauth-lookup`. Kept for back-compat; prefer the canonical path in new integrations.",
        "operationId": "paLookupAlias",
        "deprecated": true,
        "tags": ["Lookup"],
        "parameters": [
          { "$ref": "#/components/parameters/State" },
          { "$ref": "#/components/parameters/Program" },
          { "$ref": "#/components/parameters/Drug" },
          { "$ref": "#/components/parameters/Service" }
        ],
        "responses": {
          "200": { "description": "Rule found. Response shape matches `/v1/pauth-lookup`.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PaLookupResponse" } } } },
          "400": { "description": "Invalid parameters." },
          "401": { "description": "Missing or invalid `x-api-key`." },
          "404": { "description": "No verified rule for this (state, program, drug|service)." }
        }
      }
    },
    "/v1/ask": {
      "post": {
        "summary": "Free-text question against the verified PA corpus.",
        "description": "POSTs a natural-language question and returns a structured answer grounded in the verified corpus. Use this when the client doesn't yet know (state, program, drug|service); the server attempts to extract them and respond with a rule or a clarifying request.\n\nIntended for agent integrations and chat surfaces. Token budget per request is bounded; large transcripts should be chunked client-side.",
        "operationId": "ask",
        "tags": ["Lookup"],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["question"],
                "properties": {
                  "question": { "type": "string", "description": "Free-text question." },
                  "state": { "type": "string", "description": "Optional 2-letter state hint." },
                  "program": { "type": "string", "description": "Optional program hint." }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Structured answer + citations." },
          "400": { "description": "Missing or malformed question." },
          "401": { "description": "Missing or invalid `x-api-key`." }
        }
      }
    },
    "/v1/drug-crosswalk": {
      "get": {
        "summary": "Drug brand ↔ generic ↔ class crosswalk.",
        "description": "Resolves a drug class to its constituent brand/generic names (via RxNorm-backed `drug_ingredients`), or a brand/generic name back to its drug class. Use to normalize free-text drug inputs before calling `/v1/pauth-lookup`.",
        "operationId": "drugCrosswalk",
        "tags": ["Discovery"],
        "parameters": [
          { "name": "class", "in": "query", "description": "drug_class_code to expand into brand/generic members.", "schema": { "type": "string" } },
          { "name": "brand", "in": "query", "description": "Brand name to resolve to a drug_class_code.", "schema": { "type": "string" } },
          { "name": "generic", "in": "query", "description": "Generic name to resolve to a drug_class_code.", "schema": { "type": "string" } },
          { "name": "format", "in": "query", "description": "Response shape — `flat` (default) or `grouped`.", "schema": { "type": "string", "enum": ["flat", "grouped"] } }
        ],
        "responses": {
          "200": { "description": "Crosswalk rows." },
          "400": { "description": "Provide exactly one of class/brand/generic." }
        }
      }
    },
    "/api/v1/compliance/{rule_id}": {
      "get": {
        "summary": "Per-jurisdiction compliance grid against a CMS rule.",
        "description": "For a given CMS announcement (CMS-0057-F, CMS-0062-P, etc.), computes each US jurisdiction's implementation status. Status values: `in_compliance`, `partial`, `overdue`, `not_yet_due`, `unknown`. Public — no API key required.",
        "operationId": "complianceByRuleId",
        "tags": ["Metadata"],
        "security": [],
        "parameters": [
          { "name": "rule_id", "in": "path", "required": true, "description": "CMS rule identifier, e.g. `CMS-0057-F` or `CMS-0062-P`.", "schema": { "type": "string", "pattern": "^[A-Z0-9-]{3,32}$" } }
        ],
        "responses": {
          "200": { "description": "Compliance grid + summary counts." },
          "400": { "description": "Invalid rule_id format." },
          "404": { "description": "No announcement_events found for this rule_id." }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "x-api-key",
        "description": "API key as a UUID. Obtain at https://auth57.io/subscribe-api or request demo access via https://auth57.io/book."
      }
    },
    "parameters": {
      "State": {
        "name": "state",
        "in": "query",
        "required": true,
        "description": "USPS 2-letter state abbreviation.",
        "schema": { "type": "string", "pattern": "^[A-Z]{2}$", "example": "TX" }
      },
      "Program": {
        "name": "program",
        "in": "query",
        "required": true,
        "description": "Insurance program.",
        "schema": {
          "type": "string",
          "enum": ["medicaid_mco", "medicaid_ffs", "medicare_advantage", "medicare_traditional", "dual_eligible", "part_d", "chip"],
          "example": "medicaid_mco"
        }
      },
      "Drug": {
        "name": "drug",
        "in": "query",
        "required": false,
        "description": "`drug_class_code` enum. Provide exactly one of `drug` or `service`. One of 20 canonical drug classes published in the corpus.",
        "schema": {
          "type": "string",
          "enum": [
            "adhd_stimulants",
            "biosimilars",
            "brand_name_no_generic",
            "brand_name_with_generic",
            "compounded_medications",
            "controlled_schedule_ii",
            "controlled_schedule_iii_v",
            "diabetes_insulin",
            "diabetes_non_insulin",
            "glp1_weight_loss",
            "hepatitis_c",
            "hiv_antiretrovirals",
            "immunosuppressants",
            "mental_health_antidepressants",
            "mental_health_antipsychotics",
            "oncology_oral",
            "opioid_treatment",
            "rare_disease_orphan",
            "specialty_biologics",
            "specialty_non_biologic"
          ],
          "example": "glp1_weight_loss"
        }
      },
      "Service": {
        "name": "service",
        "in": "query",
        "required": false,
        "description": "`service_category` enum. Provide exactly one of `drug` or `service`. One of 20 canonical service categories published in the corpus.",
        "schema": {
          "type": "string",
          "enum": [
            "advanced_imaging",
            "ambulance_transport",
            "behavioral_health_inpatient",
            "behavioral_health_outpatient",
            "dental",
            "diagnostic_imaging",
            "durable_medical_equipment",
            "home_health",
            "hospice",
            "inpatient_hospital",
            "laboratory",
            "long_term_care",
            "occupational_therapy",
            "outpatient_surgery",
            "pharmacy_standard",
            "physical_therapy",
            "skilled_nursing_facility",
            "specialty_drugs",
            "speech_therapy",
            "substance_use_treatment"
          ],
          "example": "diagnostic_imaging"
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Invalid parameters (missing required field, bad format, conflicting drug+service).",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
      },
      "Unauthorized": {
        "description": "Missing or invalid `x-api-key`.",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" }, "example": { "error": "Invalid API key" } } }
      },
      "Forbidden": {
        "description": "The requested state, program, or endpoint is not included in your subscription.",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" }, "example": { "error": "TX not in your subscription" } } }
      },
      "NotFound": {
        "description": "No verified rule exists for this (state, program, drug_or_service) combination. Consider falling back to the state's provider manual (linked in previous lookups) or contacting the plan.",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" }, "example": { "error": "Rule not found" } } }
      },
      "RateLimit": {
        "description": "Rate limit exceeded.",
        "headers": {
          "Retry-After": {
            "description": "Seconds until you can retry.",
            "schema": { "type": "integer", "example": 3600 }
          }
        },
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/RateLimitError" },
            "example": { "error": "Rate limit exceeded", "limit": 10000, "window": "1 hour", "retry_after_seconds": 3600 }
          }
        }
      }
    },
    "schemas": {
      "PaRule": {
        "type": "object",
        "required": ["pa_required", "source_url", "last_verified"],
        "properties": {
          "pa_required": { "type": "boolean", "description": "Whether this (state, program, drug_or_service) requires prior authorization." },
          "pa_type": {
            "type": "string",
            "enum": ["full", "conditional", "step_therapy", "quantity_limit", "notification_only", "none"],
            "description": "When PA is required, the type of authorization needed."
          },
          "confidence": { "type": "number", "minimum": 0, "maximum": 1, "description": "Verification confidence (0–1). Values ≥0.8 are considered high-confidence.", "example": 0.9 },
          "notes": { "type": "string", "description": "Plain-language explanation of the rule — criteria, exceptions, common caveats." },
          "source_url": { "type": "string", "format": "uri", "description": "Authoritative source the rule was verified against. Cite this URL when quoting the rule." },
          "last_verified": { "type": "string", "format": "date", "description": "Date Auth57 last confirmed this rule against the source." },
          "federal_override": { "oneOf": [{ "type": "boolean" }, { "type": "string" }], "description": "True (or a description string) when a federal mandate overrides the state/plan rule for this entry." }
        }
      },
      "NextStep": {
        "type": "object",
        "required": ["step", "title", "items"],
        "properties": {
          "step": { "type": "integer", "example": 1 },
          "title": { "type": "string", "example": "Gather clinical documentation" },
          "items": { "type": "array", "items": { "type": "string" } }
        }
      },
      "PaLookupResponse": {
        "type": "object",
        "required": ["state", "program", "query", "result", "next_steps", "served_from", "timestamp"],
        "properties": {
          "state": { "type": "string", "example": "TX" },
          "program": { "type": "string", "example": "medicaid_mco" },
          "query": {
            "type": "object",
            "oneOf": [
              { "properties": { "drug_class": { "type": "string" } }, "required": ["drug_class"] },
              { "properties": { "service_category": { "type": "string" } }, "required": ["service_category"] }
            ]
          },
          "result": { "$ref": "#/components/schemas/PaRule" },
          "next_steps": { "type": "array", "items": { "$ref": "#/components/schemas/NextStep" } },
          "served_from": { "type": "string", "enum": ["static", "edge"], "description": "`static` = served from pre-built edge CDN (fastest). `edge` = served from live Supabase query." },
          "timestamp": { "type": "string", "format": "date-time" }
        }
      },
      "CompareStateResult": {
        "allOf": [
          { "$ref": "#/components/schemas/PaRule" },
          { "type": "object", "required": ["state_abbr"], "properties": { "state_abbr": { "type": "string", "example": "TX" } } }
        ]
      },
      "CompareSummary": {
        "type": "object",
        "required": ["total", "require_pa", "no_pa", "divergence", "divergence_summary"],
        "properties": {
          "total": { "type": "integer", "description": "Number of states that returned a rule." },
          "require_pa": { "type": "integer" },
          "no_pa": { "type": "integer" },
          "divergence": { "type": "boolean", "description": "True if the requested states disagree on PA requirement." },
          "divergence_summary": { "type": "string", "example": "4 of 5 states require PA. OH is an outlier." }
        }
      },
      "CompareResponse": {
        "type": "object",
        "required": ["states", "program", "query", "summary", "results", "served_from", "timestamp"],
        "properties": {
          "states": { "type": "array", "items": { "type": "string" } },
          "program": { "type": "string" },
          "query": { "type": "object" },
          "summary": { "$ref": "#/components/schemas/CompareSummary" },
          "results": { "type": "array", "items": { "$ref": "#/components/schemas/CompareStateResult" } },
          "served_from": { "type": "string" },
          "timestamp": { "type": "string", "format": "date-time" }
        }
      },
      "StateListItem": {
        "type": "object",
        "properties": {
          "abbr": { "type": "string", "example": "TX" },
          "name": { "type": "string", "example": "Texas" },
          "total_rules": { "type": "integer", "example": 34 },
          "pa_required_pct": { "type": "integer", "nullable": true, "example": 58 },
          "non_expansion": { "type": "boolean" },
          "ffs_dominant": { "type": "boolean" },
          "wiser": { "type": "boolean", "description": "State-specific WISER (work, income, support, enrollment review) flag." }
        }
      },
      "StatesListResponse": {
        "type": "object",
        "properties": {
          "states": { "type": "array", "items": { "$ref": "#/components/schemas/StateListItem" } }
        }
      },
      "StateDetailResponse": {
        "type": "object",
        "properties": {
          "state": { "type": "string", "example": "TX" },
          "name": { "type": "string", "example": "Texas" },
          "flags": { "type": "object", "properties": { "non_expansion": { "type": "boolean" }, "ffs_dominant": { "type": "boolean" }, "wiser": { "type": "boolean" } } },
          "summary": { "type": "object", "properties": {
            "total_rules": { "type": "integer" },
            "pa_required_count": { "type": "integer" },
            "pa_required_pct": { "type": "integer", "nullable": true },
            "programs_covered": { "type": "array", "items": { "type": "string" } },
            "pa_type_breakdown": { "type": "object", "additionalProperties": { "type": "integer" } },
            "federal_protected_classes_with_pa": { "type": "array", "items": { "type": "string" } },
            "last_verified": { "type": "string", "format": "date", "nullable": true }
          } },
          "services": { "type": "object", "additionalProperties": { "type": "object" } },
          "drugs": { "type": "object", "additionalProperties": { "type": "object" } }
        }
      },
      "ManifestResponse": {
        "type": "object",
        "required": ["service", "version", "dataset", "coverage", "mandates", "endpoints", "docs"],
        "properties": {
          "service": { "type": "string", "example": "Auth57", "description": "Stable service identifier." },
          "version": { "type": "string", "example": "1", "description": "API major version." },
          "dataset": {
            "type": "object",
            "required": ["verified_rules", "service_rules", "drug_rules", "last_verified"],
            "properties": {
              "verified_rules": { "type": "integer", "description": "Total published rules across `pa_rules` and `drug_pa_rules`." },
              "service_rules":  { "type": "integer", "description": "Published rows in the service-category corpus (`pa_rules`)." },
              "drug_rules":     { "type": "integer", "description": "Published rows in the drug-class corpus (`drug_pa_rules`)." },
              "last_verified":  { "type": "string", "format": "date", "nullable": true, "description": "Most recent `last_verified` date across the corpus." }
            }
          },
          "coverage": {
            "type": "object",
            "required": ["states", "states_count", "programs", "service_categories", "drug_classes"],
            "properties": {
              "states":             { "type": "array", "items": { "type": "string" }, "description": "USPS abbreviations of every covered state (51, including DC)." },
              "states_count":       { "type": "integer", "example": 51 },
              "programs":           { "type": "array", "items": { "type": "string" }, "description": "Insurance program codes accepted by `program` query parameters." },
              "service_categories": { "type": "array", "items": { "type": "string" }, "description": "Canonical service category codes accepted by the `service` query parameter." },
              "drug_classes":       { "type": "array", "items": { "type": "string" }, "description": "Canonical drug class codes accepted by the `drug` query parameter." }
            }
          },
          "mandates": {
            "type": "object",
            "description": "Federal interoperability mandates the dataset is benchmarked against.",
            "additionalProperties": {
              "type": "object",
              "properties": {
                "effective": { "type": "string", "format": "date" },
                "status": { "type": "string", "enum": ["final", "proposed"] }
              }
            }
          },
          "endpoints": {
            "type": "object",
            "description": "Human-readable map of available endpoints (method + path + parameter sketch).",
            "additionalProperties": { "type": "string" }
          },
          "docs": {
            "type": "object",
            "description": "Pointers to spec, reference UI, and the official SDK.",
            "properties": {
              "openapi":   { "type": "string", "format": "uri" },
              "reference": { "type": "string", "format": "uri" },
              "sdk":       { "type": "string", "format": "uri" }
            }
          }
        }
      },
      "StateListEntry": {
        "type": "object",
        "required": ["abbr", "name", "total_rules", "pa_required_pct", "non_expansion", "ffs_dominant", "wiser"],
        "properties": {
          "abbr":            { "type": "string", "example": "TX", "description": "USPS 2-letter abbreviation." },
          "name":            { "type": "string", "example": "Texas" },
          "total_rules":     { "type": "integer", "example": 34, "description": "Count of published rules (services + drugs) for this state." },
          "pa_required_pct": { "type": "integer", "example": 58, "description": "Percentage of this state's rules that require PA. Returns 0 when there are no rules yet." },
          "non_expansion":   { "type": "boolean", "description": "True for the 9 non-Medicaid-expansion states." },
          "ffs_dominant":    { "type": "boolean", "description": "True for states where fee-for-service Medicaid (not MCO) is the dominant delivery model." },
          "wiser":           { "type": "boolean", "description": "True for states with WISER (work, income, support, enrollment review) requirements layered onto Medicaid." }
        }
      },
      "StatesListV1Response": {
        "type": "object",
        "required": ["states"],
        "properties": {
          "states": {
            "type": "array",
            "description": "All 51 states (including DC), one entry each.",
            "items": { "$ref": "#/components/schemas/StateListEntry" }
          }
        }
      },
      "StateSummaryFlags": {
        "type": "object",
        "required": ["non_expansion", "ffs_dominant", "wiser"],
        "properties": {
          "non_expansion": { "type": "boolean" },
          "ffs_dominant":  { "type": "boolean" },
          "wiser":         { "type": "boolean" }
        }
      },
      "StateSummaryStats": {
        "type": "object",
        "required": ["total_rules", "pa_required_count", "pa_required_pct", "programs_covered", "pa_type_breakdown", "federal_protected_classes_with_pa", "last_verified"],
        "properties": {
          "total_rules":       { "type": "integer", "description": "Total published rules (services + drugs) for this state." },
          "pa_required_count": { "type": "integer", "description": "Subset of `total_rules` where `pa_required` is true." },
          "pa_required_pct":   { "type": "integer", "nullable": true, "description": "Percentage of rules requiring PA. Null when `total_rules` is 0." },
          "programs_covered":  { "type": "array", "items": { "type": "string" }, "description": "Distinct `program_type` values present in this state's rules." },
          "pa_type_breakdown": { "type": "object", "additionalProperties": { "type": "integer" }, "description": "Histogram of `pa_type` across rules where PA is required (e.g. `{ \"full\": 12, \"step_therapy\": 4 }`)." },
          "federal_protected_classes_with_pa": { "type": "array", "items": { "type": "string" }, "description": "Drug class codes flagged with `federal_override` where the state still requires PA — useful for compliance review." },
          "last_verified":     { "type": "string", "format": "date", "nullable": true, "description": "Most recent `last_verified` across this state's rules." }
        }
      },
      "StateServiceBreakdown": {
        "type": "object",
        "required": ["required", "total"],
        "properties": {
          "required": { "type": "integer", "description": "Number of program/service rows in this category that require PA." },
          "total":    { "type": "integer", "description": "Total program/service rows in this category." }
        }
      },
      "StateDrugBreakdown": {
        "type": "object",
        "required": ["required", "total"],
        "properties": {
          "required":         { "type": "integer", "description": "Number of program/drug rows in this class that require PA." },
          "total":            { "type": "integer", "description": "Total program/drug rows in this class." },
          "federal_override": { "oneOf": [{ "type": "boolean" }, { "type": "string" }], "description": "True (or descriptive string) if a federal mandate overrides state rules for this drug class." }
        }
      },
      "StateSummaryResponse": {
        "type": "object",
        "required": ["state", "name", "flags", "summary", "services", "drugs"],
        "properties": {
          "state":    { "type": "string", "example": "TX" },
          "name":     { "type": "string", "example": "Texas" },
          "flags":    { "$ref": "#/components/schemas/StateSummaryFlags" },
          "summary":  { "$ref": "#/components/schemas/StateSummaryStats" },
          "services": {
            "type": "object",
            "description": "Per-service-category PA breakdown. Keys are `service_category` codes.",
            "additionalProperties": { "$ref": "#/components/schemas/StateServiceBreakdown" }
          },
          "drugs": {
            "type": "object",
            "description": "Per-drug-class PA breakdown. Keys are `drug_class_code` values.",
            "additionalProperties": { "$ref": "#/components/schemas/StateDrugBreakdown" }
          }
        }
      },
      "LookupOption": {
        "type": "object",
        "required": ["val", "label"],
        "properties": {
          "val":   { "type": "string", "description": "Canonical code (e.g. `glp1_weight_loss`, `inpatient_hospital`). Pass this back to `/v1/pa-lookup` as `drug` or `service`." },
          "label": { "type": "string", "description": "Human-readable label suitable for a dropdown option." }
        }
      },
      "LookupOptionsResponse": {
        "type": "object",
        "required": ["drugs", "services"],
        "properties": {
          "drugs":    { "type": "array", "items": { "$ref": "#/components/schemas/LookupOption" }, "description": "Drug classes with published rules for this (state, program). Empty when none exist." },
          "services": { "type": "array", "items": { "$ref": "#/components/schemas/LookupOption" }, "description": "Service categories with published rules for this (state, program). Empty when none exist." }
        }
      },
      "Error": {
        "type": "object",
        "required": ["error"],
        "properties": {
          "error": { "type": "string" },
          "message": { "type": "string" },
          "signup_url": { "type": "string", "format": "uri" }
        }
      },
      "RateLimitError": {
        "type": "object",
        "required": ["error", "limit", "window", "retry_after_seconds"],
        "properties": {
          "error": { "type": "string", "example": "Rate limit exceeded" },
          "limit": { "type": "integer", "example": 10000 },
          "window": { "type": "string", "example": "1 hour" },
          "retry_after_seconds": { "type": "integer", "example": 3600 }
        }
      }
    }
  }
}
