#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2024-2026 Lukasz Krzemien (biuro@softspark.eu)
# Source: https://github.com/softspark/ai-toolkit

"""Install a fallback pre-commit hook for the ai-toolkit.

Used for non-Claude editors to enforce the constitution and quality gates.

Usage: python3 install_git_hooks.py [target-dir]
"""
from __future__ import annotations

import os
import sys
from pathlib import Path

PRE_COMMIT_CONTENT = """\
#!/usr/bin/env bash
# ai-toolkit fallback pre-commit hook
# Auto-generated by ai-toolkit.

# This hook acts as a safety fallback to ensure AI-generated commits
# aren't bypassing standard quality checks (like unresolved conflicts or missing tests)
# when using editors without native bash process hooks (like Cursor or Windsurf).

echo "[ai-toolkit] Running pre-commit quality gate..."

# 1. Check for unresolved merge conflicts
if git diff --cached -S'<<<<<<<' --name-only | grep -q '.*'; then
    echo "ERROR: Unresolved merge conflicts found in staged files."
    echo "   Please resolve conflicts and remove '<<<<<<<' markers before committing."
    exit 1
fi

# 2. Call the global quality-check if it exists
QUALITY_CHECK="$HOME/.softspark/ai-toolkit/hooks/quality-check.sh"
if [ -x "$QUALITY_CHECK" ]; then
    if ! "$QUALITY_CHECK"; then
        echo "ERROR: Linter or type checks failed."
        echo "   Use 'git commit --no-verify' if you absolutely must bypass this."
        exit 1
    fi
fi

echo "[ai-toolkit] Pre-commit checks passed."
exit 0
"""


def main() -> None:
    target_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd()
    git_hooks_dir = target_dir / ".git" / "hooks"

    if not git_hooks_dir.is_dir():
        print("  Skipped: git hooks (not a git repository)")
        return

    pre_commit = git_hooks_dir / "pre-commit"

    # Back up existing pre-commit hook if not ours
    if pre_commit.is_file():
        content = pre_commit.read_text(encoding="utf-8", errors="replace")
        if "ai-toolkit fallback pre-commit hook" not in content:
            backup = git_hooks_dir / "pre-commit.backup"
            pre_commit.rename(backup)
            print("  Backed up existing pre-commit hook to pre-commit.backup")

    pre_commit.write_text(PRE_COMMIT_CONTENT, encoding="utf-8")
    pre_commit.chmod(pre_commit.stat().st_mode | 0o111)
    print("  Installed: .git/hooks/pre-commit (ai-toolkit safety fallback)")


if __name__ == "__main__":
    main()
