"""RHAMI API client (Python 3.8+, standard library only).

Score your organization from your own data and pull the result into any
dashboard, data lake, or EHR-adjacent workflow.

    from rhami_client import score
    result = score(
        context={"region": "north_america", "income": "hic", "budget": "mid"},
        metrics={"pct_workforce_ai_trained": 42, "ai_governance_level": 3},
        ratings={"ethics": {"readiness": 4, "maturity": 3}},
    )
    print(result["overall"]["score"], result["overall"]["stage"])

No assessment data is stored by the API. For offline or high-volume use,
run the identical JavaScript engine (rhami.js) locally instead.
"""
import json
import urllib.request

BASE_URL = "https://www.gsasai.com/wp-json/rhami/v1"


def _request(path, body=None, base_url=BASE_URL, timeout=30):
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(
        base_url + path,
        data=data,
        method="POST" if body is not None else "GET",
        headers={"Content-Type": "application/json", "Accept": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read().decode("utf-8"))


def score(context=None, ratings=None, metrics=None, weights=None, options=None, base_url=BASE_URL):
    """POST /score. Ratings are 1-5 (0 = unknown); metrics are percentages or levels."""
    body = {"context": context or {}, "ratings": ratings or {}, "metrics": metrics or {}}
    if weights:
        body["weights"] = weights
    if options:
        body["options"] = options
    return _request("/score", body, base_url)


def instrument(base_url=BASE_URL):
    """GET /instrument: items, anchors, metric keys and definitions."""
    return _request("/instrument", None, base_url)


def tools(base_url=BASE_URL):
    """GET /tools: tool catalog, cost tiers, regions, disclosure."""
    return _request("/tools", None, base_url)


if __name__ == "__main__":
    r = score(context={"region": "north_america", "budget": "free"},
              metrics={"pct_workforce_ai_trained": 42, "ai_governance_level": 3})
    print(json.dumps(r["overall"], indent=2))
    for g in r["gaps"]:
        print("-", g["name"], g["score"], "->", g["next_step"])
