"""Contains logic to work with files via the configured editor."""

import shlex
import subprocess
import tempfile
from pathlib import Path

from notulist.config import AppSettings


def launch_editor() -> str:
    """Launch the editor with a temporary file and return its contents afterwards.

    The editor setting is parsed with :func:`shlex.split`, so it may contain
    arguments (e.g. ``"zeditor -w"``).
    """
    settings = AppSettings()
    with tempfile.NamedTemporaryFile(suffix=".md", delete=False, mode="w") as f:
        tmp_path = f.name
    try:
        subprocess.run([*shlex.split(settings.editor), tmp_path], check=True)
        return Path(tmp_path).read_text().strip()
    finally:
        Path(tmp_path).unlink(missing_ok=True)
