import shutil
import subprocess
from pathlib import Path


class TopologyCLIError(RuntimeError):
    """Raised when the remotive CLI invocation fails."""


def run_topology_cli(args: list[str], workspace: str) -> str:
    """
    Execute the native Remotive Topology CLI:

        remotive topology <args>

    Returns stdout on success. Raises :exc:`TopologyCLIError` on failure.
    """
    remotive_path = shutil.which("remotive")
    if remotive_path is None:
        raise TopologyCLIError("remotive CLI not found on PATH\nDETAILS: Install Remotive CLI and ensure `remotive` is available on PATH.")

    cmd = [remotive_path, "topology", *args]

    cwd = Path(workspace).resolve()
    if not cwd.is_dir():
        raise TopologyCLIError(f"Workspace directory not found\nPATH: {workspace}")

    try:
        completed = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=True,
            cwd=cwd,
        )
        return completed.stdout.strip()

    except subprocess.CalledProcessError as e:
        raise TopologyCLIError(
            f"remotive topology command exited with code {e.returncode}\n"
            f"COMMAND: {' '.join(cmd)}\n"
            f"STDOUT: {e.stdout.strip()}\n"
            f"STDERR: {e.stderr.strip()}"
        ) from e
