#!/usr/bin/env python3
"""Binary Transfer Lane for MCP - server shim (free downloadable artifact).

Given the receipt reference carried in a tools/call's arguments, verifies
the signed delivery receipt against the call, redeems the single-use
download out-of-band, re-hashes the arrived bytes, and only then lets
the tool complete.

Usage as a library:
    from server_shim import redeem_receipt
    data = redeem_receipt(base, receipt_ref, call_id)  # bytes, hash-verified
"""
import hashlib, json, urllib.error, urllib.request


def _req(base, method, path, body=None, headers=None):
    data = json.dumps(body).encode() if body is not None else None
    r = urllib.request.Request(base.rstrip("/") + path, data=data, method=method, headers=headers or {})
    try:
        with urllib.request.urlopen(r, timeout=120) as resp:
            return resp.status, resp.read()
    except urllib.error.HTTPError as e:
        return e.code, e.read()


def redeem_receipt(base, receipt_ref, call_id):
    receipt = receipt_ref["receipt"]
    st, body = _req(base, "POST", "/verify-receipt",
                    {"receipt": receipt, "signature": receipt_ref["signature"], "call_id": call_id},
                    headers={"Content-Type": "application/json"})
    if st != 200:
        raise RuntimeError(f"receipt refused: {st}")
    st, data = _req(base, "GET", "/download/" + receipt["transfer_id"],
                    headers={"X-Download-Token": receipt_ref["download_token"]})
    if st != 200:
        raise RuntimeError(f"download refused: {st}")
    if hashlib.sha256(data).hexdigest() != receipt["sha256"] or len(data) != receipt["size"]:
        raise RuntimeError("downloaded bytes failed re-hash against the receipt")
    return data
