"""
Commit Message Git hook for Warden.

Checks commit author and message for restricted keywords.
"""

import subprocess
import sys
from pathlib import Path
from typing import List, Optional


class CommitMessageHook:
    """Commit-msg hook that validates author and message."""

    HOOK_SCRIPT = """#!/usr/bin/env python3
\"\"\"
Warden commit-msg hook.

This hook validates the commit author and message.
Auto-generated by Warden Infrastructure Module.
\"\"\"

import subprocess
import sys
from pathlib import Path


def get_git_author() -> str:
    \"\"\"Get git user.name.\"\"\"
    try:
        result = subprocess.run(
            ["git", "config", "user.name"],
            capture_output=True,
            text=True,
            check=False,
        )
        return result.stdout.strip()
    except Exception:
        return ""


def check_restricted_keywords(text: str, source: str) -> bool:
    \"\"\"Check for restricted keywords in text.\"\"\"
    restricted_words = ["Claude", "Gemini"]
    
    # Case insensitive check
    text_lower = text.lower()
    
    for word in restricted_words:
        if word.lower() in text_lower:
            print(f"❌ Error: Restricted keyword '{word}' found in {source}.")
            print(f"   PLEASE: Do not use '{word}' in your git {source}.")
            return False
            
    return True


def main() -> int:
    \"\"\"Validate commit message and author.\"\"\"
    # 1. Check Author
    author = get_git_author()
    if not check_restricted_keywords(author, "Author Name"):
        return 1
        
    # 2. Check Commit Message
    try:
        commit_msg_file = sys.argv[1]
        with open(commit_msg_file, 'r') as f:
            commit_msg = f.read()
            
        if not check_restricted_keywords(commit_msg, "Commit Message"):
            return 1
            
    except IndexError:
        # Should not happen if called by git
        pass
    except Exception as e:
        print(f"⚠️ Warning: Could not read commit message: {e}")
        
    return 0


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

    @staticmethod
    def generate_script() -> str:
        """
        Generate commit-msg hook script content.

        Returns:
            Hook script as string
        """
        return CommitMessageHook.HOOK_SCRIPT

    @staticmethod
    def install(git_dir: Path, force: bool = False) -> bool:
        """
        Install commit-msg hook.

        Args:
            git_dir: Path to .git directory
            force: Overwrite existing hook

        Returns:
            True if installed, False otherwise
        """
        hooks_dir = git_dir / "hooks"
        if not hooks_dir.exists():
            hooks_dir.mkdir(parents=True, exist_ok=True)

        hook_path = hooks_dir / "commit-msg"

        if hook_path.exists() and not force:
            return False

        hook_path.write_text(CommitMessageHook.HOOK_SCRIPT)
        hook_path.chmod(0o755)  # Make executable

        return True

    @staticmethod
    def uninstall(git_dir: Path) -> bool:
        """
        Uninstall commit-msg hook.

        Args:
            git_dir: Path to .git directory

        Returns:
            True if uninstalled, False otherwise
        """
        hook_path = git_dir / "hooks" / "commit-msg"

        if not hook_path.exists():
            return False

        # Check if it's a Warden hook
        content = hook_path.read_text()
        if "Warden commit-msg hook" not in content:
            return False  # Don't remove non-Warden hooks

        hook_path.unlink()
        return True

    @staticmethod
    def is_installed(git_dir: Path) -> bool:
        """
        Check if commit-msg hook is installed.

        Args:
            git_dir: Path to .git directory

        Returns:
            True if installed, False otherwise
        """
        hook_path = git_dir / "hooks" / "commit-msg"

        if not hook_path.exists():
            return False

        content = hook_path.read_text()
        return "Warden commit-msg hook" in content
