#!/usr/bin/env python3
"""
Ultra-Simple Real-Time 3D Viewer
Bare minimum matplotlib with manual loop
"""

import re
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from collections import deque
import time

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

positions = deque(maxlen=500)
last_pos = 0
omega = 0
evol = 0
skip = 0

def read_log():
    global last_pos, omega, evol, skip
    try:
        with open(LOG_FILE, 'r', encoding='utf-8', errors='ignore') as f:
            f.seek(last_pos)
            lines = f.readlines()
            last_pos = f.tell()

            dims = {}
            for line in lines:
                if 'Ω:' in line:
                    try:
                        omega = float(line.split('Ω:')[1].split()[0])
                        evol = int(line.split('Evolution:')[1].split('│')[0].strip())
                    except:
                        pass

                for i in range(1, 9):
                    if f'  D{i}:' in line:
                        try:
                            dims[i-1] = float(line.split(':')[1].split('[')[0].strip())
                        except:
                            pass

                if len(dims) == 8:
                    skip += 1
                    if skip % 3 == 0:
                        positions.append(tuple(dims[i] for i in range(8)))
                    dims = {}
    except:
        pass

print("\n🎨 Ultra-Simple 3D Viewer")
print("=" * 50)

# Setup
plt.ion()
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
fig.patch.set_facecolor('#0a0a1a')
ax.set_facecolor('#050510')

plt.show(block=False)
plt.pause(0.1)

print("✅ Window created!")
print("   Monitoring data...\n")

frame = 0
azim = 0

try:
    while True:
        read_log()

        if len(positions) >= 10:
            # Process data
            arr = np.array(list(positions), dtype=np.float64)
            arr = np.log10(np.maximum(np.abs(arr), 1e-200))

            # Normalize
            for i in range(8):
                col = arr[:, i]
                if col.max() > col.min():
                    arr[:, i] = (col - col.min()) / (col.max() - col.min())

            # 3D projection
            x = arr[:, 0] * 0.6 + arr[:, 7] * 0.4
            y = arr[:, 2] * 0.5 + arr[:, 5] * 0.5
            z = arr[:, 4] * 0.5 + arr[:, 3] * 0.5

            # Clear and replot
            ax.clear()
            ax.set_facecolor('#050510')
            ax.set_xlim(0, 1)
            ax.set_ylim(0, 1)
            ax.set_zlim(0, 1)

            # Color gradient
            colors = plt.cm.plasma(np.linspace(0, 1, len(x)))
            ax.scatter(x, y, z, c=colors, s=5, alpha=0.8, edgecolors='none')

            # Labels
            ax.set_xlabel('X', color='cyan')
            ax.set_ylabel('Y', color='cyan')
            ax.set_zlabel('Z', color='cyan')
            ax.set_title(f'8D→3D | Ω={omega:.0f} | E={evol//1000000}M | {len(positions)}pts',
                        color='cyan', fontsize=10)
            ax.tick_params(colors='cyan', labelsize=7)

            # Rotate
            azim = (azim + 2) % 360
            ax.view_init(elev=20, azim=azim)

            # Update display
            plt.draw()
            plt.pause(0.001)

            if frame % 20 == 0:
                print(f"Frame {frame}: {len(positions)}pts | Ω={omega:.0f} | Az={azim}°")

        frame += 1
        time.sleep(0.2)

except KeyboardInterrupt:
    print("\n✅ Stopped")
    plt.close()
