import os
import subprocess

import typer

from remotivelabs.cli.topology.cli.run_in_container import run_topology_cli_in_container
from remotivelabs.cli.topology.context import TopologyContext


def _extract_marked_output(text: str | None) -> str | None:
    if not text:
        return text

    start_marker = "---BEGIN REMOTIVE STUDIO OUTPUT---"
    end_marker = "---END REMOTIVE STUDIO OUTPUT---"

    start_idx = text.find(start_marker)
    end_idx = text.find(end_marker)

    if start_idx == -1 or end_idx == -1:
        return text

    start_idx += len(start_marker)
    return text[start_idx:end_idx].strip()


def run_topology_cli(ctx: typer.Context, args: list[str]) -> None:
    try:
        run_topology(ctx.obj["topology"], args, capture_output=False)
    except subprocess.CalledProcessError as e:
        raise typer.Exit(code=e.returncode)


def run_topology(ctx: TopologyContext, args: list[str], capture_output: bool = True) -> subprocess.CompletedProcess[str]:
    if ctx.cmd is None:
        result = run_topology_cli_in_container(ctx, args, capture_output=capture_output)
        if capture_output:
            result.stdout = _extract_marked_output(result.stdout) or ""
            result.stderr = _extract_marked_output(result.stderr) or ""
        return result
    cmd = [ctx.cmd] + args
    if ctx.workspace is not None:
        os.putenv("REMOTIVE_TOPOLOGY_WORKSPACE", str(ctx.workspace))
    if ctx.is_studio:
        os.putenv("REMOTIVE_STUDIO", "true")
    os.putenv("REMOTIVE_TOPOLOGY_WORKING_DIRECTORY", str(ctx.working_directory))
    try:
        result = subprocess.run(
            cmd,
            check=True,
            capture_output=capture_output,
            text=capture_output,
        )
    except subprocess.CalledProcessError as e:
        if capture_output:
            e.stderr = _extract_marked_output(e.stderr)
        raise

    if capture_output:
        result.stdout = _extract_marked_output(result.stdout) or ""

    return result
