"""REAPER project rendering — headless render to WAV via subprocess."""

from __future__ import annotations

import subprocess
from pathlib import Path

# Default REAPER executable path on Windows
DEFAULT_REAPER_EXE = Path(r"C:\Program Files\REAPER (x64)\reaper.exe")


def render_project(
    rpp_path: str | Path,
    output_wav: str | Path,
    reaper_exe: str | Path | None = None,
    timeout_seconds: int = 120,
) -> None:
    """Render a .rpp project to WAV using the REAPER CLI.

    Args:
        rpp_path:      Path to the .rpp project file.
        output_wav:    Path where the rendered WAV will be written.
        reaper_exe:    Path to reaper.exe. Defaults to
                       ``C:\\Program Files\\REAPER (x64)\\reaper.exe``.
        timeout_seconds: Max seconds to wait for render to complete.

    Raises:
        FileNotFoundError: If reaper.exe is not found at the expected path
                           and no explicit path was provided.
        RuntimeError:     If the render process exits with a non-zero code
                          or is killed by the timeout.
    """
    reaper_path = Path(reaper_exe) if reaper_exe else DEFAULT_REAPER_EXE

    if not reaper_path.exists():
        raise FileNotFoundError(
            f"REAPER executable not found at: {reaper_path}\n"
            "Install REAPER or provide an explicit reaper_exe path."
        )

    rpp_abs = str(Path(rpp_path).resolve())
    wav_abs = str(Path(output_wav).resolve())

    cmd = [
        str(reaper_path),
        "-nosplash",
        "-render",
        rpp_abs,
        "-outfile",
        wav_abs,
    ]

    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        timeout=timeout_seconds,
    )

    if result.returncode != 0:
        raise RuntimeError(
            f"REAPER render failed (exit {result.returncode}):\n"
            f"stdout: {result.stdout}\n"
            f"stderr: {result.stderr}"
        )