"""
Multi-camera concurrent streaming stress test.

What it does:
- Opens all cameras in CAM_INDICES simultaneously via CameraObject.open() (MSMF)
- Continuously reads frames from all of them in a round-robin loop for TEST_DURATION_SECONDS
- Tallies successful vs failed grabs per camera
- Prints a summary so we know whether this hardware/USB topology can sustain
  continuous simultaneous streaming from all cameras, which is what real-time
  hand tracking (sending data to Unreal over UDP every frame) will need.

Run standalone, no Qt/app required:
    python Multi_Camera_Stream_Test.py
"""

import sys
import os
import time

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from Tbd.helper import CameraObject

CAM_INDICES = [1, 2, 3, 4, 5, 6]
TEST_DURATION_SECONDS = 15
WIDTH = 1920
HEIGHT = 1080


def main():
    cameras = []

    print("Opening cameras...")
    for index in CAM_INDICES:
        cam = CameraObject(capture=None, index=index)
        ok = cam.open(width=WIDTH, height=HEIGHT)
        print(f"cam{index}: {'opened' if ok else 'FAILED TO OPEN'}")
        if ok:
            cameras.append(cam)

    if not cameras:
        print("No cameras opened, aborting.")
        return

    print(f"\n{len(cameras)}/{len(CAM_INDICES)} cameras opened. Streaming for {TEST_DURATION_SECONDS}s...\n")

    successes = {cam.index: 0 for cam in cameras}
    failures = {cam.index: 0 for cam in cameras}

    start = time.time()
    while time.time() - start < TEST_DURATION_SECONDS:
        for cam in cameras:
            ok, frame = cam.capture.read()
            if ok and frame is not None:
                successes[cam.index] += 1
            else:
                failures[cam.index] += 1

    elapsed = time.time() - start

    print("=" * 50)
    print(f"Results after {elapsed:.1f}s:")
    for cam in cameras:
        total = successes[cam.index] + failures[cam.index]
        rate = successes[cam.index] / total * 100 if total else 0
        fps = successes[cam.index] / elapsed
        print(f"cam{cam.index}: {successes[cam.index]} ok / {failures[cam.index]} failed "
              f"({rate:.1f}% success, ~{fps:.1f} fps)")
    print("=" * 50)

    for cam in cameras:
        cam.close()


if __name__ == "__main__":
    main()
