"""``roam pre-commit`` — install or print a git pre-commit hook.

generates a hook that runs ``git diff --cached | roam critique``
on staged changes, exiting non-zero on high-severity findings. Idempotent:
installing twice is a no-op (rewrites the same content).

Output formats: text (default), ``--json``. SARIF is deliberately NOT
emitted because ``roam pre-commit`` is a setup/bootstrap command — its
output is human-facing setup status (pre-commit hook installed into
``.git/hooks``), not analysis findings with file:line coordinates.
SARIF is reserved for scanning results. See action.yml
_SUPPORTED_SARIF allowlist + W1175-RESEARCH propagation plan +
W1148 audit memo.
"""

from __future__ import annotations

from pathlib import Path

import click

from roam.capability import roam_capability
from roam.commands.resolve import ensure_index
from roam.db.connection import find_project_root
from roam.output.formatter import json_envelope, to_json

_HOOK_NAME = "pre-commit"
_HOOK_TEMPLATE = """#!/bin/sh
# Generated by `roam pre-commit --install`. Idempotent.
# Runs roam critique on staged changes. Exit 5 = high-severity finding.
# Set ROAM_PRECOMMIT_SKIP=1 to bypass.

if [ "${ROAM_PRECOMMIT_SKIP:-0}" = "1" ]; then
  exit 0
fi

if ! command -v roam >/dev/null 2>&1; then
  # NOTE: single-quoted to keep 'pip install roam-code' as literal text.
  # Backticks inside a double-quoted echo would trigger command
  # substitution (sh would actually run `pip install roam-code`).
  echo 'roam not on PATH; install with: pip install roam-code (or set ROAM_PRECOMMIT_SKIP=1).' >&2
  exit 0
fi

DIFF="$(git diff --cached)"
if [ -z "$DIFF" ]; then
  exit 0
fi

echo "$DIFF" | roam critique
status=$?
case "$status" in
  0) exit 0 ;;
  5) echo "roam critique flagged a high-severity finding. ROAM_PRECOMMIT_SKIP=1 to bypass." >&2 ; exit 1 ;;
  *) echo "roam critique exited $status — not blocking. ROAM_PRECOMMIT_SKIP=1 to silence." >&2 ; exit 0 ;;
esac
"""


def _hooks_dir(root: Path) -> Path:
    return root / ".git" / "hooks"


@roam_capability(
    name="pre-commit",
    category="getting-started",
    summary="Install or preview a roam-critique pre-commit git hook",
    maturity="stable",
    mcp_expose=False,
    mcp_preset=("core",),
    side_effect=True,
    task_required=False,
    destructive=False,
    stale_sensitive=False,
    ai_safe=True,
    requires_index=False,
)
@click.command(name="pre-commit")
@click.option("--install", is_flag=True, help="Write the hook into .git/hooks/pre-commit (idempotent).")
@click.option("--print", "print_only", is_flag=True, help="Print the hook script to stdout instead of installing.")
@click.pass_context
def pre_commit(ctx, install, print_only) -> None:
    """Install or preview a roam-critique pre-commit git hook."""
    json_mode = ctx.obj.get("json") if ctx.obj else False
    ensure_index()
    root = find_project_root()
    hooks = _hooks_dir(root)
    target = hooks / _HOOK_NAME

    if print_only or (not install):
        if json_mode:
            click.echo(
                to_json(
                    json_envelope(
                        "pre-commit",
                        summary={
                            "verdict": "preview-only — pass --install to write the hook",
                            "target": str(target),
                            "exists": target.exists(),
                        },
                        script=_HOOK_TEMPLATE,
                    )
                )
            )
        else:
            click.echo(f"# Would write to: {target}")
            click.echo()
            click.echo(_HOOK_TEMPLATE)
            click.echo()
            click.echo("Run `roam pre-commit --install` to write the hook.")
        return

    if not (root / ".git").exists():
        verdict = f"no .git directory under {root} — run from inside a git repository"
        if json_mode:
            click.echo(to_json(json_envelope("pre-commit", summary={"verdict": verdict, "installed": False})))
        else:
            click.echo(f"VERDICT: {verdict}")
        ctx.exit(2)
        return

    hooks.mkdir(parents=True, exist_ok=True)
    existing = target.read_text(encoding="utf-8") if target.exists() else None
    if existing == _HOOK_TEMPLATE:
        verdict = f"hook already up to date at {target}"
    else:
        target.write_text(_HOOK_TEMPLATE, encoding="utf-8")
        try:
            # chmod +x on POSIX. On Windows the bit is ignored but harmless.
            target.chmod(0o755)
        except OSError:
            pass
        verdict = f"installed roam pre-commit hook to {target}"

    if json_mode:
        click.echo(
            to_json(
                json_envelope(
                    "pre-commit",
                    summary={"verdict": verdict, "installed": True, "target": str(target)},
                )
            )
        )
        return
    click.echo(f"VERDICT: {verdict}")
    click.echo("  ROAM_PRECOMMIT_SKIP=1 to bypass on a single commit.")
