#!/usr/bin/env python3
"""Refuse a push whose INDEX.md or CLAUDE.md is not what core/loom/index derives from the new tip.

INDEX.md and CLAUDE.md are derivations of the tree, not judgements, so the
one question is whether they were regenerated. The recipe at the incoming
tip judges its own tree: it is extracted with git show and run through its
own shebang as ``index --rev <new> --check --old <old>``. A tip without the
recipe adds no check. Git's hook environment, including GIT_DIR, is kept.
"""

import os
import stat
import subprocess
import sys
import tempfile


def main(args):
    if len(args) < 2 or not args[0] or not args[1]:
        print("30-index: usage: 30-index <old> <new>", file=sys.stderr)
        return 2
    old, new = args[:2]
    if subprocess.run(["git", "cat-file", "-e", f"{new}:core/loom/index"], capture_output=True).returncode:
        return 0
    recipe = subprocess.run(["git", "show", f"{new}:core/loom/index"], capture_output=True)
    if recipe.returncode or not recipe.stdout:
        print(f"core/loom/index unreadable at {new}", file=sys.stderr)
        return 1
    fd, path = tempfile.mkstemp(prefix="loom-index.")
    try:
        with os.fdopen(fd, "wb") as handle:
            handle.write(recipe.stdout)
        os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
        result = subprocess.run([path, "--rev", new, "--check", "--old", old], stderr=subprocess.PIPE)
    except OSError as exc:
        print(f"core/loom/index: {exc}", file=sys.stderr)
        return 1
    finally:
        os.unlink(path)
    if result.stderr:
        sys.stderr.buffer.write(result.stderr)
    return 1 if result.returncode else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
