#!/usr/bin/env python3
"""
Ultra-Simple 2D Chromatic Visualization
Guaranteed to show up and be fast!
"""

import re
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from collections import deque

LOG_FILE = "../logs/peer1.log"

class SimpleMonitor:
    def __init__(self):
        self.x_data = deque(maxlen=500)
        self.y_data = deque(maxlen=500)
        self.z_data = deque(maxlen=500)
        self.last_pos = 0
        self.omega = 0
        self.evol = 0

    def update(self):
        try:
            with open(LOG_FILE, 'r', encoding='utf-8', errors='ignore') as f:
                f.seek(self.last_pos)
                lines = f.readlines()
                self.last_pos = f.tell()

                d1, d2, d3 = None, None, None
                for line in lines:
                    if 'Ω:' in line:
                        try:
                            self.omega = float(line.split('Ω:')[1].split()[0])
                            self.evol = int(line.split('Evolution:')[1].split('│')[0].strip())
                        except:
                            pass

                    if '  D1:' in line:
                        try:
                            d1 = float(line.split(':')[1].split('[')[0].strip())
                        except:
                            pass
                    elif '  D2:' in line:
                        try:
                            d2 = float(line.split(':')[1].split('[')[0].strip())
                        except:
                            pass
                    elif '  D3:' in line:
                        try:
                            d3 = float(line.split(':')[1].split('[')[0].strip())
                        except:
                            pass

                    if d1 and d2 and d3:
                        self.x_data.append(np.log10(abs(d1) + 1e-50))
                        self.y_data.append(np.log10(abs(d2) + 1e-50))
                        self.z_data.append(np.log10(abs(d3) + 1e-50))
                        d1, d2, d3 = None, None, None
        except:
            pass

def animate(frame, monitor, scatter, ax, text):
    monitor.update()

    if len(monitor.x_data) < 2:
        return scatter, text

    x = np.array(monitor.x_data)
    y = np.array(monitor.y_data)

    # Normalize to 0-1
    x = (x - x.min()) / (x.max() - x.min() + 1e-10)
    y = (y - y.min()) / (y.max() - y.min() + 1e-10)

    # Color by age
    colors = np.linspace(0, 1, len(x))

    scatter.set_offsets(np.c_[x, y])
    scatter.set_array(colors)

    ax.set_title(f'D1 vs D2 Phase Space | Ω={monitor.omega:.0f} | E={monitor.evol//1000000}M',
                 color='cyan', fontsize=12)

    return scatter, text

def main():
    print("🎨 Simple 2D Chromatic Visualization")
    print("   Phase space: D1 vs D2")
    print("   Window should appear NOW!\n")

    monitor = SimpleMonitor()

    # Create simple 2D plot
    fig, ax = plt.subplots(figsize=(10, 10))
    fig.patch.set_facecolor('#050510')
    ax.set_facecolor('#0a0a1a')

    ax.set_xlabel('D1 (Fundamental)', color='white', fontsize=11)
    ax.set_ylabel('D2 (Major 2nd)', color='white', fontsize=11)
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.grid(True, alpha=0.2, color='cyan')
    ax.tick_params(colors='cyan')

    # Single scatter plot
    scatter = ax.scatter([], [], c=[], cmap='plasma', s=5, alpha=0.7)

    text = ax.text(0.02, 0.98, "", transform=ax.transAxes, color='cyan',
                   va='top', fontsize=9)

    # Animate
    ani = FuncAnimation(fig, animate,
                       fargs=(monitor, scatter, ax, text),
                       interval=300,
                       blit=False,
                       cache_frame_data=False)

    print("✅ Window created! If you don't see it, check taskbar or Alt+Tab")
    plt.show()

if __name__ == "__main__":
    main()
