#!/usr/bin/env python3
"""Safe PHION reference flow: DISCOVER -> INTENT -> PREFLIGHT. Never pays or executes."""
import json
import urllib.request

BASE = "https://phion.systems"
HEADERS = {
    "Content-Type": "application/json",
    "User-Agent": "phion-reference-client-python/1.46.4",
    "X-PHION-Discovery-Source": "reference_client",
}

def get(path):
    with urllib.request.urlopen(urllib.request.Request(BASE + path, headers=HEADERS), timeout=15) as response:
        return json.load(response)

def post(path, payload):
    request = urllib.request.Request(BASE + path, data=json.dumps(payload).encode(), headers=HEADERS, method="POST")
    with urllib.request.urlopen(request, timeout=15) as response:
        return json.load(response)

discovery = get("/v1/discovery")
intent = post("/v1/intent", {"intent": "verify public web evidence with signed sources", "budgetUsdc": 0.005})
service = intent.get("recommendedService") or (intent.get("eligibleServices") or [None])[0]
if not service:
    raise SystemExit(json.dumps({"status": "ABSTAIN", "reason": "NO_ELIGIBLE_SERVICE"}))
preflight = post("/v1/preflight/service", {
    "serviceId": service["serviceId"],
    "input": {"url": "https://example.com"},
    "network": "eip155:8453",
    "intentId": intent["intentId"],
    "correlationId": intent["correlationId"],
})
print(json.dumps({"serviceCount": discovery["serviceCount"], "intent": intent, "preflight": preflight}, indent=2))
# Stop here. Inspect the immutable offer and payment requirements before any authorization.
