#!/usr/bin/env python3
# Vendor the tree-sitter grammars opencode's highlighter would otherwise
# download at run time, and rewrite its parser table to local paths.
#
# Run by the maintainer on a version bump, from the package directory. It needs
# network access; it does not need a compiler.
#
# packages/tui/src/parsers-config.ts is a list of descriptors, each with a
# `.wasm` grammar fetched from a GitHub release and one or more `highlights`
# (and sometimes `locals`) queries fetched from raw.githubusercontent.com. The
# highlighter downloads and caches them under ~/.local/share/opentui the first
# time a file of that type is rendered. A distribution package must not fetch
# and execute third-party code at run time, so this script downloads every URL
# the table references once, writes each file under tree-sitter/<lang>/, and
# produces a patch that points the descriptors at
# /usr/share/opencode/tree-sitter/<lang>/<file> instead.
#
# The five grammars @opentui/core ships as assets (javascript, typescript,
# markdown, markdown_inline, zig) are not in the table and keep working.
#
# Run after a version bump:
#     ./opencode_grammars --source opencode-<version>.tar
# then commit tree-sitter/ and the regenerated patch alongside the new tarball.

import argparse
import os
import re
import subprocess
import sys
import tarfile
import tempfile
import urllib.request

INSTALL_PREFIX = "/usr/share/opencode"


def find_config(archive):
    with tarfile.open(archive) as tf:
        for member in tf.getmembers():
            if member.name.endswith("packages/tui/src/parsers-config.ts"):
                return tf.extractfile(member).read().decode()
    raise SystemExit("parsers-config.ts not found in %s" % archive)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--source", required=True)
    ap.add_argument("--outdir", default=".")
    args = ap.parse_args()

    text = find_config(args.source)
    tree = os.path.join(args.outdir, "tree-sitter")
    os.makedirs(tree, exist_ok=True)

    used = {}

    def fetch(filetype, url):
        base = url.split("?")[0].rstrip("/").split("/")[-1] or "file"
        key = (filetype, base)
        if key in used:
            return used[key]
        name = base
        i = 2
        while os.path.exists(os.path.join(tree, filetype, name)):
            name = "%d-%s" % (i, base)
            i += 1
        os.makedirs(os.path.join(tree, filetype), exist_ok=True)
        dest = os.path.join(tree, filetype, name)
        print("  fetch %s -> tree-sitter/%s/%s" % (url, filetype, name))
        req = urllib.request.Request(url, headers={"User-Agent": "opencode-grammars/1"})
        with urllib.request.urlopen(req) as r, open(dest, "wb") as f:
            f.write(r.read())
        local = "%s/tree-sitter/%s/%s" % (INSTALL_PREFIX, filetype, name)
        used[key] = local
        return local

    def fetch_with_retries(filetype, url):
        last = None
        for _ in range(3):
            try:
                return fetch(filetype, url)
            except Exception as e:  # noqa: BLE001
                last = e
        raise last

    # Process line by line: a URL belongs to the most recent `filetype:`, and
    # each URL sits on its own line in the arrays. A URL that cannot be fetched
    # (the table does contain a dead one) drops its whole line, which is what
    # the highlighter does at run time when a download fails.
    out_lines = []
    cur = None
    for line in text.split("\n"):
        m = re.search(r'filetype: "([a-z_]+)"', line)
        if m:
            cur = m.group(1)
        urls = re.findall(r'"(https?://[^"]+)"', line)
        if not urls:
            out_lines.append(line)
            continue
        newline = line
        ok = True
        for url in urls:
            try:
                local = fetch_with_retries(cur, url)
            except Exception as e:  # noqa: BLE001
                print("  SKIP (cannot fetch: %s): %s" % (e, url))
                ok = False
                break
            newline = newline.replace('"%s"' % url, '"%s"' % local)
        if ok:
            out_lines.append(newline)
    new = "\n".join(out_lines)
    if new == text:
        raise SystemExit("no URLs were rewritten; upstream table changed")

    with tempfile.TemporaryDirectory() as tmp:
        old_p = os.path.join(tmp, "old.ts")
        new_p = os.path.join(tmp, "new.ts")
        open(old_p, "w").write(text)
        open(new_p, "w").write(new)
        diff = subprocess.run(
            ["diff", "-u",
             "--label", "a/packages/tui/src/parsers-config.ts",
             "--label", "b/packages/tui/src/parsers-config.ts",
             old_p, new_p],
            capture_output=True, text=True,
        )
    if diff.returncode == 0:
        raise SystemExit("no URLs found to rewrite; upstream table changed")
    patch = os.path.join(args.outdir, "opencode-local-grammars.patch")
    open(patch, "w").write(diff.stdout)
    print("wrote %s (%d bytes)" % (patch, len(diff.stdout)))
    print("wrote tree-sitter/ (%d files)" % sum(len(f) for _, _, f in os.walk(tree)))


if __name__ == "__main__":
    sys.exit(main())
