#!/usr/bin/env python3
"""AstraNL first success in one call, Python, standard library plus 'cryptography' for the offline signature check.
Calls the core estimate tool over MCP streamable HTTP (no key, no signup), then verifies the receipt offline
with the published key and online with astranl_verify_receipt."""
import hashlib, json, sys, urllib.request
URL = "https://astranl.com/mcp/streamable?profile=core"
KEYS = "https://astranl.com/.well-known/jwks.json"

def rpc(method, params, i=1):
    body = json.dumps({"jsonrpc": "2.0", "id": i, "method": method, "params": params}).encode()
    req = urllib.request.Request(URL, body, {"Content-Type": "application/json",
                                             "Accept": "application/json, text/event-stream"})
    raw = urllib.request.urlopen(req, timeout=60).read().decode()
    if raw.lstrip().startswith("event:") or raw.startswith("data:"):
        raw = [l[5:] for l in raw.splitlines() if l.startswith("data:")][-1]
    return json.loads(raw)["result"]

def canonical(x):
    return json.dumps(x, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")

def call(name, args):
    res = rpc("tools/call", {"name": name, "arguments": args})
    return json.loads(res["content"][0]["text"]), res.get("isError")

def verify_offline(answer):
    r = answer["receipt"]
    a = {k: v for k, v in answer.items() if k != "receipt"}
    ok_answer = hashlib.sha256(canonical(a)).hexdigest() == r["payload"]["answer_sha256"]
    ok_payload = hashlib.sha256(canonical(r["payload"])).hexdigest() == r["envelope"]["payload_hash"]
    jwks = json.load(urllib.request.urlopen(KEYS, timeout=30))
    jwk = [k for k in jwks["keys"] if k.get("kid") == r["key_id"]][0]
    import base64
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    pub = base64.urlsafe_b64decode(jwk["x"] + "=" * (-len(jwk["x"]) % 4))
    try:
        Ed25519PublicKey.from_public_bytes(pub).verify(bytes.fromhex(r["signature"]), canonical(r["envelope"]))
        ok_sig = True
    except Exception:
        ok_sig = False
    return {"answer_sha256": ok_answer, "payload_hash": ok_payload, "signature_with_published_key": ok_sig}

if __name__ == "__main__":
    answer, err = call("astranl_renovation_estimate_nl", {"category": "painting", "area_m2": 30, "location": "Utrecht"})
    rng = answer["answer_meta"]["range"]
    print("estimate EUR", rng["low"], rng["typical"], rng["high"], "as_of", answer["answer_meta"]["as_of"])
    print("receipt", answer["receipt"]["reference"], answer["receipt"]["state"])
    off = verify_offline(answer)
    print("offline", off)
    online, _ = call("astranl_verify_receipt", {"ref": answer["receipt"]["reference"]})
    verdict = online["integrity"]["verdict"]
    # PASS = signed and included in a signed tree head (L3); SIGNED_PENDING_INCLUSION = signed (L2), inclusion follows
    print("online", verdict, online["integrity"]["proof_level"])
    sys.exit(0 if all(off.values()) and verdict in ("PASS", "SIGNED_PENDING_INCLUSION") else 1)
