import pytest
import time
from helpers.container import exec_in_container

MAP_CONTAINERS = ["map-gw", "map-ext1", "map-ext2"]

REQUIRED_PROCS = {
    "map-gw": ["ubusd", "wifimngr", "ieee1905d", "mapcontroller", "mapagent"],
    "map-ext1": ["ubusd", "wifimngr", "ieee1905d", "mapagent"],
    "map-ext2": ["ubusd", "wifimngr", "ieee1905d", "mapagent"],
}

MAX_WAIT = 60
INTERVAL = 2


def is_process_running(container, process):
    """
    Return True if the process is running.
    """
    result = exec_in_container(container, ["pidof", process])
    return result.returncode == 0 and result.stdout.strip() != ""


def container_ready(container, processes):
    """
    Check if all required processes are running.
    """
    for p in processes:
        if not is_process_running(container, p):
            return False
    return True


@pytest.fixture(scope="session", autouse=True)
def wait_for_containers_ready():
    """
    Wait until all containers are ready.
    """
    start = time.time()
    print("\nWaiting for MAP containers to become ready...")

    while time.time() - start < MAX_WAIT:
        all_ready = True
        for c in MAP_CONTAINERS:
            procs = REQUIRED_PROCS.get(c, [])

            if not container_ready(c, procs):
                all_ready = False
                break

        if all_ready:
            print("All containers are ready.\n")
            return

        time.sleep(INTERVAL)

    raise TimeoutError(
        f"Containers not ready in {MAX_WAIT} seconds. "
    )

