import time
import random
import json
import os
import numpy as np
import sounddevice as sd

POOL_FILE = "qrng_pool.json"
SAMPLE_RATE = 44100  # Standard audio sample rate

# Define frequencies for bell tones (C major pentatonic scale)
BELL_FREQUENCIES = [261.63, 293.66, 329.63, 392.00, 440.00, 523.25]  # C4, D4, E4, G4, A4, C5

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 generate_bell_tone(frequency, duration=1.0, amplitude=0.5):
    t = np.linspace(0, duration, int(SAMPLE_RATE * duration), False)
    # Create a decaying sine wave (envelope for bell-like effect)
    envelope = np.exp(-3 * t)  # Fast decay for bell
    wave = amplitude * np.sin(2 * np.pi * frequency * t) * envelope
    return wave.astype(np.float32)

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

    pool_index = 0
    print("🔔 Quantum Bells Activated. Press Ctrl+C to stop.")
    try:
        while True:
            # Select bell frequency from entropy
            freq_idx = pool[pool_index % len(pool)] % len(BELL_FREQUENCIES)
            frequency = BELL_FREQUENCIES[freq_idx]
            pool_index += 1

            # Select delay time (0.5s to 3s)
            delay_entropy = pool[pool_index % len(pool)]
            delay = 0.5 + (delay_entropy / 255) * 2.5  # 0.5 - 3.0 seconds
            pool_index += 1

            # Select amplitude (0.3 - 0.8)
            amp_entropy = pool[pool_index % len(pool)]
            amplitude = 0.3 + (amp_entropy / 255) * 0.5
            pool_index += 1

            # Generate and play bell tone
            bell_wave = generate_bell_tone(frequency, duration=1.5, amplitude=amplitude)
            sd.play(bell_wave, samplerate=SAMPLE_RATE)

            print(f"🔔 Bell: {frequency:.2f} Hz | Amplitude: {amplitude:.2f} | Next in {delay:.2f}s")

            time.sleep(delay)
    except KeyboardInterrupt:
        print("\n🛑 Quantum Bells stopped.")

def run():
    quantum_bells_loop()        

if __name__ == "__main__":
    quantum_bells_loop()
