#!/usr/bin/env python3
"""
Test script to check shared memory connection and read frames
"""

from shared_memory_reader import SharedMemoryFrameReader
import time

def main():
    print("=" * 50)
    print("Shared Memory Frame Buffer Test")
    print("=" * 50)
    print()

    try:
        print("1. Connecting to shared memory...")
        reader = SharedMemoryFrameReader()
        print("   ✓ Connected successfully!")
        print()

        print("2. Reading frames for 10 seconds...")
        print("   (Press Ctrl+C to stop early)")
        print()

        start_time = time.time()
        frame_count = 0
        last_frame_num = -1

        while time.time() - start_time < 10:
            result = reader.read_frame()

            if result:
                header, jpeg_data = result

                if header.frame_number != last_frame_num:
                    frame_count += 1
                    last_frame_num = header.frame_number

                    print(f"   Frame #{header.frame_number}:")
                    print(f"     Size: {len(jpeg_data)} bytes ({len(jpeg_data)/1024:.1f} KB)")
                    print(f"     Resolution: {header.width}x{header.height}")
                    print(f"     Timestamp: {header.timestamp_us} µs")
                    print()

                    time.sleep(0.1)  # Don't spam console
            else:
                print("   No frame available, waiting...")
                time.sleep(0.5)

        print("=" * 50)
        print(f"Test complete! Received {frame_count} frames in 10 seconds")
        print(f"Average FPS: {frame_count / 10:.1f}")
        print("=" * 50)

        reader.close()

    except KeyboardInterrupt:
        print("\n\nStopped by user")
    except Exception as e:
        print(f"\n✗ Error: {e}")
        print()
        print("Troubleshooting:")
        print("1. Is beacon_track running?")
        print("   cd beacon_track/build && ./main realtime output.txt")
        print()
        print("2. Is EnableFrameBuffer=true in config.ini?")
        print()
        print("3. Check beacon_track logs for 'Shared memory frame buffer initialized'")
        return 1

    return 0

if __name__ == '__main__':
    exit(main())
