#!/usr/bin/env python3
"""Fail closed unless owners provide non-paying live Bazaar evidence.

This tool never calls a public endpoint, facilitator, or wallet.  An owner may
supply captured results from CDP's read-only /validate endpoint and a redacted
record of a separately authorized successful settlement.  The settlement is
needed because validation itself neither pays nor indexes a resource.
"""
import argparse
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
BAZAAR = ROOT / "pr7" / "generated" / "coinbase-bazaar-v2.json"
READINESS = ROOT / "pr7" / "generated" / "bazaar-readiness.json"
DEFAULT_EVIDENCE = ROOT / "pr7" / "evidence" / "bazaar-live-evidence.json"


def fail(message):
    raise SystemExit(f"NOT READY: {message}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--evidence", type=Path, default=DEFAULT_EVIDENCE)
    args = parser.parse_args()
    readiness = json.loads(READINESS.read_text())
    blocked = readiness.get("blockedRoutes", [])
    if blocked:
        fail(f"{len(blocked)} paid route(s) have unresolved Bazaar metadata; add source-backed input schemas/examples before live validation")
    if not args.evidence.is_file():
        fail(f"owner-provided evidence is absent: {args.evidence.relative_to(ROOT)}")
    evidence = json.loads(args.evidence.read_text())
    resources = {(item["method"], item["resource"]) for item in json.loads(BAZAAR.read_text())["resources"]}
    checks = evidence.get("validation", [])
    validated = set()
    for check in checks:
        key = (check.get("method"), check.get("resource"))
        if key not in resources:
            fail(f"validation evidence names unknown candidate {key}")
        if check.get("valid") is not True or check.get("statusCode") != 402 or check.get("x402Version") != 2:
            fail(f"validation evidence does not prove public x402 v2 402 for {key}")
        if check.get("simulation", {}).get("outcome") != "accepted":
            fail(f"facilitator simulation not accepted for {key}")
        required = [item for item in check.get("preflight", []) if item.get("severity") == "required"]
        if not required or any(item.get("passed") is not True for item in required):
            fail(f"required preflight checks failed or are absent for {key}")
        validated.add(key)
    if validated != resources:
        fail(f"validation evidence incomplete: {len(validated)}/{len(resources)} candidates")
    settlements = evidence.get("settlements", [])
    settled = {(item.get("method"), item.get("resource")) for item in settlements if item.get("resourceIncluded") is True and item.get("bazaarStatus") in {"success", "processing"}}
    if not settled:
        fail("no successful settled payment with paymentPayload.resource and accepted Bazaar status")
    print(f"READY: {len(validated)} candidates passed read-only validation; {len(settled)} authorized settled resource(s) may be eligible for indexing")


if __name__ == "__main__":
    main()
