#!/usr/bin/env python3
"""vre_parallel - Run vre on multiple workers. Compatibility with multi-gpu via CUDA_VISIBLE_DEVICES."""
import sys
import os
import subprocess
import signal
from functools import partial
from argparse import ArgumentParser, Namespace, REMAINDER
from vre_video import VREVideo

def _cleanup(processes: list, signum, frame): # pylint: disable=unused-argument
    print("Terminating subprocesses...")
    for p in processes:
        p.terminate()
    sys.exit(1)

def _get_gpu_indices() -> list[str] | None:
    """Checks if this run is supposed to happen on GPUs by investigating CUDA_VISIBLE_DEVICES"""
    if (gpu_indices := os.getenv("CUDA_VISIBLE_DEVICES")) is None:
        return None
    gpu_indices_split = gpu_indices.split(",")
    assert len(gpu_indices_split) > 1, f"At least 2 GPUs must be provided. For 1, use normal vre. {gpu_indices=}"
    assert sorted(set(gpu_indices_split)) == sorted(gpu_indices_split), gpu_indices_split
    return gpu_indices_split

def get_args() -> Namespace:
    """Argument parsing"""
    parser = ArgumentParser(description="Distribute VRE processing across multiple GPUs")
    parser.add_argument("video_path", type=str, help="Path to the video file")
    parser.add_argument("--n_workers", type=int, required=True, help="The number of workers (GPUs or CPUs) to run vre")
    parser.add_argument("vre_args", nargs=REMAINDER, help="Additional arguments to pass to VRE")
    args = parser.parse_args()
    return args

def main(args: Namespace):
    """main fn"""
    gpu_indices = _get_gpu_indices()
    assert gpu_indices is None or len(gpu_indices) == args.n_workers, f"{gpu_indices=} vs {args.n_workers=}"

    if "--frames" in args.vre_args:
        args.vre_args.pop(ix := args.vre_args.index("--frames")) # pop the --frames entry
        start_frame, end_frame = map(int, args.vre_args.pop(ix).split("..")) # pop the next arg too: the actual frames
    else:
        video = VREVideo(args.video_path)
        start_frame, end_frame = 0, len(video)

    total_frames = end_frame - start_frame
    if total_frames < args.n_workers:
        print(f"{total_frames=} < {args.n_workers}. Keeping just first ones.")
        args.n_workers = total_frames

    frames_per_gpu = total_frames // args.n_workers

    processes = []
    for i in range(args.n_workers):
        gpu_start_frame = start_frame + i * frames_per_gpu
        gpu_end_frame = gpu_start_frame + frames_per_gpu
        if i == args.n_workers - 1: # Ensure the last partition captures all remaining frames
            gpu_end_frame = end_frame

        env = {"VRE_DEVICE": "cpu"}
        if gpu_indices is not None:
            env = {"CUDA_VISIBLE_DEVICES": gpu_indices[i], "VRE_DEVICE": "cuda"}
        cmd = ["vre", args.video_path, "--frames", f"{gpu_start_frame}..{gpu_end_frame}"] + args.vre_args

        env_str = " ".join([f"{k}={v}" for k, v in env.items()])
        print(f"Executing command: {env_str} {' '.join(cmd)}")

        process = subprocess.Popen(cmd, env={**os.environ.copy(), **env})
        processes.append(process)

    signal.signal(signal.SIGINT, partial(_cleanup, processes=processes))
    signal.signal(signal.SIGTERM, partial(_cleanup, processes=processes))

    # Wait for all processes to complete
    return_codes = [p.wait() for p in processes]
    if any(rc != 0 for rc in return_codes):
        print(f"Some workers failed: {return_codes=}")
        sys.exit(1)

if __name__ == "__main__":
    main(get_args())
