# /// script
# requires-python = ">=3.11"
# dependencies = ["mcp==1.30.0"]
# ///
"""Hopper Cairn: public, read-only site metadata and publisher guides."""
from contextlib import closing
from dataclasses import dataclass
from datetime import date, timedelta
from functools import lru_cache
from hashlib import sha256
import json
import os
from pathlib import Path
from typing import Literal
import re
import sqlite3
import sys
import tempfile
from urllib.request import urlopen

EDITION = "2026.11.28-v1"
SOURCE = "https://huggingface.co/datasets/Grasshopper4242/hopper-site-index/resolve/7e64ac6f5368c03b10c4e42d498be83d0cf0d5b4"
MANIFEST_DIGEST = "a1334c72db375cd897c6baa1410c1bb61fcb7677e4f8896d55b88180d90a1bff"
MAX_MANIFEST = 32 << 20
MAX_PLAN = 1 << 20
MAX_EDITION = 1 << 30
RESULT_LIMIT = 30
STOP_WORDS = set("a an and are at can do does find for get how i in is me of on please show the to where which with".split())
HOST_LABELS = {"ai", "api", "co", "com", "dev", "developer", "docs", "io", "net", "org", "sh", "www"}
WORD_FORMS = {"apis": "api", "documentation": "docs", "issues": "issue", "references": "reference",
              "repositories": "repo", "repository": "repo"}


def cache_dir() -> Path:
    base = os.environ.get("XDG_CACHE_HOME")
    if not base:
        base = Path.home() / ("Library/Caches" if sys.platform == "darwin" else ".cache")
    directory = Path(base) / "hopper-public-site-index" / MANIFEST_DIGEST
    directory.mkdir(mode=0o700, parents=True, exist_ok=True)
    return directory


def public_bytes(path: str, digest: str, limit: int) -> bytes:
    """Cache immutable publisher files by digest and recheck bytes before parsing."""
    target = cache_dir() / digest
    try:
        with target.open("rb") as cached:
            data = cached.read(limit + 1)
        if len(data) <= limit and sha256(data).hexdigest() == digest:
            return data
    except FileNotFoundError:
        pass
    with urlopen(f"{SOURCE}/{path}", timeout=15) as response:
        data = response.read(limit + 1)
    if len(data) > limit or sha256(data).hexdigest() != digest:
        raise ValueError(f"Public edition integrity check failed for {path}")
    with tempfile.TemporaryDirectory(dir=target.parent) as staging:
        name = Path(staging) / "download"
        name.write_bytes(data)
        os.replace(name, target)
    return data


@dataclass
class Catalog:
    plans: dict
    host_labels: dict
    domains: list[str]
    bundle: dict


@lru_cache(maxsize=1)
def catalog() -> Catalog:
    manifest = json.loads(public_bytes("manifest.json", MANIFEST_DIGEST, MAX_MANIFEST))
    if manifest["editionVersion"] != EDITION or manifest["schemaVersion"] != "hopper.site-index.edition-manifest.v1":
        raise ValueError("Unexpected public edition manifest")
    entries = {}
    host_labels = {}
    for entry in manifest["plans"]:
        domain = entry["domain"]
        if (not re.fullmatch(r"[a-z0-9.-]+", domain) or entry["path"] != f"plans/{domain}.json"
                or not re.fullmatch(r"sha256:[0-9a-f]{64}", entry["fileSha256"])):
            raise ValueError("Invalid domain entry in the public edition")
        entries[domain] = entry
        for label in set(domain.split(".")) - HOST_LABELS:
            host_labels.setdefault(label, []).append(domain)
    bundle = next(file for file in manifest["files"] if file["path"] == "plans.jsonl")
    return Catalog(entries, host_labels, sorted(entries), bundle)


@lru_cache(maxsize=64)
def read_plan(domain: str) -> dict:
    entry = catalog().plans[domain]
    raw = public_bytes(entry["path"], entry["fileSha256"].removeprefix("sha256:"), MAX_PLAN)
    plan = json.loads(raw)
    if plan["domain"] != domain:
        raise ValueError("Plan hostname differs from its manifest entry")
    return plan


def verified_plans():
    """Verify the entire stream before yielding any row; keep the payload on disk."""
    bundle = catalog().bundle
    size = bundle["byteLength"]
    if not 0 < size <= MAX_EDITION:
        raise ValueError("Public edition exceeds the supported download size")
    digest = sha256()
    count = 0
    with tempfile.TemporaryFile() as verified:
        with urlopen(f"{SOURCE}/plans.jsonl", timeout=15) as response:
            while chunk := response.read(65536):
                count += len(chunk)
                if count > size:
                    raise ValueError("Public edition exceeds its declared size")
                digest.update(chunk)
                verified.write(chunk)
        if count != size or f"sha256:{digest.hexdigest()}" != bundle["sha256"]:
            raise ValueError("Public edition stream integrity check failed")
        verified.seek(0)
        while row := verified.readline(MAX_PLAN + 1):
            if len(row) > MAX_PLAN:
                raise ValueError("Plan exceeds the supported record size")
            if row.strip():
                yield json.loads(row)


def list_sites(offset: int = 0, limit: int | None = None) -> dict:
    """List documented domains, optionally in pages of up to 1,000."""
    if offset < 0 or (limit is not None and not 1 <= limit <= 1000):
        raise ValueError("Use a nonnegative offset and a page size from 1 to 1000")
    domains = catalog().domains
    return {"edition": EDITION, "domains": domains[offset:None if limit is None else offset + limit]}


def site_map(domain: str) -> dict:
    """Read a domain's documented routes, workflow states and action relationships."""
    domain = domain.strip().lower()
    if domain not in catalog().plans:
        return {"status": "unindexed"}
    plan = read_plan(domain)
    return {
        "domain": domain, "edition": EDITION,
        "source": f"{SOURCE}/plans/{domain}.json",
        "routes": [{"id": r["routeId"], "path": r["pathTemplate"], "links": r["outlinks"]} for r in plan["routes"]],
        "states": [{"id": s["stateId"], "route": s["routeId"], "next": s["transitionsTo"]} for s in plan["workflowStates"]],
        "actions": [{"id": a["actionId"], "name": a["name"], "route": a["routeId"], "risk": a["risk"]} for a in plan["actions"]],
    }


def words(text: str) -> set[str]:
    text = re.sub(r"['’]s\b", "", text.casefold())
    return {WORD_FORMS.get(w, w) for w in re.findall(r"[a-z0-9]+", text)} - STOP_WORDS


def route_rows(plan):
    domain = plan["domain"]
    routes = plan["routes"]
    paths = {route["pathTemplate"] for route in routes}
    linked = {link for route in routes for link in route["outlinks"]} - paths
    for route in routes:
        path, rid = route["pathTemplate"], route["routeId"]
        literal = " ".join((domain, rid, path, *route["tags"])).casefold()
        yield {"kind": "route", "domain": domain, "id": rid, "path": path}, literal
    for path in sorted(linked):
        yield {"kind": "linkedPath", "domain": domain, "path": path}, f"{domain} {path}".casefold()


def route_words(literal: str) -> set[str]:
    terms = words(literal)
    if "rest" in terms:
        terms.update(("api", "reference"))
    return terms


def search_scoped(domains, term, tokens):
    exact, matches = [], []
    for domain in sorted(domains):
        for result, literal in route_rows(read_plan(domain)):
            if term in literal:
                exact.append(result)
            elif tokens and tokens <= route_words(literal):
                path_terms = words(result["path"] + " " + result.get("id", ""))
                matches.append((len(tokens & path_terms), result))
    matches.sort(key=lambda match: -match[0])
    return (exact or [result for _, result in matches])[:RESULT_LIMIT]


def index_routes(db):
    # The ready marker commits with both indexes. A failed download or process exit
    # rolls the transaction back; other helpers reuse the first completed build.
    if db.execute("PRAGMA user_version").fetchone()[0] == 1:
        return
    with db:
        db.execute("BEGIN IMMEDIATE")
        if db.execute("PRAGMA user_version").fetchone()[0] == 1:
            return
        db.execute("CREATE VIRTUAL TABLE literals USING fts5(literal, result UNINDEXED, tokenize='trigram')")
        db.execute("CREATE VIRTUAL TABLE keywords USING fts5(terms)")
        for plan in verified_plans():
            for result, literal in route_rows(plan):
                rowid = db.execute("INSERT INTO literals VALUES (?, ?)", (literal, json.dumps(result))).lastrowid
                terms = " ".join(sorted(route_words(literal)))
                db.execute("INSERT INTO keywords(rowid, terms) VALUES (?, ?)", (rowid, terms))
        db.execute("PRAGMA user_version=1")


def fts_phrase(text: str) -> str:
    return '"' + text.replace('"', '""') + '"'


def find_routes(query: str) -> list[dict]:
    """Find up to 30 documented routes or linked paths by literal text or a site-and-topic question."""
    term = query.strip().casefold()
    if not term or len(term) > 100 or "\x00" in term:
        raise ValueError("Use a search phrase of 1 to 100 characters")
    tokens = words(term)
    if len(term.split()) > 1:
        labels = catalog().host_labels
        domains = {d for token in tokens for d in labels.get(token, ())}
        if 0 < len(domains) <= 4:
            return search_scoped(domains, term, tokens)

    with closing(sqlite3.connect(cache_dir() / "routes-v1.sqlite3", timeout=120)) as db:
        index_routes(db)
        if len(term) < 3:
            rows = db.execute("SELECT result FROM literals WHERE instr(literal, ?) > 0 ORDER BY rowid LIMIT ?", (term, RESULT_LIMIT))
        else:
            rows = db.execute("SELECT result FROM literals WHERE literals MATCH ? ORDER BY rowid LIMIT ?", (fts_phrase(term), RESULT_LIMIT))
        exact = [json.loads(row[0]) for row in rows]
        if exact or not tokens:
            return exact
        expression = " AND ".join(fts_phrase(t) for t in sorted(tokens))
        rows = db.execute("""
            SELECT result FROM keywords JOIN literals ON literals.rowid = keywords.rowid
            WHERE keywords MATCH ? ORDER BY keywords.rank, keywords.rowid LIMIT ?
        """, (expression, RESULT_LIMIT))
        return [json.loads(row[0]) for row in rows]


GUIDE_DIGEST = "a10b478aeeac0b6eaea30632702bc4be0f29f6f2489e24ddcaf66a9c78d8c0b5"
GUIDE_PATH = "guides/2026-11-29-shopping.json"
SHOPPING_PATH = "shopping/2026-11-29-v1.json"
SHOPPING_DIGEST = "53b7ec17704cf8629e29336f7de3b18c495a1b24bac318925ede1d0bf8c2020c"


@lru_cache(maxsize=2)
def _fixed_catalog(path: str, digest: str) -> dict:
    maximum = 256 * 1024
    try:
        reader = (Path(__file__).resolve().parent / path).open("rb")
    except FileNotFoundError:
        reader = urlopen(f"https://hopperlabs.ai/developers/site-index/{path}", timeout=15)
    with reader:
        data = reader.read(maximum + 1)
    if len(data) > maximum or sha256(data).hexdigest() != digest:
        raise ValueError("Publisher catalog digest mismatch")
    return json.loads(data)


def publisher_catalog() -> dict:
    return _fixed_catalog(GUIDE_PATH, GUIDE_DIGEST)


def check_headphone_return(received_on: str, as_of: str,
                          seller: Literal["apple-us-online", "other", "unknown"],
                          condition: Literal["complete", "needs-review"]) -> dict:
    """Check a US Apple online headphone return against recorded terms. Dates are YYYY-MM-DD. Complete means undamaged with included pieces. No order lookup or return submission."""
    book = _fixed_catalog(SHOPPING_PATH, SHOPPING_DIGEST)
    policy = book["apple"]
    result = {"source": policy["source"], "checkedOn": book["checkedOn"], "scope": policy["scope"]}
    if seller != "apple-us-online":
        status = "seller"
    else:
        try:
            received, checking = date.fromisoformat(received_on), date.fromisoformat(as_of)
            valid = received.isoformat() == received_on and checking.isoformat() == as_of and received <= checking
        except ValueError:
            valid = False
        if not valid:
            status = "dates"
        elif not policy["coverageFrom"] <= received_on <= policy["coverageThrough"]:
            status = "coverage"
        else:
            holiday = policy["holidayFrom"] <= received_on <= policy["holidayThrough"]
            deadline = policy["holidayDeadline"] if holiday else (received + timedelta(days=policy["standardDays"])).isoformat()
            within = as_of <= deadline
            result.update(deadline=deadline, window="holiday" if holiday else "standard",
                          withinWindow=within, daysSinceReceipt=(checking - received).days)
            status = "holiday-open" if holiday else "standard-open"
            if not within:
                status = "closed"
            elif condition != "complete":
                status = "condition"
    return {**result, "status": status, "summary": book["messages"][status]}


def check_fridge_filter(model: str, part: str) -> dict:
    """Check an exact GE refrigerator model and cartridge code against recorded manufacturer specifications. Model suffixes matter. Includes a source and where to look next."""
    book = _fixed_catalog(SHOPPING_PATH, SHOPPING_DIGEST)
    ge = book["ge"]
    model, part = model.strip().upper(), part.strip().upper()
    row = ge["models"].get(model)
    result = {"checkedOn": book["checkedOn"], "finder": ge["finder"], "source": ge["finder"]}
    status = "unknown"
    if row:
        result.update(row)
        expected = row["specified"]
        if expected is None:
            status = "ambiguous"
        else:
            result["partSource"] = ge["parts"][expected]
            if part == expected:
                status = "specified"
            else:
                status = "different" if part in ge["parts"] else "unlisted"
    return {**result, "status": status, "summary": book["messages"][status]}


def find_publisher_guides(query: str) -> list[dict]:
    """Find first-party documentation by publisher, task or title. These links grant no browser tools."""
    if not query.strip() or len(query) > 100:
        raise ValueError("Use a publisher name or a task of 1 to 100 characters")
    terms = words(query.casefold())
    if not terms:
        return []
    results = []
    catalog = publisher_catalog()
    for publisher in catalog["publishers"]:
        for guide in publisher["guides"]:
            fields = (publisher["name"], publisher["domain"], guide["task"], guide["pageTitle"], guide["url"])
            if terms <= words(" ".join(fields).casefold()):
                results.append({
                    "kind": "publisherGuide", "publisher": publisher["name"],
                    "task": guide["task"], "url": guide["url"], "checkedOn": catalog["checkedOn"],
                })
    return results[:RESULT_LIMIT]


def site_brief(domain: str) -> dict:
    """Get a compact pre-visit briefing with source links, documented reads and write counts."""
    domain = domain.strip().lower()
    if len(domain) > 253 or not re.fullmatch(r"[a-z0-9.-]+", domain):
        return {"status": "unindexed"}
    plan = site_map(domain)
    guide_book = publisher_catalog()
    publisher = next((item for item in guide_book["publishers"] if item["domain"] == domain), None)
    if "routes" not in plan and publisher is None:
        return {"status": "unindexed"}
    brief = {"domain": domain, "status": "documented", "executionAuthority": "none"}
    if publisher is not None:
        brief["publisherGuides"] = {"checkedOn": guide_book["checkedOn"], "guides": publisher["guides"][:6]}
    if "routes" in plan:
        paths = {route["id"]: route["path"] for route in plan["routes"]}
        reads = [action for action in plan["actions"] if action["risk"] == "read"]
        brief["signedPlan"] = {
            "edition": plan["edition"], "source": plan["source"],
            "routeCount": len(paths), "stateCount": len(plan["states"]),
            "readCount": len(reads),
            "writeCount": sum(action["risk"] == "write" for action in plan["actions"]),
            "routes": [{"id": rid, "path": path} for rid, path in list(paths.items())[:6]],
            "states": plan["states"][:6],
            "documentedReads": [{"id": action["id"], "name": action["name"], "path": paths[action["route"]]}
                                for action in reads[:6]],
        }
    return brief


def _checksums(reference):
    if len(reference) > 1024 * 1024:
        raise ValueError("Use a checksum list under 1 MiB.")
    if re.fullmatch(r"[0-9a-fA-F]{64}", reference.strip()):
        return reference.strip().lower(), {}
    names = {}
    for line in reference.splitlines():
        if not line.strip() or line.startswith("#"):
            continue
        match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](.+)", line)
        if not match:
            raise ValueError("Expected a SHA-256 digest or sha256sum list.")
        digest, name = match[1].lower(), match[2]
        if name in names and names[name] != digest:
            raise ValueError("Conflicting checksums for the same filename.")
        names[name] = digest
    if not names:
        raise ValueError("Empty checksum reference.")
    return None, names


def _compare_digest(filename, actual, parsed):
    direct, names = parsed
    expected = direct or names.get(filename)
    if expected:
        return {"name": filename, "actual": actual, "expected": expected,
                "status": "match" if actual == expected else "mismatch"}
    matches = [name for name, digest in names.items() if digest == actual]
    return {"name": filename, "actual": actual, "matchingNames": matches,
            "status": "different-name" if matches else "unlisted"}


def check_download_digest(filename: str, sha256_hex: str, reference: str) -> dict:
    """Compare an already computed SHA-256 with a publisher digest or sha256sum list. Pure local comparison; no file access, network or execution."""
    if not filename or len(filename) > 4096 or not re.fullmatch(r"[0-9a-fA-F]{64}", sha256_hex):
        raise ValueError("Supply a filename and a 64-character hexadecimal SHA-256.")
    return _compare_digest(filename, sha256_hex.lower(), _checksums(reference))


def verify_files():
    import argparse
    parser = argparse.ArgumentParser(description="Compare local files with publisher SHA-256 checksums.")
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--manifest", type=Path)
    source.add_argument("--sha256")
    parser.add_argument("files", nargs="+", type=Path)
    args = parser.parse_args(sys.argv[2:])
    try:
        if args.manifest:
            with args.manifest.open("rb") as stream:
                raw = stream.read(1024 * 1024 + 1)
            if len(raw) > 1024 * 1024:
                raise ValueError("Use a checksum list under 1 MiB.")
            reference = raw.decode("utf-8")
        else:
            reference = args.sha256
        parsed = _checksums(reference)
    except (OSError, ValueError) as error:
        parser.error(str(error))
    results = []
    for path in args.files:
        try:
            digest = sha256()
            if not path.is_file():
                raise ValueError("Not a regular file")
            with path.open("rb") as stream:
                for chunk in iter(lambda: stream.read(1024 * 1024), b""):
                    digest.update(chunk)
            results.append(_compare_digest(path.name, digest.hexdigest(), parsed))
        except (OSError, ValueError) as error:
            results.append({"name": path.name, "status": "unreadable", "error": str(error)})
    print(json.dumps(results, ensure_ascii=False, indent=2))
    return 0 if all(row["status"] == "match" for row in results) else 1


if __name__ == "__main__":
    if sys.argv[1:2] == ["verify"]:
        raise SystemExit(verify_files())
    from mcp.server.fastmcp import FastMCP
    server = FastMCP("Hopper Cairn")
    for tool in (list_sites, site_map, find_routes, find_publisher_guides, site_brief,
                 check_download_digest, check_headphone_return, check_fridge_filter):
        server.tool()(tool)
    server.run(transport="stdio")
