"""Public Xochi discovery and non-persisted quote preview. No wallet or writes."""
import argparse
import json
from pathlib import Path
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from uuid import UUID

api = "https://api.xochi.fi/api"
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--public-intent", type=UUID,
                    help="read status for an existing public intent you may inspect")
parser.add_argument("--json", type=Path, help="also write the preview outcome to this JSON file")
args = parser.parse_args()


def record(outcome):
    if args.json:
        args.json.write_text(json.dumps(outcome, indent=2) + "\n")


def stop(message, action):
    if not args.public_intent:
        record({"error": message})
    print(f"check-xochi: {message}", file=sys.stderr)
    print(f"fix:         {action}", file=sys.stderr)
    raise SystemExit(1)


def request(path, payload=None):
    data = None if payload is None else json.dumps(payload).encode()
    headers = {"Accept": "application/json"}
    if data is not None:
        headers["Content-Type"] = "application/json"
    try:
        with urlopen(Request(api + path, data, headers), timeout=20) as response:
            return json.load(response)
    except HTTPError:
        raise
    except (URLError, TimeoutError, OSError) as err:
        reason = getattr(err, "reason", err)
        stop(f"Xochi API unreachable ({reason}); the local mock still works",
             "check the network, then retry python3 check-xochi.py")
    except ValueError:
        stop(f"Xochi API returned something other than JSON for {path}",
             "retry python3 check-xochi.py later")


def describe(route):
    """The served route in one phrase, e.g. 8453 -> 1 public (about 30s)."""
    if not isinstance(route, dict) or not route:
        return "none served"
    phrase = f"{route.get('from_chain_id', '?')} -> {route.get('to_chain_id', '?')}"
    if route.get("settlement_type"):
        phrase += f" {route['settlement_type']}"
    if route.get("expected_fill_seconds"):
        phrase += f" (about {route['expected_fill_seconds']}s)"
    return phrase


if args.public_intent:
    try:
        status = request(f"/intent/{args.public_intent}/status")
        print("Public status:", status.get("status"), "terminal:", status.get("terminal"))
    except HTTPError as err:
        stop(f"public status unavailable (HTTP {err.code})", "retry later")
    raise SystemExit(0)

try:
    live = request("/capabilities")
except HTTPError as err:
    stop(f"Xochi capabilities unavailable (HTTP {err.code}); the local mock still works",
         "retry python3 check-xochi.py later")
capabilities = live["capabilities"]
usdc = next((token for token in capabilities["tokens"] if token["symbol"] == "USDC"), None)
if usdc is None:
    stop("Xochi no longer advertises USDC", "check live capabilities before retrying")
print("Xochi capabilities source:", live["source"], flush=True)
try:
    preview = request("/intent/quote", {
        "preview": True, "from_chain_id": 8453, "to_chain_id": 1,
        "from_token": usdc["addresses"]["8453"], "to_token": usdc["addresses"]["1"],
        "from_amount": str(25 * 10 ** usdc["decimals"]),
        "deadline": int(time.time()) + 3600, "slippage_bps": 50, "settlement_preference": "public",
    })
    route = preview.get("route") or {}
    print(f"Base → Ethereum USDC quote preview; route: {describe(route)}; "
          f"can_solve: {preview.get('can_solve')}")
    print("Preview has no settlement status.")
    record({"capabilities_source": live["source"], "route": describe(route), "route_detail": route,
            "can_solve": preview.get("can_solve")})
except HTTPError as err:
    stop(f"quote unavailable (HTTP {err.code}); the local mock still works",
         "check live routes and retry python3 check-xochi.py later")
