import pygame
import json
import os
import colorsys

POOL_FILE = "qrng_pool.json"

def load_entropy_pool():
    if not os.path.exists(POOL_FILE):
        print("⚠️ No entropy pool found!")
        return []
    with open(POOL_FILE, 'r') as f:
        data = json.load(f)
        return data.get('pool', [])

def run():
    pool = load_entropy_pool()
    if not pool:
        return

    pygame.init()
    WIDTH, HEIGHT = 800, 600
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
    pygame.display.set_caption("Quantum Waveform Visualizer")

    clock = pygame.time.Clock()
    pool_index = 0
    hue_offset = 0.0  # For color cycling

    running = True
    while running:
        screen.fill((0, 0, 0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.VIDEORESIZE:
                WIDTH, HEIGHT = event.size
                screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_f:
                    pygame.display.toggle_fullscreen()

        # Calculate points across the screen
        step = 5  # pixels between points (finer resolution)
        points = []
        baseline = HEIGHT // 2
        for x in range(0, WIDTH, step):
            value = pool[pool_index % len(pool)]
            amplitude = int((value / 255) * (HEIGHT // 3))  # Keep waves within bounds
            y = baseline + amplitude - (HEIGHT // 6)
            points.append((x, y))
            pool_index += 1

        # Color cycling
        hue = hue_offset % 1.0
        r, g, b = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
        color = (int(r * 255), int(g * 255), int(b * 255))

        # Draw lines between points
        if len(points) > 1:
            pygame.draw.aalines(screen, color, False, points)

        pygame.display.flip()
        clock.tick(30)

        # Cycle hue
        hue_offset += 0.002

    pygame.quit()
