# standard
import os
import pathlib
import tempfile
import subprocess

# third party
# custom


def open_editor(
    initial_content: str = "",
    suffix: str = ".md",
) -> str:  # pragma: no cover
    """Open $EDITOR with initial_content, return the saved content."""

    editor = os.environ.get("EDITOR", "vim")
    with tempfile.NamedTemporaryFile(
        mode="w", suffix=suffix, delete=False, encoding="utf-8"
    ) as tf:
        tf.write(initial_content)
        tmp_path = pathlib.Path(tf.name)
    try:
        subprocess.run([editor, str(tmp_path)], check=True)
        return tmp_path.read_text(encoding="utf-8")
    finally:
        tmp_path.unlink(missing_ok=True)
