#!/usr/bin/env python3
"""
Non-Blocking 2D Chromatic Visualization
Uses interactive mode for immediate window display
"""

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

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

class Monitor:
    def __init__(self):
        self.x_data = deque(maxlen=500)
        self.y_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 = 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

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

def main():
    print("\n" + "="*60)
    print("  🎨 LIVE 2D CHROMATIC VISUALIZATION")
    print("  Phase Space: D1 vs D2")
    print("="*60 + "\n")

    monitor = Monitor()

    # Enable interactive mode - window appears immediately!
    plt.ion()

    # Create figure
    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')

    scatter = ax.scatter([], [], c=[], cmap='plasma', s=5, alpha=0.7, vmin=0, vmax=1)

    # Show window immediately
    plt.show(block=False)
    plt.pause(0.1)

    print("✅ Window should be visible now!")
    print("   Press Ctrl+C to stop\n")

    frame = 0
    try:
        while True:
            monitor.update()

            if len(monitor.x_data) >= 2:
                x = np.array(monitor.x_data)
                y = np.array(monitor.y_data)

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

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

                # Update plot
                scatter.set_offsets(np.c_[x_norm, y_norm])
                scatter.set_array(colors)

                # Update title
                omega_icon = "🔴" if monitor.omega >= 999 else "🟢"
                ax.set_title(f'{omega_icon} D1 vs D2 Phase Space | Ω={monitor.omega:.0f} | E={monitor.evol//1000000}M | Pts={len(monitor.x_data)}',
                            color='cyan', fontsize=12)

                # Redraw
                fig.canvas.draw_idle()
                fig.canvas.flush_events()

            # Update every 0.3 seconds
            time.sleep(0.3)
            frame += 1

            # Print status every 10 frames
            if frame % 10 == 0:
                print(f"Frame {frame}: {len(monitor.x_data)} points, Ω={monitor.omega:.0f}, E={monitor.evol//1000000}M")

    except KeyboardInterrupt:
        print("\n\n✅ Visualization stopped by user.")
        plt.close()

if __name__ == "__main__":
    main()
