#!/usr/bin/env python
"""Lint what is about to be pushed, so clang-tidy debt never reaches main unnoticed.

Installed by `python scripts/setup.py` (copied to .git/hooks/pre-push when none exists;
an existing hook can call this file instead). For every updated ref it lints the
translation units that the pushed commits touch, against the remote's old tip, through
`scripts/lint.py --changed --quick --profile fast`: the changed units and one unit per
changed header, without the static analyzer, so a push waits seconds to a few minutes.
CI then lints every unit the change reaches under the full profile, from a cache of
clean results. Set GDL_SKIP_LINT=1 to push regardless, for example to publish a fix for
the lint itself. A push interrupted at the terminal ends git but not this hook, so the
hook watches the git that ran it and ends the lint, workers and all, once git is gone.
"""

import os
import pathlib
import subprocess
import sys

ROOT = pathlib.Path(__file__).resolve().parents[2]
LINT = ROOT / "scripts" / "lint.py"
sys.path.insert(0, str(ROOT / "scripts"))  # the top-level helpers
import process_tree  # noqa: E402  the path above makes it importable


def pushed_ranges(lines):
    """(base, head) pairs for the refs being created or updated; deletions are skipped."""
    ranges = []
    for line in lines:
        parts = line.split()
        if len(parts) != 4:
            continue
        _local_ref, local_oid, _remote_ref, remote_oid = parts
        if set(local_oid) == {"0"}:
            continue
        ranges.append((None if set(remote_oid) == {"0"} else remote_oid, local_oid))
    return ranges


def base_for(base, head, git="git"):
    """The remote's old tip when it exists locally; otherwise where head left origin/main."""
    if base is not None:
        if subprocess.run([git, "cat-file", "-e", f"{base}^{{commit}}"], cwd=ROOT,
                          capture_output=True, check=False).returncode == 0:
            return base
    merge_base = subprocess.run([git, "merge-base", "origin/main", head], cwd=ROOT,
                                capture_output=True, text=True, check=False)
    if merge_base.returncode == 0 and merge_base.stdout.strip():
        return merge_base.stdout.strip()
    return None


def run_lint(arguments, watched=None):
    """Run the lint; end it, workers and all, once the watched process (git) is gone."""
    gone = []
    lint = process_tree.start([sys.executable, str(LINT), *arguments], cwd=ROOT)

    def end():
        gone.append(True)
        process_tree.stop(lint)

    if watched is not None:
        process_tree.stop_when_gone(watched, end)
    try:
        code = lint.wait()
    except KeyboardInterrupt:
        process_tree.stop(lint)
        raise
    if gone:
        print("pre-push: git is gone, so the lint was stopped", file=sys.stderr)
        return 1
    return code


def main():
    if os.environ.get("GDL_SKIP_LINT") == "1":
        print("pre-push: lint skipped by GDL_SKIP_LINT=1", file=sys.stderr)
        return 0
    for base, head in pushed_ranges(sys.stdin):
        start = base_for(base, head)
        if start is None:
            print("pre-push: no base to compare against; linting is skipped for this ref",
                  file=sys.stderr)
            continue
        print(f"pre-push: quick clang-tidy over the units changed in {start[:9]}..{head[:9]} "
              "(CI lints the full fan-out)", file=sys.stderr)
        git = process_tree.nearest_ancestor(process_tree.table(), os.getpid(), process_tree.GIT)
        code = run_lint(["--changed", f"{start}..{head}", "--quick", "--profile", "fast"], git)
        if code != 0:
            print("pre-push: refused, fix the findings above (or push with GDL_SKIP_LINT=1).",
                  file=sys.stderr)
            return 1
    return 0


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