#!/usr/bin/env python3

import argparse
import subprocess
import sys


def main():
    parser = argparse.ArgumentParser(description="Format files that have changed between HEAD and REF")
    parser.add_argument("--ref", required=True, help="Check python files changed since REF")
    ns, unknown_args = parser.parse_known_args()

    changed_python_files: list[str] = []
    diff = subprocess.getoutput(f"git diff --name-status {ns.ref}")
    for line in diff.split("\n"):
        try:
            status, filename = line.split()
        except ValueError:
            continue
        if filename.endswith((".py", ".pyt")) and status != "D":
            changed_python_files.append(filename)
    if not changed_python_files:
        print("No changed python files")
        return
    s = "\n- ".join(changed_python_files)
    print(f"Changed python files:\n- {s}")

    args = ["ruff", "format"]
    args.extend(unknown_args or [])
    args.extend(changed_python_files)
    proc = subprocess.run(args)
    return proc.returncode


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