"""
Delegate all arguments to the remotive-topology CLI inside Docker.
Example:
  remotive topology status --help
"""

import os
import shutil
import subprocess

import typer


def check_docker_installed() -> None:
    """Check if Docker is installed and accessible."""
    if shutil.which("docker") is None:
        typer.echo("❌ Docker is not installed or not in PATH.", err=True)
        typer.echo("👉 Please install Docker: https://docs.docker.com/get-docker/", err=True)
        raise typer.Exit(code=1)


def run_topology_cli_in_docker(ctx: typer.Context, args: list[str]) -> None:
    check_docker_installed()

    topology_image = ctx.obj.get("topology_image") or "remotivelabs/remotive-topology:0.14.1"

    # Build base docker command equivalent to your alias
    docker_cmd = [
        "docker",
        "run",
    ]
    # -u flag only works on Unix (os.getuid/getgid not available on Windows)
    if hasattr(os, "getuid") and hasattr(os, "getgid"):
        docker_cmd += ["-u", f"{os.getuid()}:{os.getgid()}"]  # type: ignore[unused-ignore, attr-defined]  # needed on Windows
    docker_cmd += [
        "--rm",
        "-v",
        f"{os.path.expanduser('~')}/.config/remotive/:/.config/remotive",
        "-v",
        f"{os.getcwd()}:{os.getcwd()}",
        "-w",
        os.getcwd(),
        "-e",
        f"REMOTIVE_CLOUD_ORGANIZATION={os.environ.get('REMOTIVE_CLOUD_ORGANIZATION', '')}",
        "-e",
        f"REMOTIVE_CLOUD_AUTH_TOKEN={os.environ.get('REMOTIVE_CLOUD_AUTH_TOKEN', '')}",
        "-e",
        "REMOTIVE_CONFIG_DIR=/.config/remotive",
    ]
    docker_cmd += [topology_image] + args

    # typer.echo(f"🚀 Running: {' '.join(docker_cmd)}")

    try:
        subprocess.run(docker_cmd, check=True)
    except subprocess.CalledProcessError as e:
        raise typer.Exit(code=e.returncode)
    except FileNotFoundError:
        typer.echo("❌ Docker not found. Make sure Docker is installed and in PATH.", err=True)
        raise typer.Exit(code=1)
