"""x402audit - a client-side audit record for x402 payment challenges.

The 402 response tells you a price. It is not a receipt of what you paid.
If the price moves between the quote you read and the retry you send, the
only durable record of that is the one the client writes.

Per call, this records:
  correlation_id   minted before the first attempt, carried across retries
  attempt          1, 2, ...
  decoded_at       when the challenge was read
  attempted_at     when the payment header was sent
  terms            scheme, network, amount, asset, payTo, maxTimeoutSeconds
  header_sha256    hash of the payment-required header, never the header
  payment_sha256   hash of the PAYMENT-SIGNATURE header, never the header

Run the tests:  python3 -m unittest -v test_x402audit
Live probe:     python3 x402audit.py https://example.com/api
"""

from __future__ import annotations

import base64
import hashlib
import json
import time
import urllib.request
import uuid
from dataclasses import dataclass

TERM_KEYS = ("scheme", "network", "amount", "asset", "payTo", "maxTimeoutSeconds")
_ALIASES = {"amount": ("amount", "maxAmountRequired")}


def _b64d(text: str) -> bytes:
    """Decode base64 or base64url, with or without padding."""
    s = text.strip().replace("-", "+").replace("_", "/")
    s += "=" * (-len(s) % 4)
    return base64.b64decode(s)


def sha256_hex(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


@dataclass
class Challenge:
    x402_version: int
    resource_url: str | None
    accepts: list
    error: str | None
    header_sha256: str


def decode_challenge(header_value: str) -> Challenge:
    """Decode the payment-required header (x402 v2, with v1 key fallback)."""
    raw = _b64d(header_value)
    obj = json.loads(raw)
    res = obj.get("resource")
    if isinstance(res, dict):
        resource_url = res.get("url")
    elif isinstance(res, str):
        resource_url = res
    else:
        resource_url = None
    return Challenge(
        x402_version=int(obj.get("x402Version") or obj.get("x402_version") or 0),
        resource_url=resource_url,
        accepts=list(obj.get("accepts") or []),
        error=obj.get("error"),
        header_sha256=sha256_hex(raw),
    )


def terms_of(accept: dict, keys: tuple = TERM_KEYS) -> dict:
    """The terms a client is committing to, under one stable set of names."""
    out = {}
    for key in keys:
        if key in accept:
            out[key] = accept[key]
            continue
        for alias in _ALIASES.get(key, ()):
            if alias in accept:
                out[key] = accept[alias]
                break
    return out


def payment_terms(header_value: str) -> tuple[dict | None, str]:
    """Best-effort read of what the payment header itself commits to.

    The audit must record the header the server sees, not the terms the
    client meant to send. A client that reuses a stale acceptance will
    still log the stale amount here, which is the point.

    Returns (terms, source). source is "unparsed" when the scheme's payload
    does not expose an amount in any known place; then no mismatch is
    claimed, because the record does not know.
    """
    try:
        obj = json.loads(_b64d(header_value))
    except Exception:
        return None, "unparsed"
    if not isinstance(obj, dict):
        return None, "unparsed"
    payload = obj.get("payload") if isinstance(obj.get("payload"), dict) else {}
    auth = payload.get("authorization") if isinstance(payload.get("authorization"), dict) else None
    if auth is not None and "value" in auth:
        return {
            "scheme": obj.get("scheme"),
            "network": obj.get("network"),
            "amount": auth.get("value"),
            "payTo": auth.get("to"),
        }, "payload.authorization"
    if "amount" in payload:
        return {"amount": payload.get("amount"), **{k: payload[k] for k in ("scheme", "network", "payTo") if k in payload}}, "payload"
    if "amount" in obj:
        return {"amount": obj.get("amount"), **{k: obj[k] for k in ("scheme", "network", "payTo") if k in obj}}, "top-level"
    return None, "unparsed"


def choose(challenge: Challenge, network: str | None = None, scheme: str | None = None) -> dict | None:
    for accept in challenge.accepts:
        if network and accept.get("network") != network:
            continue
        if scheme and accept.get("scheme") != scheme:
            continue
        return accept
    return challenge.accepts[0] if challenge.accepts else None


def classify(prev: dict | None, new: dict | None) -> str:
    if prev is None or new is None:
        return "unknown"
    if prev.get("amount") != new.get("amount"):
        return "price_changed"
    if prev.get("payTo") != new.get("payTo"):
        return "payto_changed"
    if prev.get("asset") != new.get("asset"):
        return "asset_changed"
    if prev.get("network") != new.get("network"):
        return "network_changed"
    return "same_terms"


class AuditLog:
    """Append-only record. One JSON object per line, one line per event."""

    def __init__(self, path: str | None = None, clock=time.time):
        self.path = path
        self.clock = clock
        self.records: list[dict] = []
        self._last_terms: dict[str, dict | None] = {}

    def _write(self, record: dict) -> None:
        record["logged_at"] = self.clock()
        self.records.append(record)
        if self.path:
            with open(self.path, "a", encoding="utf-8") as fh:
                fh.write(json.dumps(record, sort_keys=True) + "\n")

    def start(self, url: str, method: str = "GET") -> str:
        """Mint the ID before the first attempt; carry it across every retry."""
        correlation_id = str(uuid.uuid4())
        self._last_terms[correlation_id] = None
        self._write({
            "event": "start",
            "correlation_id": correlation_id,
            "url": url,
            "method": method,
        })
        return correlation_id

    def challenge(self, correlation_id: str, attempt: int, header_value: str, accept: dict | None) -> dict | None:
        decoded = decode_challenge(header_value)
        terms = terms_of(accept) if accept else None
        prev = self._last_terms.get(correlation_id)
        change = classify(prev, terms)
        self._last_terms[correlation_id] = terms
        self._write({
            "event": "challenge",
            "correlation_id": correlation_id,
            "attempt": attempt,
            "x402_version": decoded.x402_version,
            "resource_url": decoded.resource_url,
            "accepts_count": len(decoded.accepts),
            "terms": terms,
            "terms_change": change,
            "header_sha256": decoded.header_sha256,
            "decoded_at": self.clock(),
        })
        return terms

    def payment(self, correlation_id: str, attempt: int, header_value: str) -> None:
        paid, source = payment_terms(header_value)
        self._write({
            "event": "payment",
            "correlation_id": correlation_id,
            "attempt": attempt,
            "payment_sha256": sha256_hex(header_value.encode("utf-8")),
            "paid_terms": paid,
            "paid_terms_source": source,
            "attempted_at": self.clock(),
        })

    def result(self, correlation_id: str, attempt: int, status: int) -> None:
        self._write({
            "event": "result",
            "correlation_id": correlation_id,
            "attempt": attempt,
            "status": status,
        })


def mismatches(records: list[dict]) -> list[dict]:
    """Attempts where the terms sent differ from the terms last quoted.

    A non-empty list means the client paid, or tried to pay, a price it had
    not read at that attempt.
    """
    quotes: dict[tuple, dict | None] = {}
    bad = []
    for rec in records:
        key = (rec.get("correlation_id"), rec.get("attempt"))
        if rec.get("event") == "challenge":
            quotes[key] = rec.get("terms")
        elif rec.get("event") == "payment":
            quoted = quotes.get(key) or {}
            paid = rec.get("paid_terms")
            if paid is None:
                continue  # unparsed payload: the record does not know
            shared = [k for k in paid if k in quoted]
            if any(quoted[k] != paid[k] for k in shared):
                bad.append({
                    "correlation_id": rec.get("correlation_id"),
                    "attempt": rec.get("attempt"),
                    "quoted": quoted,
                    "paid": paid,
                })
    return bad


def _urllib_transport(url: str, method: str, body: bytes | None, headers: dict):
    req = urllib.request.Request(url, data=body, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            return resp.status, dict(resp.headers), resp.read()
    except urllib.error.HTTPError as exc:
        return exc.code, dict(exc.headers), exc.read()


class AuditedClient:
    """A client that logs every challenge and every payment header it sends.

    payer(accept) must return a PAYMENT-SIGNATURE value built from the
    accept it is given. A payer that ignores its argument is the bug this
    module exists to catch.
    """

    def __init__(self, audit: AuditLog, payer, transport=None):
        self.audit = audit
        self.payer = payer
        self.transport = transport or _urllib_transport

    def call(self, url, method="GET", body=None, headers=None, network=None, max_attempts=3):
        if isinstance(body, str):
            body = body.encode("utf-8")
        correlation_id = self.audit.start(url, method)
        send_headers = dict(headers or {})
        status, response_body = 0, b""
        for attempt in range(1, max_attempts + 1):
            status, response_headers, response_body = self.transport(url, method, body, send_headers)
            raw = {k.lower(): v for k, v in response_headers.items()}.get("payment-required")
            if status != 402 or not raw:
                self.audit.result(correlation_id, attempt, status)
                return status, response_body, correlation_id
            decoded = decode_challenge(raw)
            accept = choose(decoded, network=network)
            terms = self.audit.challenge(correlation_id, attempt, raw, accept)
            payment = self.payer(accept)
            self.audit.payment(correlation_id, attempt, payment)
            send_headers["PAYMENT-SIGNATURE"] = payment
        self.audit.result(correlation_id, max_attempts, status)
        return status, response_body, correlation_id


def main(argv: list[str]) -> int:
    if len(argv) != 2:
        print("usage: python3 x402audit.py <url> [method]")
        return 2
    url = argv[1]
    method = argv[2] if len(argv) > 2 else "GET"
    status, headers, _ = _urllib_transport(url, method, None, {"User-Agent": "Mozilla/5.0"})
    raw = {k.lower(): v for k, v in headers.items()}.get("payment-required")
    print(f"status: {status}")
    if not raw:
        print("no payment-required header; this route is not asking for payment")
        return 0
    decoded = decode_challenge(raw)
    print(f"x402Version: {decoded.x402_version}")
    print(f"resource: {decoded.resource_url}")
    print(f"accepts: {len(decoded.accepts)}")
    print(f"header_sha256: {decoded.header_sha256}")
    for i, accept in enumerate(decoded.accepts):
        print(f"  [{i}] {terms_of(accept)}")
    return 0


if __name__ == "__main__":
    import sys
    raise SystemExit(main(sys.argv))