"""pjctx hook — Install/uninstall/status for git post-commit hook."""

from __future__ import annotations

import os
import stat

from pjctx.core.config import find_repo_root, get_pjctx_dir
from pjctx.core.git_ops import get_hooks_dir
from pjctx import ui

HOOK_NAME = "post-commit"
MARKER_START = "# --- pjctx auto-save start ---"
MARKER_END = "# --- pjctx auto-save end ---"
HOOK_BODY = """\
# --- pjctx auto-save start ---
if command -v pjctx >/dev/null 2>&1; then
    pjctx save --auto 2>/dev/null || true
fi
# --- pjctx auto-save end ---
"""


def run_install(obj: dict) -> None:
    repo_root = find_repo_root()
    if repo_root is None:
        ui.error("Not inside a git repository.")
        raise SystemExit(1)

    if not get_pjctx_dir(repo_root).exists():
        ui.error("Not initialized. Run 'pjctx init' first.")
        raise SystemExit(1)

    hooks_dir = get_hooks_dir(repo_root)
    hooks_dir.mkdir(parents=True, exist_ok=True)
    hook_path = hooks_dir / HOOK_NAME

    if hook_path.exists():
        content = hook_path.read_text()
        if MARKER_START in content:
            ui.warning("Hook already installed.")
            return
        # Append to existing hook
        if not content.endswith("\n"):
            content += "\n"
        content += "\n" + HOOK_BODY
    else:
        content = "#!/bin/sh\n\n" + HOOK_BODY

    hook_path.write_text(content)
    # Make executable
    hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)

    ui.success("Post-commit hook installed.")
    ui.info("Context will auto-save after each commit.")


def run_uninstall(obj: dict) -> None:
    repo_root = find_repo_root()
    if repo_root is None:
        ui.error("Not inside a git repository.")
        raise SystemExit(1)

    hooks_dir = get_hooks_dir(repo_root)
    hook_path = hooks_dir / HOOK_NAME

    if not hook_path.exists():
        ui.warning("No post-commit hook found.")
        return

    content = hook_path.read_text()
    if MARKER_START not in content:
        ui.warning("pjctx hook not found in post-commit.")
        return

    # Remove our section
    lines = content.splitlines(keepends=True)
    new_lines: list[str] = []
    inside = False
    for line in lines:
        if MARKER_START in line:
            inside = True
            continue
        if MARKER_END in line:
            inside = False
            continue
        if not inside:
            new_lines.append(line)

    remaining = "".join(new_lines).strip()
    if remaining == "#!/bin/sh" or not remaining:
        # Remove the file entirely if only shebang left
        hook_path.unlink()
        ui.success("Post-commit hook removed.")
    else:
        hook_path.write_text(remaining + "\n")
        ui.success("pjctx section removed from post-commit hook.")


def run_status(obj: dict) -> None:
    repo_root = find_repo_root()
    if repo_root is None:
        ui.error("Not inside a git repository.")
        raise SystemExit(1)

    hooks_dir = get_hooks_dir(repo_root)
    hook_path = hooks_dir / HOOK_NAME

    if not hook_path.exists():
        ui.info("Post-commit hook: [bold red]not installed[/]")
        return

    content = hook_path.read_text()
    if MARKER_START in content:
        ui.info("Post-commit hook: [bold green]installed[/]")
    else:
        ui.info("Post-commit hook: [bold yellow]exists but pjctx not found[/]")
