# =============================================================================
# Název:   run_test_results_parallel_v1.2.py
# Verze:   1.2
# Datum:   2026-05-29
# Popis:   Launcher pro paralelni stahovani Test Results. Spusti N procesu
#          download_test_results_v1.4.py, kazdy s --shard i --of N, kazdy
#          ve vlastnim konzolovem okne (CREATE_NEW_CONSOLE) a s vlastnim
#          profilem browser_profile_{i}. Pocka, az vsechny dobehnou.
# Zmeny v1.2: cili na download_test_results_v1.4.py (retry na urovni reportu).
# Zmeny v1.1: cili na v1.3 (robustni login + okno se pri chybe nezavre),
#             STAGGER_S zvysen na 8 s.
# =============================================================================
import subprocess
import sys
import os
import time

N_SHARDS  = 4                       # pocet soubeznych procesu (oken)
STAGGER_S = 8                       # rozestup mezi starty (s) — at se OKTA login
                                    # nezahlti soucasnymi pozadavky najednou
BASE   = os.path.dirname(os.path.abspath(__file__))
SCRIPT = os.path.join(BASE, "download_test_results_v1.4.py")
PYEXE  = sys.executable             # stejny interpreter (.venv), kterym byl spusten launcher

# Vlastni konzolove okno pro kazdy proces (jen Windows) -> logy se neprolinaji.
CREATE_NEW_CONSOLE = getattr(subprocess, "CREATE_NEW_CONSOLE", 0)


def main():
    print(f"Launcher: spoustim {N_SHARDS} shardu skriptu {os.path.basename(SCRIPT)}")
    procs = []
    for shard in range(1, N_SHARDS + 1):
        cmd = [PYEXE, SCRIPT, "--shard", str(shard), "--of", str(N_SHARDS)]
        print(f"  -> shard {shard}/{N_SHARDS}: {' '.join(cmd)}")
        p = subprocess.Popen(cmd, cwd=BASE, creationflags=CREATE_NEW_CONSOLE)
        procs.append((shard, p))
        if shard < N_SHARDS and STAGGER_S:
            time.sleep(STAGGER_S)   # rozestup startu (login)

    print("Launcher: vsechny shardy spusteny, cekam na dokonceni...")
    rc = {}
    for shard, p in procs:
        p.wait()
        rc[shard] = p.returncode
        print(f"Launcher: shard {shard} skoncil (returncode={p.returncode}).")

    failed = [s for s, code in rc.items() if code != 0]
    if failed:
        print(f"Launcher: HOTOVO, ale shardy {failed} skoncily s chybou (returncode != 0).")
    else:
        print("Launcher: HOTOVO — vsechny shardy uspesne dokonceny.")


if __name__ == "__main__":
    main()
