#!/usr/bin/env python3
"""Generate the AIAX 0.1 manifest and Tier 1 sections for api.youraitools.co (static files under public/).
Source of truth: each tool's live x402 402 answer (bazaar input schema + recorded real output example), saved in aiax-src/*.json.
Run: python3 scripts/gen_aiax.py  (then validate: npx aiax-validate https://api.youraitools.co)"""
import json, os, datetime
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "aiax-src"); PUB = os.path.join(ROOT, "public")
BASE = "https://api.youraitools.co"
SECTIONS = [  # id, src file, purpose (short), tool name, price
 ("webread", "pr-webread-read.json", "Web", "WebRead"),
 ("payguard_address", "pr-payguard-address.json", "OFAC", "PayGuard"),
 ("payguard_batch", "pr-payguard-batch.json", "OFAC bulk", "PayGuard"),
 ("domaincheck_domain", "pr-domaincheck-domain.json", "Domain", "DomainCheck"),
 ("domaincheck_email", "pr-domaincheck-email.json", "Mail", "DomainCheck"),
 ("injectscan", "pr-injectscan-scan.json", "Inject", "InjectScan"),
 ("pkgguard_scan", "pr-pkgguard-scan.json", "Lock", "PkgGuard"),
 ("pkgguard_package", "pr-pkgguard-package.json", "Pkg", "PkgGuard"),
 ("agentgate", "pr-agentgate-check-agent.json", "Agent", "AgentGate"),
 ("stackdetect", "pr-stackdetect-detect.json", "Stack", "StackDetect"),
 ("tokenverdict", "pr-tokenverdict-quick.json", "Token", "TokenVerdict"),
 ("signcheck", "pr-signcheck-check.json", "Sign", "SignCheck"),
 ("counterpartycheck", "pr-counterpartycheck-quick.json", "Payee", "CounterpartyCheck"),
 ("x402fix", "pr-x402fix-check.json", "x402", "x402fix"),
 ("solverdict", "pr-solverdict-check.json", "SPL", "SolVerdict"),
 ("agentready", "pr-agentready-audit.json", "Site", "AgentReady"),
 ("perpradar", "pr-perpradar-lite.json", "Fund", "PerpRadar"),
 ("tasignal", "pr-tasignal-lite.json", "TA", "TASignal"),
 ("leakguard", "pr-leakguard-lite.json", "Leaks", "LeakGuard"),
 ("smartperps", "pr-smartperps-lite.json", "Whale", "SmartPerps"),
 ("toolpick", "pr-toolpick-lite.json", "Pick", "ToolPick"),
 ("perpcheck", "pr-perpcheck-lite.json", "Order", "PerpCheck"),
 ("x402_template_download", "pr-x402template-download.json", "Tmpl", "x402 Proxy Template"),
]
NO_MCP = {"x402-template"}
# Secondary routes of a tool already listed: section file still written, but left out of the manifest entry_points
# (AIAX manifest <= 600 tokens; added 2026-10-23 to fit ToolPick).
MANIFEST_SKIP = {"payguard_batch", "pkgguard_package"}
def infer(v):
    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", "items": infer(v[0]) if v else {}}
    return {"type": "object", "properties": {k: infer(x) for k, x in v.items()}}
def shrink(v):
    if isinstance(v, list): return [shrink(x) for x in v[:3]]
    if isinstance(v, dict): return {k: shrink(x) for k, x in v.items()}
    if isinstance(v, str) and len(v) > 240: return v[:240] + "..."
    return v
def usdc(atomic): return f"{int(atomic) / 1e6:.6f}".rstrip("0").rstrip(".")
def toks(o): return max(1, round(len(json.dumps(o, separators=(",", ":"))) / 4))
def write(rel, obj, compact=False):
    p = os.path.join(PUB, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
    text = json.dumps(obj, separators=(",", ":"), ensure_ascii=False) if compact else json.dumps(obj, indent=1, ensure_ascii=False)
    open(p, "w").write(text + "\n"); return obj
entries = []
for sid, f, purpose, tool in SECTIONS:
    d = json.load(open(os.path.join(SRC, f)))
    res, acc, baz = d["resource"], d["accepts"][0], d["extensions"]["bazaar"]
    inp = baz["info"]["input"]; s = baz["schema"]["properties"]["input"]["properties"]
    in_schema = dict(s.get("queryParams") or s.get("body")); in_schema.setdefault("type", "object")
    out_ex = baz["info"]["output"]["example"]
    if toks(out_ex) > 2500: out_ex = shrink(out_ex)  # long recorded outputs (AgentReady audit): keep shape, cap lists/strings so the section stays under 5000 tokens
    method = inp["method"]; url = res["url"]
    req = {"method": method, "url": url}
    if inp.get("queryParams"): req["query"] = inp["queryParams"]
    if inp.get("body") is not None: req["body"] = inp["body"]
    sec = {
        "aiax_version": "0.1", "section_id": sid,
        "purpose": (f"{tool}: {res['description']}")[:600],
        "inputs": in_schema,
        "outputs": infer(out_ex),
        "pricing": {"model": "per_call", "amount": usdc(acc["amount"]), "currency": "USDC", "rail": "x402"},
        "examples": [{"description": f"{method} {url.replace(BASE, '')}, paid over x402 (USDC on Base); an unpaid call answers 402 with the terms.", "request": req, "response": out_ex}],
        "pact_mandate_template": None,
        "mcp_tool_name": None,
        "extensions": {"youraitools": {"endpoint": url, "network": acc["network"], "x402_versions": [2, 1], **({} if url.split('/')[3] in NO_MCP else {"mcp": f"{BASE}/{url.split('/')[3]}/mcp"}), "openapi": f"{BASE}/{url.split('/')[3]}/openapi.json", **({"preview": f"{BASE}/{url.split('/')[3]}/", "response_mime": res.get("mimeType")} if url.split('/')[3] in NO_MCP else {})}},
    }
    sec.pop("mcp_tool_name")
    write(f"aiax/sections/{sid}.json", sec)
    if sid not in MANIFEST_SKIP: entries.append({"id": sid, "url": f"/aiax/sections/{sid}.json", "purpose": purpose, "est_tokens": toks(sec)})
manifest = {
    "aiax_version": "0.1",
    "product": {"name": "YourAITools API", "one_line_purpose": "x402 agent tools", "domain": "agent-tools"},
    "entry_points": entries,
    "pricing_summary": "USDC/call via x402",
    "trust_signals": {"partnerships": ["LAX"]},
    "updated_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "mcp_endpoint": None,
    "extensions": {"youraitools": {"lax_listing": "lax-ext-d898c749478a"}},
}
write(".well-known/aiax.json", manifest, True); write("aiax/manifest.json", manifest, True)  # compact: AIAX targets <= 600 tokens (openapi_url and extensions.source dropped 2026-10-22 to fit PerpRadar + TASignal; shorter purposes + pricing_summary, partnership list without directory name, contact moved out (in mcp.json), to fit LeakGuard; 1-word purposes, shorter one_line_purpose + pricing_summary 2026-10-22 to fit SmartPerps)
print("wrote manifest +", len(entries), "sections")
