#!/usr/bin/env python3
"""Post-commit: set Commit: SHA on sources touched in HEAD (amends commit once if needed)."""
from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

from header_lib import (
    REPO_ROOT,
    files_in_git_commit,
    git_head_sha,
    hook_skip_requested,
    update_header_commit,
)


def main() -> int:
    if hook_skip_requested():
        return 0

    sha = git_head_sha()
    if not sha:
        return 0

    touched: list[Path] = []
    for path in files_in_git_commit("HEAD"):
        text = path.read_text(encoding="utf-8", errors="replace")
        new_text = update_header_commit(text, path, sha)
        if new_text != text:
            path.write_text(new_text, encoding="utf-8", newline="\n")
            touched.append(path)

    if not touched:
        return 0

    env = os.environ.copy()
    env["HEADER_HOOK_SKIP"] = "1"
    for path in touched:
        rel = path.relative_to(REPO_ROOT).as_posix()
        subprocess.check_call(["git", "add", "--", rel], cwd=REPO_ROOT, env=env)
    subprocess.check_call(
        ["git", "commit", "--amend", "--no-edit", "--no-verify"],
        cwd=REPO_ROOT,
        env=env,
    )
    return 0


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