"""
Git hooks implementation.
"""
import os
import subprocess
import sys
from pathlib import Path
from typing import List

class Hook:
    """Manages Git hooks."""
    
    def __init__(self, repo_path: Path):
        self.repo_path = repo_path
        self.hooks_dir = repo_path / ".rvs" / "hooks"
    
    def run_hook(self, hook_name: str, args: List[str] = None) -> bool:
        """Run a hook script if it exists."""
        hook_file = self.hooks_dir / hook_name
        if not hook_file.exists() or not os.access(hook_file, os.X_OK):
            return True  # Hook doesn't exist or isn't executable
        
        try:
            # Prepare environment
            env = os.environ.copy()
            env["RVS_DIR"] = str(self.repo_path / ".rvs")
            
            # Run hook
            result = subprocess.run(
                [str(hook_file)] + (args or []),
                cwd=self.repo_path,
                env=env,
                capture_output=True,
                text=True
            )
            
            # Only print hook output if it's not the default sample hook messages
            if result.stdout and not result.stdout.strip().startswith("Running "):
                print(result.stdout)
            if result.stderr:
                print(result.stderr, file=sys.stderr)
            
            return result.returncode == 0
        except Exception as e:
            print(f"Error running hook {hook_name}: {e}")
            return False
    
    def install_sample_hooks(self, show_message: bool = False):
        """Install sample hooks."""
        # Create hooks directory if it doesn't exist
        self.hooks_dir.mkdir(parents=True, exist_ok=True)
        
        # Pre-commit hook
        pre_commit = self.hooks_dir / "pre-commit"
        with open(pre_commit, 'w') as f:
            f.write("""#!/bin/sh
# Sample pre-commit hook
echo "Running pre-commit hook"
# Add your checks here
# Exit with non-zero status to abort commit
exit 0
""")
        pre_commit.chmod(0o755)
        
        # Post-commit hook
        post_commit = self.hooks_dir / "post-commit"
        with open(post_commit, 'w') as f:
            f.write("""#!/bin/sh
# Sample post-commit hook
echo "Running post-commit hook"
# Add your post-commit actions here
exit 0
""")
        post_commit.chmod(0o755)
        
        if show_message:
            print("Sample hooks installed in .rvs/hooks/")
