"""Buyer-side x402 v2 example for AARN. No AARN owner wallet is ever used.

Default mode previews a no-signature HTTP 402; it cannot spend.
Only --pay explicitly enables the buyer's own signer and the upstream SDK.
Install for the buyer environment: pip install 'x402[httpx,evm]>=2.25,<3' eth-account
"""
from __future__ import annotations

import argparse
import asyncio
import base64
import binascii
from decimal import Decimal, InvalidOperation
import json
import os
import re
from typing import Any

import httpx


ORIGIN = "https://api.aarn.space"
GUIDE_URL = ORIGIN + "/.well-known/aarn-buyer.json"
BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
ROUTES = {
    "web_read:v1": "/v1/web/read",
    "web_content_extraction:v1": "/v1/web-content/extract",
    "web_search:v1": "/v1/web/search",
    "web_extract_json:v1": "/v1/web/extract-json",
    "web_research:v1": "/v1/web/research",
}


def select_offering(guide: dict[str, Any], offering_id: str) -> dict[str, Any]:
    if guide.get("schema") != "aarn-buyer-integration/v1":
        raise ValueError("Unexpected buyer guide schema")
    if guide.get("protocol", {}).get("network") != "eip155:8453":
        raise ValueError("Only USDC on Base mainnet is supported")
    matched = [
        offer for offer in guide.get("offerings", [])
        if offer.get("offering_id") == offering_id
    ]
    if len(matched) != 1:
        raise ValueError("Requested offering is unavailable")
    offer = matched[0]
    if offer.get("url") != ORIGIN + ROUTES[offering_id] or offer.get("method") != "POST":
        raise ValueError("Non-canonical offering URL or method")
    if offer.get("availability") != "LIVE":
        raise ValueError("Paid offering is not active")
    if not isinstance(offer.get("example_json_body"), dict):
        raise ValueError("Missing request example")
    return offer


def validate_challenge(
    encoded: str | None, resource_url: str, cap_usdc: str,
) -> dict[str, Any]:
    """Validate decoded canonical 402 before constructing a buyer payment."""
    if not encoded:
        raise ValueError("Missing PAYMENT-REQUIRED header")
    if len(encoded) > 65536:
        raise ValueError("Oversized payment challenge")
    try:
        raw = base64.b64decode(encoded, validate=True)
        challenge = json.loads(raw)
        cap_atomic = int(Decimal(cap_usdc) * Decimal(1_000_000))
    except (ValueError, InvalidOperation, UnicodeError, binascii.Error, TypeError) as exc:
        raise ValueError("Invalid 402 challenge or price") from exc
    if not isinstance(challenge, dict):
        raise ValueError("Payment challenge must be a JSON object")
    if challenge.get("x402Version") != 2:
        raise ValueError("Unexpected x402 version")
    if challenge.get("resource", {}).get("url") != resource_url:
        raise ValueError("Unexpected payable resource")
    offers = challenge.get("accepts", [])
    if not isinstance(offers, list) or len(offers) != 1:
        raise ValueError("Ambiguous or missing payment option")
    chosen = offers[0]
    if (
        chosen.get("scheme") != "exact"
        or chosen.get("network") != "eip155:8453"
        or str(chosen.get("asset", "")).lower() != BASE_USDC.lower()
    ):
        raise ValueError("Unsupported chain, token, or payment scheme")
    amount = chosen.get("amount")
    if (
        not isinstance(amount, str)
        or not amount.isascii()
        or not amount.isdigit()
        or int(amount) < 1
        or int(amount) > cap_atomic
    ):
        raise ValueError("Payment exceeds per-request buyer cap")
    if not isinstance(chosen.get("payTo"), str):
        raise ValueError("Missing payee")
    payee = chosen["payTo"]
    if not re.fullmatch(r"0x[0-9a-fA-F]{40}", payee):
        raise ValueError("Invalid payee")
    return {
        "resource": resource_url,
        "network": chosen["network"],
        "amount_atomic": amount,
        "price_cap_usdc": cap_usdc,
        "inspected_pay_to": payee.lower(),
    }



def select_sdk_requirements(version: int, requirements: list[Any],
                            inspected: dict[str, Any]) -> list[Any]:
    """Fail-closed gate on the SECOND 402 received by x402HttpxClient.

    SDK requirement objects expose snake_case `pay_to`. No signing occurs
    unless the recipient, network, scheme, token and exact amount match
    the previously inspected challenge. Payment caps remain enforced by SDK.
    """
    if version != 2 or not isinstance(requirements, (list, tuple)):
        return []
    allowed = []
    for r in requirements:
        amount = getattr(r, "amount", None)
        pay_to = getattr(r, "pay_to", None)
        if (
            getattr(r, "scheme", None) != "exact"
            or getattr(r, "network", None) != "eip155:8453"
            or str(getattr(r, "asset", "")).lower() != BASE_USDC.lower()
            or not isinstance(amount, str)
            or amount != inspected["amount_atomic"]
            or not isinstance(pay_to, str)
            or pay_to.lower() != inspected["inspected_pay_to"]
        ):
            continue
        allowed.append(r)
    return allowed


async def invoke(offering_id: str, *, pay: bool = False) -> dict[str, Any]:
    if offering_id not in ROUTES:
        raise ValueError("Unknown offering")

    # AARN discovery and initial challenge are public/unpaid.
    async with httpx.AsyncClient(follow_redirects=False, timeout=20) as http:
        guide_response = await http.get(GUIDE_URL)
        guide_response.raise_for_status()
        offer = select_offering(guide_response.json(), offering_id)
        body = offer["example_json_body"]
        url = offer["url"]
        challenge_response = await http.post(url, json=body)
        if challenge_response.status_code != 402:
            raise ValueError("Expected an unpaid HTTP 402, no payment initiated")
        preview = validate_challenge(
            challenge_response.headers.get("PAYMENT-REQUIRED"),
            url, offer["indicative_price_usdc"],
        )
        if not pay:
            return {"mode": "PREVIEW_UNPAID", "offer": offering_id, **preview}

    # Explicit buyer opt-in only; AARN's production never runs this example.
    key = os.environ.get("BUYER_EVM_PRIVATE_KEY")
    if not key:
        raise ValueError("Buyer must supply BUYER_EVM_PRIVATE_KEY for --pay")
    from eth_account import Account
    from x402 import x402Client
    from x402.http.clients import x402HttpxClient
    from x402.mechanisms.evm import EthAccountSigner
    from x402.mechanisms.evm.exact.register import register_exact_evm_client

    signer = EthAccountSigner(Account.from_key(key))
    client = x402Client().set_spend_controls({
        "max_amount_per_payment": f"${offer['indicative_price_usdc']}",
    })
    register_exact_evm_client(client, signer)
    client.register_policy(
        lambda version, accepts: select_sdk_requirements(version, accepts, preview)
    )

    # The official SDK performs the 402 -> PAYMENT-SIGNATURE exchange.
    # Never add a second retry following a network timeout/unknown result.
    async with x402HttpxClient(client) as http:
        response = await http.post(url, json=body, timeout=150)
        await response.aread()
    if response.status_code != 200:
        raise RuntimeError(
            "Paid result not confirmed; reconcile settlement before retrying"
        )
    if not response.headers.get("PAYMENT-RESPONSE"):
        raise RuntimeError(
            "Missing settlement receipt; reconcile before any further request"
        )
    return {"mode": "BUYER_PAID", "offer": offering_id, "result": response.json()}


def main() -> None:
    parser = argparse.ArgumentParser(description="AARN x402 buyer preview / opt-in payment")
    parser.add_argument("offering_id", choices=sorted(ROUTES))
    parser.add_argument("--pay", action="store_true", help="Spend buyer funds; requires buyer wallet")
    args = parser.parse_args()
    try:
        print(json.dumps(asyncio.run(invoke(args.offering_id, pay=args.pay)), indent=2))
    except (ValueError, RuntimeError, httpx.HTTPError) as exc:
        parser.exit(1, f"STOP: {exc}\n")


if __name__ == "__main__":
    main()
