# HDGL Spiral10000 Visualizer
# Simple visualization script for the generated spiral field

import json
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

def load_spiral_data(filename="hdgl_spiral10000.json"):
    """Load the generated spiral field data"""
    with open(filename, 'r') as f:
        data = json.load(f)
    return data

def create_static_plot(data):
    """Create a static plot of the spiral field"""
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12))

    # Extract spiral data
    spiral_data = data['spiral_data']
    x_coords = [p['x'] for p in spiral_data]
    y_coords = [p['y'] for p in spiral_data]
    energies = [p['energy'] for p in spiral_data]
    phases = [p['phase'] for p in spiral_data]

    # Plot 1: Basic spiral pattern
    scatter1 = ax1.scatter(x_coords, y_coords, c=energies, cmap='viridis', s=1, alpha=0.7)
    ax1.set_title('HDGL Quantum Spiral (Energy)')
    ax1.set_xlabel('X Coordinate')
    ax1.set_ylabel('Y Coordinate')
    ax1.axis('equal')
    plt.colorbar(scatter1, ax=ax1, label='Energy')

    # Plot 2: Phase visualization
    scatter2 = ax2.scatter(x_coords, y_coords, c=phases, cmap='hsv', s=1, alpha=0.7)
    ax2.set_title('HDGL Quantum Spiral (Phase)')
    ax2.set_xlabel('X Coordinate')
    ax2.set_ylabel('Y Coordinate')
    ax2.axis('equal')
    plt.colorbar(scatter2, ax=ax2, label='Phase (radians)')

    # Plot 3: Energy distribution
    ax3.hist(energies, bins=50, alpha=0.7, color='blue', edgecolor='black')
    ax3.set_title('Energy Distribution')
    ax3.set_xlabel('Energy')
    ax3.set_ylabel('Frequency')
    ax3.axvline(np.mean(energies), color='red', linestyle='--', label=f'Mean: {np.mean(energies):.3f}')
    ax3.legend()

    # Plot 4: Ternary state distribution
    ternary_states = [p['ternary'] for p in spiral_data]
    unique_states, counts = np.unique(ternary_states, return_counts=True)
    ax4.bar(unique_states, counts, alpha=0.7, color=['red', 'gray', 'blue'], edgecolor='black')
    ax4.set_title('HDGL Ternary State Distribution')
    ax4.set_xlabel('Ternary State (-1, 0, 1)')
    ax4.set_ylabel('Count')
    ax4.set_xticks([-1, 0, 1])

    plt.tight_layout()
    plt.savefig('hdgl_spiral_visualization.png', dpi=300, bbox_inches='tight')
    # plt.show()  # Commented out for headless environment

def create_animation(data, frames=100):
    """Create an animated visualization showing evolution over time"""
    fig, ax = plt.subplots(figsize=(10, 10))

    spiral_data = data['spiral_data']
    x_coords = [p['x'] for p in spiral_data]
    y_coords = [p['y'] for p in spiral_data]
    energies = [p['energy'] for p in spiral_data]

    # Create scatter plot
    scatter = ax.scatter([], [], c=[], cmap='viridis', s=1, alpha=0.7, vmin=min(energies), vmax=max(energies))

    def init():
        scatter.set_offsets(np.empty((0, 2)))
        scatter.set_array(np.array([]))
        return scatter,

    def animate(frame):
        # Show progressive points
        n_points = int(len(spiral_data) * (frame + 1) / frames)
        current_x = x_coords[:n_points]
        current_y = y_coords[:n_points]
        current_energies = energies[:n_points]

        scatter.set_offsets(np.column_stack([current_x, current_y]))
        scatter.set_array(np.array(current_energies))

        ax.set_title(f'HDGL Quantum Spiral Evolution - Frame {frame+1}/{frames} ({n_points} points)')
        ax.set_xlabel('X Coordinate')
        ax.set_ylabel('Y Coordinate')
        ax.axis('equal')

        return scatter,

    anim = FuncAnimation(fig, animate, init_func=init, frames=frames, interval=100, blit=True)
    anim.save('hdgl_spiral_evolution.gif', writer='pillow', fps=10, dpi=100)
    # plt.show()  # Commented out for headless environment

def main():
    """Main visualization function"""
    print("🌟 HDGL Spiral10000 Visualizer 🌟")
    print("=" * 40)

    # Load data
    print("Loading spiral field data...")
    data = load_spiral_data()

    # Display statistics
    stats = data['statistics']
    print(f"Total Points: {stats['total_points']:,}")
    print(f"Max Energy: {stats['energy_stats']['max']:.3f}")
    print(f"Final Radius: {stats['radius_stats']['final_radius']:.1f}")
    print(f"Golden Ratio φ: {stats['golden_ratio']:.6f}")
    print()

    # Create visualizations
    print("Creating static plot...")
    create_static_plot(data)

    print("Creating evolution animation...")
    create_animation(data, frames=50)

    print("✓ Visualization complete!")
    print("Files saved: hdgl_spiral_visualization.png, hdgl_spiral_evolution.gif")

if __name__ == "__main__":
    main()