"""Set up git hooks for a project."""

from __future__ import annotations

import subprocess
from pathlib import Path

import click


def setup_hooks(project_dir: Path) -> None:
    """Configure git hooks for a project repository.

    Sets core.hooksPath to .githooks/ and ensures hook scripts are executable.
    Does NOT overwrite existing hooks - only configures git to use them.
    """
    project_dir = project_dir.resolve()
    hooks_dir = project_dir / ".githooks"

    if not (project_dir / ".git").exists():
        raise click.ClickException(f"{project_dir} is not a git repository")

    if not hooks_dir.exists():
        click.echo(f"  No .githooks/ directory found in {project_dir}")
        click.echo("  Skipping hook setup. Create .githooks/ with your hook scripts first.")
        return

    # Set core.hooksPath
    result = subprocess.run(
        ["git", "config", "core.hooksPath", ".githooks"],
        cwd=project_dir,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        raise click.ClickException(f"Failed to set core.hooksPath: {result.stderr}")

    click.echo(f"  Set core.hooksPath to .githooks/ in {project_dir}")

    # Ensure hook scripts are executable
    hook_files = ["pre-commit", "commit-msg", "pre-push", "post-commit"]
    for hook in hook_files:
        hook_path = hooks_dir / hook
        if hook_path.exists() and not hook_path.stat().st_mode & 0o111:
            hook_path.chmod(hook_path.stat().st_mode | 0o755)
            click.echo(f"  Made {hook} executable")

    click.echo("  Git hooks configured.")
