import os
from pathlib import Path
from typing import Dict
from rich.console import Console

console = Console()


def install_hooks(project_root: Path, hooks: Dict[str, str]):
    """
    Install git hooks based on configuration.
    """
    git_dir = project_root / ".git"
    if not git_dir.exists():
        console.print("[dim]Skipping hooks installation: Not a git repository.[/dim]")
        return

    hooks_dir = git_dir / "hooks"
    hooks_dir.mkdir(exist_ok=True)

    for hook_name, command in hooks.items():
        hook_path = hooks_dir / hook_name

        # Check if exists
        if hook_path.exists():
            # Check if it was generated by us
            try:
                with open(hook_path, "r") as f:
                    first_line = f.readline()
                if "Monoco Hook" not in first_line:
                    console.print(
                        f"[yellow]Warning: Hook '{hook_name}' already exists and is not managed by Monoco. Skipping.[/yellow]"
                    )
                    continue
                # If it IS managed by us, we overwrite it to update the command
            except Exception:
                console.print(
                    f"[yellow]Warning: Hook '{hook_name}' exists and cannot be read. Skipping.[/yellow]"
                )
                continue

        content = f"""#!/bin/sh
# Monoco Hook: {hook_name}
# Auto-generated by Monoco Toolkit. Do not edit manually.

{command}
exit $?
"""
        try:
            with open(hook_path, "w") as f:
                f.write(content)

            # Make executable
            os.chmod(hook_path, 0o755)
            console.print(f"[green]✓ Installed hook '{hook_name}'[/green]")
        except Exception as e:
            console.print(f"[red]Failed to install hook '{hook_name}': {e}[/red]")
