# /// script
# requires-python = ">=3.11,<3.14"
# dependencies = ["duckdb==1.4.1", "mcp==1.30.0"]
# ///
"""Run with: uv run --script workflow-proof.py > workflow-proof.json"""
import asyncio
from datetime import datetime, timezone
from hashlib import sha256
from html.parser import HTMLParser
import json
from pathlib import Path
import sqlite3
import sys
import tempfile
from urllib.parse import urljoin
from urllib.request import Request, urlopen

import duckdb
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

ROOT = "https://hopperlabs.ai/developers/site-index/"
HELPER_SHA = "e2f40b2ced85bbba64abbe0412013a3627f9bdd5d0643e8ea4961e6e07180362"
GUIDES_SHA = "32ed862f75003d0200120bb7954a049d62c19f7a2d8a60e6c5bdba742b63d74e"
DATA = "https://huggingface.co/datasets/Grasshopper4242/hopper-site-index/resolve/7e64ac6f5368c03b10c4e42d498be83d0cf0d5b4/plans.jsonl"
DATA_SHA = "865963163980c2e6187c45aeca2a0edb58e90fdc6871e55ef7dbcd5ed8072c30"
FLOW = {
    "lookup-parquet": ("DuckDB Parquet", "https://duckdb.org/docs/2.0/", [
        ("Import & Export", "/docs/2.0/data/overview"),
        ("read_parquet function", "/docs/2.0/data/parquet/overview.html")]),
    "query-plan": ("SQLite query planner", "https://sqlite.org/docs.html", [
        ("Alphabetical Listing Of All Documents", "doclist.html"),
        ("Query Planning", "queryplanner.html")]),
}


def fetch(url, digest=None):
    request = Request(url, headers={"User-Agent": "Hopper public workflow replay/1.0", "Accept-Encoding": "identity"})
    with urlopen(request, timeout=30) as response:
        body = response.read(4_000_001)
        final = response.geturl()
    if len(body) > 4_000_000 or (digest and sha256(body).hexdigest() != digest):
        raise RuntimeError(f"Unexpected source payload from {url}")
    return body, final


class Page(HTMLParser):
    def __init__(self, body, url):
        super().__init__(convert_charrefs=True)
        self.url = url
        self.links = []
        self.text = []
        self.href = None
        self.label = []
        self.canonical = url
        self.feed(body.decode("utf-8"))

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == "a" and attrs.get("href"):
            self.href = urljoin(self.url, attrs["href"])
            self.label = []
        if tag == "link" and "canonical" in attrs.get("rel", "").split():
            self.canonical = urljoin(self.url, attrs["href"])

    def handle_endtag(self, tag):
        if tag == "a" and self.href:
            self.links.append((" ".join("".join(self.label).split()), self.href))
            self.href = None

    def handle_data(self, data):
        self.text.append(data)
        if self.href:
            self.label.append(data)


def read_page(url):
    data, final = fetch(url)
    page = Page(data, final)
    return page, {"url": final, "canonical": page.canonical, "htmlBodyBytes": len(data)}


def record_path(entry, clicks):
    page, landing = read_page(entry)
    records = [landing]
    for text, href in clicks:
        target = urljoin(page.url, href)
        if (text, target) not in page.links:
            raise RuntimeError(f"Publisher navigation changed at {page.url}: {text}")
        page, readback = read_page(target)
        records.append({"viaLink": text, **readback})
    return records


async def lookup(helper_path, query):
    parameters = StdioServerParameters(command=sys.executable, args=[str(helper_path)])
    async with stdio_client(parameters) as (reader, writer), ClientSession(reader, writer) as client:
        await client.initialize()
        response = await client.call_tool("find_publisher_guides", {"query": query})
        if response.isError:
            raise RuntimeError(str(response.content))
        guides = response.structuredContent["result"] if response.structuredContent else [
            json.loads(part.text) for part in response.content]
        if len(guides) != 1:
            raise RuntimeError(f"Expected one dated publisher guide for {query}")
        return guides[0], len(json.dumps(guides, ensure_ascii=False, separators=(",", ":")).encode())


async def navigation(helper, catalog_bytes):
    cases = {}
    for name, (query, entry, clicks) in FLOW.items():
        baseline = record_path(entry, clicks)
        guide, answer_bytes = await lookup(helper, query)
        page, direct = read_page(guide["url"])
        concept = "read_parquet" if name == "lookup-parquet" else "covering index"
        if concept not in " ".join(page.text).casefold():
            raise RuntimeError(f"The publisher guide no longer describes {concept}")
        direct["verifiedGuideTerm"] = concept
        if direct["canonical"] != baseline[-1]["canonical"]:
            raise RuntimeError("The two paths did not reach the same publisher guide")
        cases[name] = {
            "query": query,
            "baseline": {"publisherPages": len(baseline), "linkClicks": len(clicks), "path": baseline,
                         "publisherHtmlBodyBytes": sum(x["htmlBodyBytes"] for x in baseline)},
            "indexed": {"publisherPages": 1, "helperCalls": 1, "guide": guide, "directPage": direct,
                        "coldCatalogBodyBytes": catalog_bytes, "normalizedToolResultBytes": answer_bytes},
        }
    return cases


def inspect_parquet(plans, directory):
    actions = [(plan["domain"], action["name"], action["risk"]) for plan in plans for action in plan["actions"]]
    with duckdb.connect() as db:
        db.execute("CREATE TABLE actions(domain VARCHAR, name VARCHAR, risk VARCHAR)")
        db.executemany("INSERT INTO actions VALUES (?, ?, ?)", actions)
        parquet = directory / "actions.parquet"
        db.execute("COPY actions TO ? (FORMAT PARQUET)", [str(parquet)])
        summary_sql = """SELECT count(*) AS actions, count(*) FILTER (WHERE risk = 'write') AS write_actions,
            count(DISTINCT domain) FILTER (WHERE risk = 'write') AS domains_with_writes
            FROM read_parquet(?)"""
        counts = db.execute(summary_sql, [str(parquet)]).fetchone()
        detail_sql = "SELECT domain, name FROM read_parquet(?) WHERE risk = 'write' ORDER BY domain, name"
        flagged = db.execute(detail_sql, [str(parquet)]).fetchall()
        if counts != (124, 16, 16) or ("slack.com", "Send Slack Channel Message") not in flagged:
            raise RuntimeError("Unexpected rows in the pinned public edition")
        return {"engine": "DuckDB " + duckdb.__version__, "input": "actions.parquet",
                "preparation": "Project domain, action name and declared risk from the verified JSONL into a local Parquet file.",
                "parquetBytes": parquet.stat().st_size, "parquetSha256": sha256(parquet.read_bytes()).hexdigest(),
                "summarySql": summary_sql, "detailSql": detail_sql, "parameter": "actions.parquet",
                "actionRows": counts[0], "writeRows": counts[1], "domainsWithWrites": counts[2],
                "writeActions": [{"domain": d, "name": n} for d, n in flagged]}


def inspect_plan(plans):
    routes = [(p["domain"], r["routeId"], r["pathTemplate"]) for p in plans for r in p["routes"]]
    db = sqlite3.connect(":memory:")
    try:
        db.execute("CREATE TABLE routes(domain TEXT, id TEXT, path TEXT)")
        db.executemany("INSERT INTO routes VALUES (?, ?, ?)", routes)
        query = "SELECT path FROM routes WHERE domain = ? ORDER BY path"
        parameter = ("github.com",)

        def inspect():
            plan = [r[3] for r in db.execute("EXPLAIN QUERY PLAN " + query, parameter)]
            steps = 0

            def count_step():
                nonlocal steps
                steps += 1
                return 0

            db.set_progress_handler(count_step, 1)
            try:
                rows = [r[0] for r in db.execute(query, parameter)]
            finally:
                db.set_progress_handler(None, 0)
            return {"plan": plan, "rows": rows, "sqliteVmProgressCallbacks": steps}

        before = inspect()
        create = "CREATE INDEX routes_by_domain_path ON routes(domain, path)"
        db.execute(create)
        after = inspect()
        if (before["rows"] != after["rows"] or len(after["rows"]) != 3
                or not any("SCAN routes" in s for s in before["plan"])
                or not any("COVERING INDEX routes_by_domain_path" in s for s in after["plan"])):
            raise RuntimeError("Unexpected SQLite query plan or result rows")
        return {"engine": "SQLite " + sqlite3.sqlite_version, "inputRouteRows": len(routes), "query": query,
                "parameter": parameter[0], "indexSql": create, "before": before, "after": after,
                "counterMethod": "One SQLite progress callback per virtual-machine instruction during the SELECT. Index creation is excluded. Counts measure the SQLite index and depend on the engine version."}
    finally:
        db.close()


async def main():
    sibling = Path(__file__).with_name("site_index.py")
    if sibling.is_file():
        helper_bytes = sibling.read_bytes()
        if sha256(helper_bytes).hexdigest() != HELPER_SHA:
            raise RuntimeError("Adjacent site_index.py differs from the measured helper")
    else:
        helper_bytes, _ = fetch(ROOT + "site_index.py", HELPER_SHA)
    catalog_bytes, _ = fetch(ROOT + "guides/2026-11-29.json", GUIDES_SHA)
    data, _ = fetch(DATA, DATA_SHA)
    plans = [json.loads(line) for line in data.splitlines() if line]
    with tempfile.TemporaryDirectory() as folder:
        directory = Path(folder)
        helper = directory / "site_index.py"
        helper.write_bytes(helper_bytes)
        cases = await navigation(helper, len(catalog_bytes))
        cases["lookup-parquet"]["execution"] = inspect_parquet(plans, directory)
        cases["query-plan"]["execution"] = inspect_plan(plans)
    print(json.dumps({
        "schemaVersion": 1, "measuredAtUtc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "method": [
            "The baseline starts at each publisher's documentation landing page and follows two visible links to the full guide. Both paths were also clicked in a desktop browser. Replay verifies each link label and href against live HTML.",
            "The indexed path starts with an installed helper, one fresh stdio process per case. Each calls find_publisher_guides once and opens its one returned publisher URL. Both approaches must reach the same canonical document, then run the same SQL against the same data.",
            "HTML counts are decoded main-document body bytes. The catalog is the known SHA-256-pinned body read by a standalone helper on its first call. Tool result bytes are compact UTF-8 JSON for the result array. Library installation, protocol handshake, redirects, headers, subresources and caching are excluded.",
            "This replay measures two paths through publisher documentation. Its units are page opens, link clicks, helper calls and decoded body bytes.",
        ],
        "helper": {"url": ROOT + "site_index.py", "sha256": HELPER_SHA, "oneTimeScriptBytes": len(helper_bytes),
                   "catalogUrl": ROOT + "guides/2026-11-29.json", "catalogSha256": GUIDES_SHA},
        "data": {"edition": "2026.11.28-v1", "url": DATA, "sha256": DATA_SHA, "bytes": len(data), "domains": len(plans)},
        "cases": cases,
    }, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    asyncio.run(main())
