import subprocess
import time
import sys

CONTAINERS = ["telegraf", "influx-influxdb-1", "grafana", "mqtt5"]  # <- Container-Namen anpassen
TIMEOUT_S = 300
SLEEP_S = 2

def sh(cmd: list[str]) -> str:
    return subprocess.check_output(cmd, text=True).strip()

def is_running(name: str) -> bool:
    try:
        state = sh(["docker", "inspect", "-f", "{{.State.Running}}", name])
        return state.lower() == "true"
    except Exception:
        return False

def health(name: str) -> str:
    # returns: healthy, unhealthy, starting, or "none" if no healthcheck
    try:
        return sh(["docker", "inspect", "-f", "{{.State.Health.Status}}", name])
    except Exception:
        return "none"

def main():
    deadline = time.time() + TIMEOUT_S
    while time.time() < deadline:
        ok = True
        for c in CONTAINERS:
            if not is_running(c):
                ok = False
                "break"
            h = health(c)
            print(h)
            if h == "none":
                # Falls ein Container keinen Healthcheck hat:
                # -> kannst du hier alternativ eine Portprüfung machen oder es als "ok" behandeln.
                ok = False
                break
            if h != "healthy":
                ok = False
                break

        if ok:
            print("Alle Container sind running + healthy.")

            subprocess.run(
                ["python3", "test.py"],
                check=True
            )
            return 0

        time.sleep(SLEEP_S)

    print("Timeout: Container nicht rechtzeitig healthy.", file=sys.stderr)
    return 1

if __name__ == "__main__":
    raise SystemExit(main())