#!/usr/bin/env python3
import json
import time
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from collections import deque

# Path to your log file
LOG_FILE = 'ga_viewers.log'
# How many points of history to keep per streamer
MAX_POINTS = 60

# Open the log file and seek to the end
f = open(LOG_FILE, 'r')
f.seek(0, 2)

# histories: streamer → deque of viewerCounts
histories = {}
# timestamps for the x‐axis (shared length)
timestamps = deque(maxlen=MAX_POINTS)

def update(frame):
    """Read new log lines, update histories, and redraw the plot."""
    global histories, timestamps

    # Read all new lines
    while True:
        line = f.readline()
        if not line:
            break
        try:
            # Each line is like: [2025-05-14 23:54:31] {"streamer1": {...}, ...}
            _, blob = line.split('] ', 1)
            data = json.loads(blob)
        except Exception:
            continue

        # Record a timestamp for this batch of updates
        timestamps.append(time.strftime('%H:%M:%S'))

        # Update each streamer's history
        for streamer, info in data.items():
            cnt = info.get('viewerCount', 0)
            if streamer not in histories:
                histories[streamer] = deque(maxlen=MAX_POINTS)
            histories[streamer].append(cnt)

        # Make sure every existing streamer has an entry for this time step
        for streamer, dq in histories.items():
            if len(dq) < len(timestamps):
                # pad with last known value (or zero)
                dq.append(dq[-1] if dq else 0)

    # Redraw
    ax.clear()
    for streamer, dq in histories.items():
        ax.plot(list(range(-len(dq)+1, 1)), dq, label=streamer)
    ax.set_title('Live Viewer Counts')
    ax.set_xlabel('Samples (newest at 0)')
    ax.set_ylabel('Viewer Count')
    ax.legend(loc='upper left', fontsize='small', ncol=2)
    plt.tight_layout()

# Set up the figure
fig, ax = plt.subplots()
# Animate: call update() every second
ani = FuncAnimation(fig, update, interval=1000)

# Show the live‐updating chart
#plt.show()
plt.tight_layout()
plt.savefig('live_viewers.png')
plt.clf()         # clear the figure for the next cycle
print("Wrote live_viewers.png")
