"""Reproduce the GitHub CLI file check. Run beside site_index.py with Python 3.11+.

python3 release-proof.py                     # pinned release
python3 release-proof.py --latest            # current stable release
python3 release-proof.py --model qwen3-vl:4b # optional local Ollama comparison
"""
import argparse
import hashlib
import json
from datetime import datetime, timezone
from html.parser import HTMLParser
from urllib.request import Request, urlopen

from site_index import find_routes

DOCS = "https://docs.github.com"
API = "https://api.github.com/repos/cli/cli/releases/"
PIN = "v2.106.0"


def fetch(url):
    return urlopen(Request(url, headers={"User-Agent": "Sandstone-release-proof/1"}), timeout=60)


class Links(HTMLParser):
    def __init__(self):
        super().__init__()
        self.paths = []

    def handle_starttag(self, tag, attrs):
        href = dict(attrs).get("href") or ""
        if tag == "a" and href.startswith("/en/") and href not in self.paths:
            self.paths.append(href)


def read_links(url):
    with fetch(url) as response:
        page = response.read().decode()
    links = Links()
    links.feed(page)
    return links.paths


def compare_chat(model, paths):
    request = {
        "model": model, "stream": False, "think": False,
        "format": {"type": "object", "properties": {"path": {"type": "string", "enum": [*paths, "UNKNOWN"]}},
                   "required": ["path"]},
        "options": {"temperature": 0, "num_predict": 1024, "num_ctx": 8192},
        "messages": [{"role": "user", "content":
            "Select the English GitHub REST API documentation home from these observed paths. "
            "Use the JSON path field for the exact answer. If absent return UNKNOWN.\n" + "\n".join(paths)}],
    }
    post = Request("http://127.0.0.1:11434/api/chat", data=json.dumps(request).encode(),
                   headers={"Content-Type": "application/json"})
    with urlopen(post, timeout=180) as response:
        result = json.load(response)
    raw = result["message"]["content"].strip()
    try:
        answer = json.loads(raw).get("path", "")
    except (json.JSONDecodeError, AttributeError):
        answer = raw
    return {"model": result["model"], "offeredPaths": len(paths), "format": "constrained JSON choice", "answer": answer,
            "correct": answer == "/en/rest", "promptTokens": result["prompt_eval_count"],
            "outputTokens": result["eval_count"], "outputTokenLimit": 1024,
            "stopReason": result.get("done_reason"), "temperature": 0,
            "input": "Unique English paths linked from the GitHub Docs home in document order."}



def compare(model, paths):
    # Explicit direct-answer template for the installed Qwen3-VL model.
    prompt = ("<|im_start|>user\nWhich path leads to the English GitHub REST API reference? "
              "Answer with just one path from this list.\n" + "\n".join(paths)
              + "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n")
    request = {"model": model, "raw": True, "prompt": prompt, "stream": False,
               "options": {"temperature": 0, "num_predict": 64, "stop": ["<|im_end|>", "\n"]}}
    post = Request("http://127.0.0.1:11434/api/generate", data=json.dumps(request).encode(),
                   headers={"Content-Type": "application/json"})
    with urlopen(post, timeout=180) as response:
        result = json.load(response)
    answer = result["response"].strip()
    return {"model": result["model"], "offeredPaths": len(paths), "answer": answer,
            "format": "direct answer with empty thinking prefill", "correct": answer == "/en/rest",
            "promptTokens": result["prompt_eval_count"], "outputTokens": result["eval_count"],
            "stopReason": result.get("done_reason"), "outputTokenLimit": 64, "temperature": 0,
            "chatComparison": compare_chat(model, paths)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--latest", action="store_true")
    parser.add_argument("--model", help="Optional installed Ollama model, run only on localhost")
    args = parser.parse_args()
    home_paths = read_links(DOCS + "/en")
    route = find_routes("Where is GitHub’s REST API reference?")[0]
    assert route["domain"] == "docs.github.com" and route["path"] in home_paths
    rest = DOCS + route["path"]
    reference = "/en/rest/releases/releases"
    assert reference in read_links(rest)
    with fetch(DOCS + reference) as response:
        page = response.read().decode()
    assert "get-the-latest-release" in page and "/releases/latest" in page
    endpoint = API + ("latest" if args.latest else "tags/" + PIN)
    with fetch(endpoint) as response:
        release = json.load(response)
    assert not release["draft"] and not release["prerelease"]
    version = release["tag_name"].removeprefix("v")
    name = f"gh_{version}_macOS_arm64.zip"
    assets = {item["name"]: item for item in release["assets"]}
    archive = assets[name]
    checksums = assets[f"gh_{version}_checksums.txt"]["browser_download_url"]
    with fetch(checksums) as response:
        candidates = [line.split() for line in response.read().decode().splitlines() if line.strip()]
    expected, = [digest for digest, filename in candidates if filename.lstrip("*") == name]
    digest = hashlib.sha256()
    size = 0
    with fetch(archive["browser_download_url"]) as response:
        while block := response.read(65536):
            digest.update(block)
            size += len(block)
    actual = digest.hexdigest()
    assert size == archive["size"] and actual == expected and archive["digest"] == "sha256:" + actual
    proof = {
        "checkedAt": datetime.now(timezone.utc).isoformat(),
        "task": "Identify and verify the GitHub CLI zip for an Apple silicon Mac.",
        "modelComparisonTask": "Find the English REST API documentation landing path.",
        "helper": {"query": "Where is GitHub’s REST API reference?", "result": route,
                   "modelCalls": 0, "modelTokens": 0, "providerApiKeyRequired": False},
        "manual": {"start": DOCS + "/en", "linkedPath": route["path"],
                   "note": "The home page also links directly to REST. A bookmark can skip discovery."},
        "source": {"rest": rest, "endpointDocs": DOCS + reference + "#get-the-latest-release",
                   "releaseRequest": endpoint, "releasePage": release["html_url"], "checksums": checksums},
        "result": {"tag": release["tag_name"], "name": name, "assetCount": len(assets),
                   "url": archive["browser_download_url"], "downloadedBytes": size,
                   "sha256": actual, "publisherSha256": expected, "match": True},
        "attribution": "The helper found the docs. The script selected the file and checked the publisher's bytes locally. Nothing was installed.",
    }
    if args.model:
        proof["localModel"] = compare(args.model, home_paths)
    print(json.dumps(proof, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()
