#!/usr/bin/env python3
"""ChainLedger publishing engine. Stdlib only.

Subcommands:
  next              -> prints the next unpublished topic as JSON
  publish FILE.json -> publishes an article payload, rebuilds site, updates queue
  status            -> prints progress stats
  links             -> prints monetization links (fill affiliate_url in links.json)
  deploy            -> push site live via Worker publish endpoint
  indexnow          -> submit sitemap URLs to IndexNow

Article payload JSON (all strings unless noted):
{
  "slug": "best-solana-dex-low-fees-2026",
  "title": "...",
  "keyword": "...",
  "summary": "2 sentence description for meta + homepage",
  "html_body": "<p>...full article body HTML...</p>",
  "sources": ["https://...", "..."],
  "affiliate_target": "jupiter"
}
"""
import json, os, sys, html, datetime, subprocess, shlex, gzip, base64, hashlib

ROOT = os.path.dirname(os.path.abspath(__file__))
SITE = os.path.join(ROOT, "site")
ARTICLES = os.path.join(SITE, "articles")
QUEUE = os.path.join(ROOT, "queue.json")
LINKS = os.path.join(ROOT, "links.json")
CONFIG = os.path.join(ROOT, "config.json")
JOURNAL = os.path.join(ROOT, "journal.md")

def load(path):
    with open(path, encoding="utf-8") as f:
        return json.load(f)

def save(path, obj):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(obj, f, indent=2, ensure_ascii=False)
        f.write("\n")

def cfg():
    return load(CONFIG)

def esc(s):
    return html.escape(str(s), quote=True)

def base_url():
    return cfg().get("base_url", "").rstrip("/")

def cta_for(target):
    links = load(LINKS)
    entry = links.get(target) or links.get("jupiter") or {}
    url = entry.get("affiliate_url") or entry.get("url") or "#"
    label = entry.get("label", target)
    return f'<a class="cta" href="{esc(url)}" rel="nofollow noopener" target="_blank">Try {esc(label)} &rarr;</a>'

def sources_block(sources):
    if not sources:
        return ""
    items = "".join(f'<li><a href="{esc(u)}" rel="nofollow noopener" target="_blank">{esc(u)}</a></li>' for u in sources)
    return f'<div class="note"><strong>Sources &amp; data:</strong><ul>{items}</ul></div>'

def shell(title, body, description="", article=False, url=""):
    c = cfg()
    desc = description or c["tagline"]
    canonical = url or base_url() + "/"
    ld = ""
    if article:
        ld = {
          "@context": "https://schema.org", "@type": "Article",
          "headline": title, "description": desc,
          "datePublished": datetime.datetime.now(datetime.timezone.utc).isoformat(),
          "author": {"@type": "Organization", "name": c["author"]},
          "mainEntityOfPage": canonical
        }
    ld_json = '<script type="application/ld+json">' + json.dumps(ld) + "</script>" if ld else ""
    return f'''<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{esc(title)} | {esc(c['site_name'])}</title>
<meta name="description" content="{esc(desc)}">
<link rel="canonical" href="{esc(canonical)}">
<meta property="og:title" content="{esc(title)}"><meta property="og:description" content="{esc(desc)}">
<meta property="og:type" content="{"article" if article else "website"}">
<link rel="stylesheet" href="/style.css">{ld_json}
</head><body><div class="wrap">
<header><a href="/" class="brand" style="color:inherit"><b>{esc(c['site_name'])}</b></a><div class="tag">{esc(c['tagline'])}</div>
<nav class="site"><a href="/">Home</a><a href="/tools/">Tools</a><a href="/ai-agent-toolkit/">AI toolkit</a><a href="/leaderboards/">Leaderboards</a><a href="/compare/">Compare</a><a href="/papers/">Papers</a><a href="/products/">Bots</a><a href="/data/">Data</a><a href="/method/">Benchmark method</a><a href="/rpc-cost/">RPC cost</a><a href="/methodology/">Method</a></nav></header>
<main>{body}</main>
<footer><div class="footer-grid">
<div class="footer-col"><strong>Independence &amp; risk</strong><div class="meta">Site last updated: 2026-11-28</div>Independent research — not financial advice. No paid rankings; every figure links to a dated source. Paper/simulated results do not equal live trading results.</div>
<div class="footer-col"><strong>Affiliate &amp; data transparency</strong>{esc(c['disclosure'])}</div>
<div class="footer-col"><strong>Support (SOL)</strong>Optional tip address: <code>{esc(c.get('tip_address',''))}</code></div>
</div></footer>
</div></body></html>
'''

def rebuild_index():
    q = load(QUEUE)
    pub = [t for t in q if t.get("published")]
    pub.sort(key=lambda t: t.get("published_at") or "", reverse=True)
    if pub:
        items = "".join(
          f'<li><a href="/articles/{esc(t["slug"])}/">{esc(t["title"])}</a>'
          f'<div class="meta">{esc(t.get("summary",""))}</div></li>' for t in pub)
    else:
        items = '<li class="meta">First research articles publishing soon.</li>'
    body = f'''<p class="meta">levsolbotturnkey &middot; legacy handle: <code>levsolbotturnkey</code> &mdash; Solana &amp; Web3 Benchmark Ledger</p>
<h1>Web3 tools, measured.</h1>
<p class="meta">{len(pub)} researched comparison{"s" if len(pub)!=1 else ""} &middot; updated daily</p>
<p>Empirical Solana RPC benchmarks, DEX fee and slippage tests, open CSV datasets, AI-agent endpoints, and self-hosted bot packages. Every metric carries a source URL, a test date, and zero paid rankings.</p>

<h2>Bots for sale &mdash; automatic on-chain delivery</h2>
<div class="grid">
<div class="card" style="border-color:#14f195">
<p class="meta">SELF-HOSTED TRADING BOT</p>
<h3 style="margin-top:0;font-size:24px"><a href="/for-sale/jup7-bot/">JUP7 &mdash; Jupiter Perps SOL bot</a></h3>
<p><strong style="font-size:26px;color:#14f195">$20</strong> <span class="meta">USD equivalent in SOL</span></p>
<p>One-command, self-hosted trading: 14-day momentum at 10x, 15% take-profit / 7% stop, 7-day exit, full safety stack including drawdown pauses, daily-loss block and a kill switch. Buyer's key stays in their own Jupiter CLI. No keys in the archive. <strong>No profit claim.</strong></p>
<p class="meta">Send SOL to <code>EFCC9rEwbsBHr92vNTyGHYRswH1fg5M8ZdrPCfuSsLpQ</code> with memo <code>JUP7 your@email.com</code> &mdash; the archive is emailed automatically within 5 minutes.</p>
<a class="cta" href="/for-sale/jup7-bot/">Full JUP7 specification &rarr;</a>
</div>
<div class="card" style="border-color:#9945ff">
<p class="meta">PAPER DECISION ENGINE &middot; NO SIGNING</p>
<h3 style="margin-top:0;font-size:24px"><a href="/for-sale/sol-sniper/">SOL Sniper &mdash; paper engine</a></h3>
<p><strong style="font-size:26px;color:#9945ff">$25</strong> <span class="meta">USD equivalent in SOL</span></p>
<p>Node 26 / Solana Kit new-pool monitor with fail-closed evidence gates, risk and cost checks, and paper P&amp;L. <strong>114/114 tests pass.</strong> Paper-only: no keys, no signing, no live order submission.</p>
<p class="meta">Send SOL to <code>EFCC9rEwbsBHr92vNTyGHYRswH1fg5M8ZdrPCfuSsLpQ</code> with memo <code>SNIPER your@email.com</code> &mdash; automatic delivery.</p>
<a class="cta" href="/for-sale/sol-sniper/">Full Sniper specification &rarr;</a>
</div>
</div>
<p class="meta">Both are source packages sold as-is, no warranty or profit guarantee. See <a href="/products/">the product index</a> and each page for test coverage and live-vs-paper boundaries.</p>

<h2>Start Here</h2>
<ul>
<li><strong>Compare Infrastructure:</strong> Check 2026 Solana RPC latency/availability (Helius, QuickNode, Alchemy) and DEX routing/pool fees (Jupiter, Orca, Raydium). <a href="/articles/best-solana-rpc-2026/">RPC benchmark</a> &middot; <a href="/articles/best-solana-dex-low-fees-2026/">DEX fees</a> &middot; <a href="/compare/">comparison matrix</a></li>
<li><strong>Run Free Tools &amp; Data:</strong> Test swap costs with the <a href="/tools/solana-fee-calculator/">free swap fee calculator</a>, inspect <a href="/metrics/">metric definitions</a>, or download timestamped <a href="/data/">CSVs</a> and <a href="/llms.txt">llms.txt</a>.</li>
<li><strong>Inspect Self-Hosted Bots:</strong> Compare the bots above, including test coverage and live-vs.-paper boundaries.</li>
</ul>
<p class="meta"><a href="/search/">Search this site</a> &middot; <a href="/papers/">All papers</a> &middot; <a href="/methodology/">How we verify</a> &middot; <a href="/glossary/">Glossary</a></p>
<h2>Latest research</h2>
<ul class="article-list">{items}</ul>'''
    with open(os.path.join(SITE, "index.html"), "w", encoding="utf-8") as f:
        f.write(shell(cfg()["site_name"] + " - " + cfg()["tagline"], body))

def rebuild_sitemap():
    q = load(QUEUE)
    urls = [base_url() + "/", base_url() + "/tools/", base_url() + "/tools/solana-fee-calculator/",
            base_url() + "/methodology/", base_url() + "/products/", base_url() + "/for-sale/jup7-bot/", base_url() + "/for-sale/sol-sniper/",
            base_url() + "/ai-agent-toolkit/", base_url() + "/ai-trading-sites/",
            base_url() + "/leaderboards/", base_url() + "/compare/", base_url() + "/method/", base_url() + "/rpc-cost/", base_url() + "/dex-fee-modes/", base_url() + "/papers/",
            base_url() + "/papers/agent-trading-benchmarks-2026/",
            base_url() + "/papers/agent-data-stack-2026/",
            base_url() + "/papers/exchange-agent-rails-2026/",
            base_url() + "/api/tools.json", base_url() + "/api/leaderboards.json",
            base_url() + "/sources/", base_url() + "/data/", base_url() + "/metrics/", base_url() + "/glossary/", base_url() + "/search/", base_url() + "/api/search.json", base_url() + "/api/registry.json",
            base_url() + "/for-sale/jup7-bot/artifacts/", base_url() + "/for-sale/sol-sniper/artifacts/",
            base_url() + "/about/", base_url() + "/security/", base_url() + "/security.txt",
            base_url() + "/changelog/", base_url() + "/status/", base_url() + "/checksums/",
            base_url() + "/CHECKSUMS.txt", base_url() + "/api/", base_url() + "/api/openapi.json",
            base_url() + "/data/LICENSE.txt",
            base_url() + "/data/tools.csv", base_url() + "/data/x402.csv",
            base_url() + "/data/benchmarks.csv", base_url() + "/data/papers.csv",
            base_url() + "/llms.txt", base_url() + "/stats/"]
    for t in q:
        if t.get("published"):
            urls.append(base_url() + "/articles/" + t["slug"] + "/")
    today = datetime.date.today().isoformat()
    xml = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
    for u in urls:
        xml += f'<url><loc>{esc(u)}</loc><lastmod>{today}</lastmod></url>'
    xml += "</urlset>\n"
    with open(os.path.join(SITE, "sitemap.xml"), "w", encoding="utf-8") as f:
        f.write(xml)
    with open(os.path.join(SITE, "robots.txt"), "w", encoding="utf-8") as f:
        f.write(f"User-agent: *\nAllow: /\nSitemap: {base_url()}/sitemap.xml\n")

def rebuild_rss():
    q = load(QUEUE)
    pub = [t for t in q if t.get("published")]
    pub.sort(key=lambda t: t.get("published_at") or "", reverse=True)
    items = "".join(
      f"<item><title>{esc(t['title'])}</title><link>{base_url()}/articles/{t['slug']}/</link>"
      f"<description>{esc(t.get('summary',''))}</description></item>" for t in pub[:20])
    rss = f'<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>{esc(cfg()["site_name"])}</title><link>{base_url()}</link><description>{esc(cfg()["tagline"])}</description>{items}</channel></rss>\n'
    with open(os.path.join(SITE, "feed.xml"), "w", encoding="utf-8") as f:
        f.write(rss)

def cmd_next():
    q = load(QUEUE)
    for t in q:
        if not t.get("published"):
            print(json.dumps(t, ensure_ascii=False))
            return
    print(json.dumps({"done": True, "message": "All topics published. Add more to queue.json."}))

def cmd_publish(path):
    a = load(path)
    q = load(QUEUE)
    match = next((t for t in q if t["slug"] == a["slug"]), None)
    if not match:
        print("ERROR: slug not in queue.json: " + a["slug"]); sys.exit(2)
    outdir = os.path.join(ARTICLES, a["slug"])
    os.makedirs(outdir, exist_ok=True)
    target = match.get("affiliate_target", a.get("affiliate_target", "jupiter"))
    body = (
      f'<article><h1>{esc(a["title"])}</h1>'
      f'<div class="meta">Published {datetime.date.today().isoformat()} &middot; {esc(cfg()["author"])}</div>'
      + a["html_body"]
      + '<div class="card">' + cta_for(target) + '</div>'
      + sources_block(a.get("sources", []))
      + '<div class="disclosure">' + esc(cfg()["disclosure"]) + '</div></article>'
    )
    url = base_url() + "/articles/" + a["slug"] + "/"
    with open(os.path.join(outdir, "index.html"), "w", encoding="utf-8") as f:
        f.write(shell(a["title"], body, a.get("summary", ""), article=True, url=url))
    match["published"] = True
    match["published_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
    match["summary"] = a.get("summary", "")
    save(QUEUE, q)
    rebuild_index(); rebuild_sitemap(); rebuild_rss()
    with open(JOURNAL, "a", encoding="utf-8") as f:
        f.write(f'- {datetime.date.today().isoformat()} — published **{a["title"]}** ({url})\n')
    print("PUBLISHED: " + url)

def cmd_status():
    q = load(QUEUE)
    pub = [t for t in q if t.get("published")]
    print(f"topics={len(q)} published={len(pub)} remaining={len(q)-len(pub)}")
    for t in q:
        if t.get("published"):
            print("  [x]", t["title"])
    nxt = next((t for t in q if not t.get("published")), None)
    if nxt: print("  next:", nxt["title"])

def cmd_kvpayload():
    """Print gzip+base64 of the site bundle as {path:{k,v,ct}} for the Cloudflare connector."""
    import gzip, base64
    files = {}
    for base, dirs, fnames in os.walk(SITE):
        for fn in fnames:
            fp = os.path.join(base, fn)
            rel = os.path.relpath(fp, SITE).replace("\\", "/")
            data = open(fp, "rb").read()
            ct = {"html":"text/html; charset=utf-8","css":"text/css","xml":"application/xml","txt":"text/plain"}.get(fn.rsplit(".",1)[-1], "application/octet-stream")
            files[rel] = {"k": hashlib.md5(data).hexdigest(), "v": base64.b64encode(data).decode(), "ct": ct}
    raw = json.dumps(files, separators=(",", ":")).encode("utf-8")
    print(base64.b64encode(gzip.compress(raw, 9)).decode())

def cmd_indexnow():
    """Submit every sitemap URL to IndexNow (no account required)."""
    import re, urllib.request, urllib.parse
    c = cfg()
    key = c.get("indexnow_key", "")
    if not key:
        print("No IndexNow key configured."); return
    xml = open(os.path.join(SITE, "sitemap.xml"), encoding="utf-8").read()
    urls = re.findall(r"<loc>([^<]+)</loc>", xml)
    if not urls:
        print("No URLs in sitemap."); return
    host = urllib.parse.urlparse(c["base_url"]).netloc
    body = json.dumps({
        "host": host, "key": key,
        "keyLocation": c["base_url"] + "/" + key + ".txt",
        "urlList": urls,
    }).encode("utf-8")
    req = urllib.request.Request(
        c.get("indexnow_endpoint", "https://api.indexnow.org/indexnow"),
        data=body,
        headers={"Content-Type": "application/json; charset=utf-8",
                 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ChainLedgerPublisher/1.0"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=45) as resp:
            print("INDEXNOW OK", resp.status, "submitted", len(urls), "URLs")
    except Exception as e:
        print("INDEXNOW FAILED:", repr(e)); sys.exit(1)

def cmd_deploy():
    """Push the generated site bundle to the live Worker's publish endpoint."""
    import gzip, base64, hashlib, urllib.request
    d = cfg().get("deploy", {})
    url = d.get("publish_url", "")
    token = d.get("publish_token", "")
    if not url or not token:
        print("No publish endpoint configured."); return
    files = {}
    for base, dirs, fnames in os.walk(SITE):
        for fn in fnames:
            fp = os.path.join(base, fn)
            rel = os.path.relpath(fp, SITE).replace("\\", "/")
            data = open(fp, "rb").read()
            ct = {"html":"text/html; charset=utf-8","css":"text/css","xml":"application/xml","txt":"text/plain"}.get(fn.rsplit(".",1)[-1], "application/octet-stream")
            files[rel] = {"k": hashlib.md5(data).hexdigest(), "v": base64.b64encode(data).decode(), "ct": ct}
    payload = base64.b64encode(gzip.compress(json.dumps(files, separators=(",", ":")).encode("utf-8"), 9)).decode()
    req = urllib.request.Request(
        url,
        data=json.dumps({"gz": payload}).encode("utf-8"),
        headers={"Content-Type": "application/json", "Authorization": "Bearer " + token,
                 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ChainLedgerPublisher/1.0"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            print("DEPLOY OK", resp.status, resp.read(300).decode("utf-8", "replace"))
    except Exception as e:
        print("DEPLOY FAILED:", repr(e)); sys.exit(1)

def main():
    if len(sys.argv) < 2:
        print(__doc__); return
    cmd = sys.argv[1]
    if cmd == "next": cmd_next()
    elif cmd == "publish": cmd_publish(sys.argv[2])
    elif cmd == "status": cmd_status()
    elif cmd == "links": print(json.dumps(load(LINKS), indent=2))
    elif cmd == "deploy": cmd_deploy()
    elif cmd == "kvpayload": cmd_kvpayload()
    elif cmd == "indexnow": cmd_indexnow()
    else: print("unknown command: " + cmd); sys.exit(1)

if __name__ == "__main__":
    main()
