#!/bin/bash

# Script to visualize autoclicker log files
# Starts Python server and opens the HTML visualization tool

VISUALIZER_FILE="click-visualizer.html"
LOG_DIR="/tmp/autoclicker_logs"
SERVER_SCRIPT="click_server.py"
SERVER_PORT=8661

# Check if visualization file exists
if [ ! -f "$VISUALIZER_FILE" ]; then
    echo "Error: Visualization tool not found at $VISUALIZER_FILE"
    exit 1
fi

# Check if server script exists
if [ ! -f "$SERVER_SCRIPT" ]; then
    echo "Error: Server script not found at $SERVER_SCRIPT"
    exit 1
fi

# Check if Python is available
if ! command -v python3 &> /dev/null; then
    echo "Error: Python 3 is not installed. Install it with: sudo pacman -S python"
    exit 1
fi

# Check if we have any log files
if [ ! -d "$LOG_DIR" ] || [ -z "$(ls -A "$LOG_DIR")" ]; then
    echo "No autoclicker log files found in $LOG_DIR"
    echo "Run the enhanced autoclicker first to generate data."
    echo ""
    echo "Starting server anyway (you can generate logs while it's running)..."
fi

echo "Starting autoclicker visualization server..."
echo "Server will be available at: http://localhost:$SERVER_PORT"
echo "Log directory: $LOG_DIR"
echo ""

# Start the Python server in the background
python3 "$SERVER_SCRIPT" &
SERVER_PID=$!

# Give the server a moment to start
sleep 2

# Check if server started successfully
if ! ps -p $SERVER_PID > /dev/null; then
    echo "Error: Failed to start server"
    exit 1
fi

# Open browser
if command -v xdg-open &> /dev/null; then
    xdg-open "http://localhost:$SERVER_PORT"
elif command -v open &> /dev/null; then
    open "http://localhost:$SERVER_PORT"
else
    echo "Server started successfully!"
    echo "Open your browser and navigate to: http://localhost:$SERVER_PORT"
fi

echo ""
echo "Server is running in the background (PID: $SERVER_PID)"
echo "Press Ctrl+C to stop the server when you're done"
echo ""

# Wait for server to finish (it will run until manually stopped)
wait $SERVER_PID