#!/usr/bin/env python3
"""
Simple runner script for Ray Training Metrics Visualizer

Usage examples:
    # Interactive Streamlit dashboard
    python run_metrics_viz.py /path/to/metrics.csv
    
    # Generate HTML plots
    python run_metrics_viz.py /path/to/metrics.csv --html
    
    # Generate HTML plots with running average (window size 10)
    python run_metrics_viz.py /path/to/metrics.csv --html --window-size 10
    
    # Print summary only
    python run_metrics_viz.py /path/to/metrics.csv --summary
    
    # Use with your specific file
    python run_metrics_viz.py ../../examples/custom_calc_x/logs/custom_calc_x_ray_metrics.csv
"""

import os
import sys
import subprocess
from pathlib import Path

def main():
    # Default CSV file if none provided
    default_csv = "../../examples/custom_calc_x/logs/custom_calc_x_ray_metrics.csv"
    
    if len(sys.argv) < 2:
        if os.path.exists(default_csv):
            csv_file = default_csv
            print(f"No CSV file specified, using default: {csv_file}")
        else:
            print("Usage: python run_metrics_viz.py <csv_file> [--html|--summary] [--window-size N]")
            print(f"Example: python run_metrics_viz.py {default_csv}")
            print("Example with running average: python run_metrics_viz.py <csv_file> --html --window-size 10")
            sys.exit(1)
    else:
        csv_file = sys.argv[1]
    
    # Check if file exists
    if not os.path.exists(csv_file):
        print(f"Error: CSV file not found: {csv_file}")
        sys.exit(1)
    
    # Determine mode and extract window_size
    mode = "streamlit"  # default
    window_size = None
    
    if "--html" in sys.argv:
        mode = "html"
    elif "--summary" in sys.argv:
        mode = "summary"
    
    # Extract window_size if provided
    for i, arg in enumerate(sys.argv):
        if arg == "--window-size" and i + 1 < len(sys.argv):
            try:
                window_size = int(sys.argv[i + 1])
            except ValueError:
                print("Error: window-size must be an integer")
                sys.exit(1)
    
    # Get the directory of this script
    script_dir = Path(__file__).parent
    visualizer_script = script_dir / "metrics_visualizer.py"
    
    if mode == "streamlit":
        print("🚀 Launching Streamlit dashboard...")
        print("📊 Your browser should open automatically")
        print("🌐 If not, go to: http://localhost:8501")
        print("\nPress Ctrl+C to stop the dashboard")
        
        # Run streamlit
        cmd = [
            sys.executable, "-m", "streamlit", "run", 
            str(visualizer_script), "--", 
            csv_file, "--mode", "streamlit"
        ]
        subprocess.run(cmd)
        
    elif mode == "html":
        print("📈 Generating HTML plots...")
        cmd = [
            sys.executable, str(visualizer_script),
            csv_file, "--mode", "html"
        ]
        if window_size:
            cmd.extend(["--window-size", str(window_size)])
            print(f"📊 Using running average window size: {window_size}")
        subprocess.run(cmd)
        
    elif mode == "summary":
        print("📋 Generating metrics summary...")
        cmd = [
            sys.executable, str(visualizer_script),
            csv_file, "--mode", "summary"
        ]
        subprocess.run(cmd)

if __name__ == "__main__":
    main() 