import pygame
import math
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 Wave Visualizer")

    clock = pygame.time.Clock()
    pool_index = 0
    phase = 0.0  # Controls horizontal shifting
    hue_offset = 0.0

    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)

        # Entropy-driven amplitude and frequency
        amplitude = 50 + (pool[pool_index % len(pool)] / 255) * 100
        frequency = 0.01 + (pool[(pool_index + 1) % len(pool)] / 255) * 0.05
        hue = (hue_offset + (pool_index / len(pool))) % 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 sine wave
        prev_x, prev_y = 0, HEIGHT // 2
        for x in range(1, WIDTH):
            y = int(HEIGHT // 2 + amplitude * math.sin(frequency * x + phase))
            pygame.draw.line(screen, color, (prev_x, prev_y), (x, y), 2)
            prev_x, prev_y = x, y

        pygame.display.flip()
        clock.tick(60)
        phase += 0.05  # Smoothly shift phase for wave motion
        pool_index += 1
        hue_offset += 0.001

    pygame.quit()
