#!/usr/bin/env python3
"""
Prepare-commit-msg hook: Add co-author attribution to commits.

Every commit by Genie should credit the Automagik Genie LLM as co-author.
This hook automatically appends the co-author line if not already present.

Exit codes:
    0 - Hook passed, commit message prepared
    1 - Hook failed, abort commit
"""

import sys
import os
from pathlib import Path


def main():
    # Undocumented escape hatch: disable co-author attribution
    if os.environ.get('GENIE_DISABLE_COAUTHOR') == '1':
        sys.exit(0)

    commit_msg_file = sys.argv[1] if len(sys.argv) > 1 else None

    if not commit_msg_file or not Path(commit_msg_file).exists():
        sys.exit(0)  # No message file, nothing to do

    msg_path = Path(commit_msg_file)
    content = msg_path.read_text()

    # This is Genie's identity - hardcoded by design
    target_name = "Automagik Genie 🧞"
    target_email = "genie@namastex.ai"
    normalized_line = f"Co-authored-by: {target_name} <{target_email}>"

    lines = content.splitlines()
    updated = False
    found_genie = False

    for i, line in enumerate(lines):
        if line.strip().lower().startswith("co-authored-by:") and target_name in line:
            found_genie = True
            if line.strip() != normalized_line:
                lines[i] = normalized_line
                updated = True

    if not found_genie:
        # Ensure a trailing blank line, then append normalized co-author line
        if lines and lines[-1].strip() != "":
            lines.append("")
        lines.append(normalized_line)
        updated = True

    if updated:
        # Preserve final newline
        msg = "\n".join(lines)
        if not msg.endswith("\n"):
            msg += "\n"
        msg_path.write_text(msg)
    sys.exit(0)


if __name__ == "__main__":
    main()
