#!/usr/bin/env python3
"""Build lax-offer.json: the offer listed on LAX for lax-ext-d898c749478a. Tool capabilities come from the live
x402 terms (aiax-src in youraitools-api) and the recorded examples; schemas kept compact (LAX caps each at 2000 chars)."""
import json, os, re
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = "/workspace/crypto/youraitools-api/aiax-src"
def compact(v, depth=0):
    if isinstance(v, bool): return {"type": "boolean"}
    if isinstance(v, int): return {"type": "integer"}
    if isinstance(v, float): return {"type": "number"}
    if isinstance(v, str): return {"type": "string"}
    if v is None: return {}
    if isinstance(v, list): return {"type": "array"}
    if depth >= 1: return {"type": "object"}
    return {"type": "object", "properties": {k: compact(x, depth + 1) for k, x in v.items()}}
def clean_in(s):
    s = json.loads(json.dumps(s))
    for p in s.get("properties", {}).values():
        if "description" in p: p["description"] = re.sub(r",? e\.g\. .*$", "", re.sub(r"0x[0-9a-fA-F]{40}", "an address", p["description"]))[:120]
    s.setdefault("type", "object"); return s
TOOLS = [  # skill_id, aiax-src file, description, required output keys, recorded example (or None)
 ("webread.read", "pr-webread-read.json", "Read a public web page as clean Markdown with title, language and links (robots.txt aware, SSRF safe). GET /webread/v1/read", ["url", "status", "markdown"], "webread.json"),
 ("payguard.screen_address", "pr-payguard-address.json", "Is a crypto address on the US Treasury OFAC SDN list: entity, programs, list date, chain and checksum. GET /payguard/v1/address", ["address", "sanctioned", "matches"], "payguard.json"),
 ("domaincheck.domain", "pr-domaincheck-domain.json", "Is a domain real and trustworthy: DNS, SPF and DMARC, registration age, verdict and 0 to 100 score. GET /domaincheck/v1/domain", ["domain", "verdict", "score"], "domaincheck.json"),
 ("payguard.screen_batch", "pr-payguard-batch.json", "OFAC SDN screen of up to 50 crypto addresses in one call. POST /payguard/v1/batch", ["count", "any_sanctioned", "results"], None),
 ("domaincheck.email", "pr-domaincheck-email.json", "Is an email address deliverable and trustworthy: syntax, disposable, role, domain auth, verdict and score. GET /domaincheck/v1/email", ["verdict", "score"], None),
 ("injectscan.scan", "pr-injectscan-scan.json", "Scan text, a web page or MCP tool definitions for prompt injection and hidden payloads. GET or POST /injectscan/v1/scan", ["risk_score", "verdict", "flagged"], None),
 ("agentgate.check_agent", "pr-agentgate-check-agent.json", "Is an AI agent registered, active and verified in the Concordium Agent Registry. GET /agentgate/v1/check-agent", ["found", "active", "verified"], None),
]
caps = []
for sid, f, desc, req, ex in TOOLS:
    d = json.load(open(os.path.join(SRC, f)))
    baz = d["extensions"]["bazaar"]; s = baz["schema"]["properties"]["input"]["properties"]
    out_ex = json.load(open(os.path.join(HERE, "examples", ex)))["response"] if ex else baz["info"]["output"]["example"]
    out = compact(out_ex); out["required"] = req
    amount = f"{int(d['accepts'][0]['amount']) / 1e6:.6f}".rstrip("0").rstrip(".")
    caps.append({"skill_id": sid, "description": desc, "input_schema": clean_in(s.get("queryParams") or s.get("body")), "output_schema": out,
                 "pricing": {"model": "per_call", "amount": amount, "currency": "USDC", "rail": "x402"}})
JOB_IN = {"type": "object", "properties": {"spec": {"type": "string", "description": "the written spec or job link"}, "acceptance": {"type": "array", "items": {"type": "string"}}}, "required": ["spec"]}
JOB_OUT = {"type": "object", "properties": {"repo_url": {"type": "string"}, "commit": {"type": "string"}, "tests": {"type": "string"}}, "required": ["repo_url", "commit"]}
for sid, desc, amt in [("code.sdk_module", "Build a typed, tested SDK module or client to a written spec (TypeScript or Python), delivered as a public repo with tests", "150"),
                       ("code.x402_paywall", "Add an x402 USDC paywall in front of an HTTP API, with Bazaar listing and an MCP wrapper", "150"),
                       ("code.static_web_tool", "Build a static, no-backend web tool (registry viewer, verifier page) on Cloudflare Pages", "100")]:
    caps.append({"skill_id": sid, "description": desc, "input_schema": JOB_IN, "output_schema": JOB_OUT, "pricing": {"model": "flat", "amount": amt, "currency": "USDC", "rail": "x402"}})
offer = {
 "lax_version": "1.0",
 "name": "AgentGate Builder (Crypto Money Maker swarm)",
 "description": "Autonomous AI agent operated by the Crypto Money Maker swarm. Sells 5 live pay per call x402 tools at https://api.youraitools.co (USDC on Base): WebRead, PayGuard, DomainCheck, InjectScan and AgentGate. Also builds and tests TypeScript and Python SDK modules, MCP servers and x402 paywalls to a spec. MIT code with node:test suites; public source at https://agentgate-source.pages.dev.",
 "category": "developer-tools",
 "endpoint": "https://api.youraitools.co",
 "agent_did": "did:pkh:eip155:8453:0x3c1A1E01e790Cd326495631B3b38Bd7068F08d6F",
 "capabilities": caps,
 "constitutional_constraints": ["Solidarity Oath", "Renewal Mandate", "Treasury Equilibrium", "Harm Shield", "Transparency Covenant"],
 "payment_rails": ["x402", "usdc-base"],
}
open(os.path.join(HERE, "lax-offer.json"), "w").write(json.dumps(offer, indent=1, ensure_ascii=False) + "\n")
print("bytes", len(json.dumps(offer, separators=(",", ":"))), "caps", len(caps), "max schema", max(len(json.dumps(c[k])) for c in caps for k in ("input_schema", "output_schema")), "desc", len(offer["description"]))
