"""External editor integration for the chat TUI.

Provides functionality to open text in $EDITOR for composition of long messages.
"""

import os
import subprocess
import tempfile


class EditorError(Exception):
    """Raised when editor operations fail."""

    pass


def open_in_editor(current_text: str = "") -> str | None:
    """Open text in $EDITOR and return the edited content.

    Uses the editor specified by $EDITOR, falling back to $VISUAL, then 'vi'.

    Args:
        current_text: The initial text to populate the editor with.

    Returns:
        The edited text if successful, None if editor failed or was cancelled.

    Raises:
        EditorError: If the editor could not be found or execution failed.
    """
    editor = os.environ.get("EDITOR", os.environ.get("VISUAL", "vi"))

    try:
        # Create a temporary file with the current text
        with tempfile.NamedTemporaryFile(
            mode="w",
            suffix=".md",
            delete=False,
        ) as tmp_file:
            tmp_file.write(current_text)
            tmp_path = tmp_file.name

        try:
            # Open the editor and wait for it to close
            result = subprocess.run([editor, tmp_path], check=False)

            if result.returncode != 0:
                raise EditorError(f"Editor exited with code {result.returncode}")

            # Read the edited content back
            with open(tmp_path, encoding="utf-8") as f:
                edited_text = f.read()

            # Strip trailing newlines that editors often add
            return edited_text.rstrip("\n")

        finally:
            # Clean up the temporary file
            try:
                os.unlink(tmp_path)
            except OSError:
                pass

    except FileNotFoundError:
        raise EditorError(
            f"Editor '{editor}' not found. Set $EDITOR environment variable."
        )
    except Exception as e:
        if isinstance(e, EditorError):
            raise
        raise EditorError(f"Failed to open editor: {e}")
