"""Minimal Proofstand client: connection test, exam loop and daily heartbeat.

pip install "mcp>=1.30" httpx
PROOFSTAND_TOKEN=ps_... python proofstand_client.py test
PROOFSTAND_TOKEN=ps_... python proofstand_client.py exam medication-renewal-triage
PROOFSTAND_TOKEN=ps_... python proofstand_client.py heartbeat      # run daily, e.g. from cron
"""

import asyncio
import json
import os
import sys

import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client

URL = os.environ.get("PROOFSTAND_URL", "https://proofstand.org/mcp")
TOKEN = os.environ["PROOFSTAND_TOKEN"]          # never hard-code it
MODEL_VERSION = os.environ.get("MODEL_VERSION", "my-model-2026-12-01")  # report the exact model you run


def my_ai_decide(case: dict, how_to_answer: dict) -> dict:
    """Replace this with a call to YOUR AI, configured exactly as in production.
    Give it case["prompt"] as untrusted data and the allowed decisions; return its answer."""
    allowed = list(how_to_answer["allowed_decisions"])
    return {"decision": allowed[0], "rationale": "Replace with your AI's one- or two-sentence reason.", "actions": []}


async def call(session: ClientSession, tool: str, **args) -> dict:
    result = await session.call_tool(tool, args)
    data = result.structuredContent or json.loads(result.content[0].text)
    data = data.get("result", data) if isinstance(data, dict) else data
    if isinstance(data, dict) and data.get("error"):
        raise SystemExit(f"{tool}: {data['error']}")
    return data


async def run_exam(session, slug, readiness_check=False):
    exam = await call(session, "start_exam", certification=slug, model_version=MODEL_VERSION,
                      readiness_check=readiness_check)
    await answer_cases(session, exam["exam_id"])
    print(json.dumps(await call(session, "get_exam_result", exam_id=exam["exam_id"]), indent=2))


async def answer_cases(session, exam_id):
    while True:
        nxt = await call(session, "get_next_case", exam_id=exam_id)
        if nxt.get("done"):
            return
        ans = my_ai_decide(nxt["case"], nxt["how_to_answer"])
        await call(session, "submit_answer", exam_id=exam_id, case_id=nxt["case"]["case_id"], **ans)


async def heartbeat(session):
    hb = await call(session, "heartbeat", model_version=MODEL_VERSION)
    if "canary" in hb:
        c = hb["canary"]
        ans = my_ai_decide(c["case"], c["how_to_answer"])
        await call(session, "submit_canary", heartbeat_id=c["heartbeat_id"], decision=ans["decision"],
                   rationale=ans["rationale"])
    if "spot_exam" in hb:
        await answer_cases(session, hb["spot_exam"]["exam_id"])
    for cred in hb.get("credentials", []):
        if cred["status"] == "active":
            await call(session, "renew_credential", registry_id=cred["registry_id"])
    print(json.dumps(hb.get("notes", []), indent=2))


async def main(cmd, *args):
    headers = {"Authorization": f"Bearer {TOKEN}"}
    async with httpx.AsyncClient(headers=headers, timeout=httpx.Timeout(30, read=300)) as http:
        async with streamable_http_client(URL, http_client=http) as (read, write, _):
            async with ClientSession(read, write) as session:
                await session.initialize()
                if cmd == "test":
                    t = await call(session, "connection_test", model_version=MODEL_VERSION)
                    ans = my_ai_decide(t["case"], t["how_to_answer"])
                    print(json.dumps(await call(session, "submit_connection_test", test_id=t["test_id"], **ans), indent=2))
                elif cmd == "exam":
                    await run_exam(session, args[0])
                elif cmd == "readiness":
                    await run_exam(session, args[0], readiness_check=True)
                elif cmd == "heartbeat":
                    await heartbeat(session)


if __name__ == "__main__":
    asyncio.run(main(*(sys.argv[1:] or ["test"])))
