"""Editor helpers for reconciliation workflows."""

from __future__ import annotations

import shlex
import shutil
import subprocess
from pathlib import Path

from .exceptions import EditorCancelledError


def _git_editor() -> str | None:
    """Return the repository-local Git-configured editor, if available."""
    completed = subprocess.run(
        ["git", "config", "--local", "--get", "core.editor"],
        check=False,
        capture_output=True,
        text=True,
    )
    if completed.returncode != 0:
        return None
    editor = completed.stdout.strip()
    return editor or None


def _fallback_editor() -> str | None:
    """Return a simple terminal editor fallback when available."""
    return shutil.which("nano") or shutil.which("vim")


def _resolve_editor() -> str | None:
    """Resolve the editor command using Git first, then terminal fallbacks."""
    return _git_editor() or _fallback_editor()


def edit_file(initial_text: str, path: Path) -> str:
    """Open the user's editor on the given file and return the edited contents."""
    path.write_text(initial_text)
    editor = _resolve_editor()
    if not editor:
        raise EditorCancelledError(
            "Set git core.editor or install nano/vim."
        )

    command = f"{editor} {shlex.quote(str(path))}"
    completed = subprocess.run(command, shell=True, check=False)
    if completed.returncode != 0:
        raise EditorCancelledError("Reconciliation editor exited without saving a plan.")
    return path.read_text()
