"""
Ontario agent-commerce sandbox sample.

Runs against deterministic, simulated x402 endpoints. It does not require
wallet credentials and does not settle on-chain.
"""

from __future__ import annotations

import json
import urllib.request

ONTARIO_BASE = "https://ontarioprotocol.com"
SANDBOX_BASE = "https://sandbox.ontarioprotocol.com"


def post_json(url: str, payload: dict) -> dict:
    req = urllib.request.Request(
        url,
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "OntarioAgentSandbox-Python/1.0",
        },
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=20) as res:
        return json.loads(res.read().decode("utf-8"))


def can_pay(scenario: str = "allow") -> dict:
    return post_json(
        f"{ONTARIO_BASE}/api/agent/can-pay",
        {
            "sandbox": True,
            "endpoint": f"{SANDBOX_BASE}/x402/{scenario}",
            "max_usdc": "0.05",
            "agent_policy": "strict",
        },
    )


def fake_settle() -> dict:
    requirements = {
        "scheme": "exact",
        "network": "base-sandbox",
        "maxAmountRequired": "10000",
        "resource": f"{SANDBOX_BASE}/x402/allow",
        "payTo": "0x0000000000000000000000000000000000000420",
        "asset": "0x0000000000000000000000000000000000000402",
    }
    payment = {
        "x402Version": 1,
        "scheme": "exact",
        "network": "base-sandbox",
        "payload": {
            "signature": "sandbox-valid",
            "authorization": {
                "from": "0xAgent",
                "to": requirements["payTo"],
                "value": requirements["maxAmountRequired"],
                "nonce": "demo",
            },
        },
    }
    return post_json(
        f"{SANDBOX_BASE}/facilitator/settle",
        {"paymentPayload": payment, "paymentRequirements": requirements},
    )


if __name__ == "__main__":
    for name in ("allow", "review", "deny"):
        print(json.dumps(can_pay(name), indent=2))
    print(json.dumps(fake_settle(), indent=2))
