"""Standard-library client. No automatic route execution or payment."""
import json
from urllib.request import Request, urlopen

def preflight(target_url, action="read", capabilities=None, base_url="https://accessgraph.snugguppy5.chatgpt.site", api_key=None, demo=False, fresh=False, source="python-client"):
    headers = {"Content-Type": "application/json", "X-AccessGraph-Source": source,
               "User-Agent": "AccessGraphPython/0.2 (+https://accessgraph.snugguppy5.chatgpt.site/docs)"}
    if demo:
        headers["X-AccessGraph-Demo"] = "1"
    if fresh:
        headers["Cache-Control"] = "no-cache"
    if api_key:
        headers["Authorization"] = "Bearer " + api_key
    body = {"target_url": target_url, "action": action, "capabilities": capabilities or ["http"], "budget_usd": 0}
    req = Request(base_url.rstrip("/") + "/route", data=json.dumps(body).encode(), headers=headers, method="POST")
    with urlopen(req, timeout=45) as response:
        return json.load(response)

def report_outcome(receipt, success, base_url="https://accessgraph.snugguppy5.chatgpt.site", api_key=None):
    headers = {"Content-Type": "application/json",
               "User-Agent": "AccessGraphPython/0.2 (+https://accessgraph.snugguppy5.chatgpt.site/docs)"}
    if api_key:
        headers["Authorization"] = "Bearer " + api_key
    payload = {"request_id": receipt["request_id"], "feedback_token": receipt["feedback_token"], "success": bool(success)}
    req = Request(base_url.rstrip("/") + "/feedback", data=json.dumps(payload).encode(), headers=headers, method="POST")
    with urlopen(req, timeout=10) as response:
        return json.load(response)
