"""
Verzi Healthcare Data API — Python example.

Fetches hospitals in California, iterates the paginated results,
and screens each hospital's NPI against OIG exclusions. Real,
working code — copy-paste and run after setting VERZI_API_KEY.

Requires: httpx (pip install httpx)

Get a free API key: https://api.healthcaredata.io/signup
Full API reference:  https://api.healthcaredata.io/docs
"""

import os
import time

import httpx

API_KEY = os.environ["VERZI_API_KEY"]
BASE_URL = "https://api.healthcaredata.io"
HEADERS = {"X-API-Key": API_KEY}


def search_hospitals(state: str, page_size: int = 100):
    """Yield every hospital in a state, handling pagination automatically."""
    offset = 0
    with httpx.Client(base_url=BASE_URL, headers=HEADERS, timeout=30) as client:
        while True:
            resp = client.get(
                "/hospitals",
                params={"state": state, "limit": page_size, "offset": offset},
            )
            _handle_response(resp)
            data = resp.json()
            results = data.get("results", [])
            if not results:
                break
            for hospital in results:
                yield hospital
            if len(results) < page_size:
                break
            offset += page_size


def check_exclusion(npi: str) -> bool:
    """Return True if the NPI is on the OIG exclusion list."""
    with httpx.Client(base_url=BASE_URL, headers=HEADERS, timeout=10) as client:
        resp = client.get(f"/exclusions/check/{npi}")
        _handle_response(resp)
        return resp.json().get("excluded", False)


def _handle_response(resp: httpx.Response) -> None:
    """Fail-fast error handling for the demo. In production, log + retry."""
    if resp.status_code == 429:
        reset = resp.headers.get("X-RateLimit-Reset", "midnight UTC")
        raise RuntimeError(f"Rate limited. Resets at {reset}. Upgrade at /pricing.")
    if resp.status_code == 401:
        raise RuntimeError("Invalid API key. Check X-API-Key header.")
    resp.raise_for_status()


if __name__ == "__main__":
    ca_hospitals = list(search_hospitals("CA"))
    print(f"Found {len(ca_hospitals)} California hospitals")
    for h in ca_hospitals[:5]:
        stars = h.get("overall_rating") or "unrated"
        print(f"  {h['ccn']}  {h['name']:50s}  {stars}*")
