"""
Simple example script demonstrating how to use the new modular structure.

This script shows how to:
1. Load data for a specific ball type and height
2. Detect bounces and calculate COR
3. Create static and animated visualizations
"""

import os
import sys
import matplotlib.pyplot as plt

# Add the src directory to the Python path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# Import modules from the project
from data.loader import load_trial, GOLF_BALL_PATHS
from analysis.bounce_detection import process_trial
from visualization.static_plots import plot_trial_with_bounces
from visualization.animation import create_ball_animation_with_model, save_animation


def main():
    """
    Main function to demonstrate the use of the modular structure.
    """
    print("Simple Bouncing Ball Analysis Example")
    print("====================================")
    
    # Create output directory
    output_dir = "output"
    os.makedirs(output_dir, exist_ok=True)
    
    # Select a specific ball and height
    ball_type = "Golf"
    height = "11 inches"
    file_path = GOLF_BALL_PATHS[height]
    
    print(f"Analyzing {ball_type} ball from {height}...")
    
    # Load the trial data
    df = load_trial(file_path)
    print(f"Loaded data with {len(df)} rows")
    
    # Process the trial to detect bounces and calculate COR
    result = process_trial(
        df, 
        initial_height=float(height.split()[0]),
        ball_type=ball_type
    )
    
    # Print the results
    print("\nAnalysis Results:")
    print(f"Number of bounces detected: {len(result['peak_indices'])}")
    print(f"Average COR: {result['Average COR']:.4f}")
    print(f"Initial height: {result['Initial Height']} inches")
    
    # Create a static plot with detected bounces
    print("\nCreating static plot...")
    plot_trial_with_bounces(
        df, 
        result['peak_indices'], 
        df['Position'].values,
        height, 
        ball_type,
        initial_height=float(height.split()[0]),
        cor=result['Average COR']
    )
    
    # Save the static plot
    plt.savefig(os.path.join(output_dir, f"{ball_type.lower()}_{height.split()[0]}_bounces.png"))
    plt.close()
    
    # Create an animation
    print("\nCreating animation...")
    anim = create_ball_animation_with_model(
        df, 
        result['peak_indices'], 
        result['Average COR'], 
        float(height.split()[0]),
        title=f"{ball_type} Ball - {height}"
    )
    
    # Save the animation
    animation_path = os.path.join(output_dir, f"{ball_type.lower()}_{height.split()[0]}_animation.mp4")
    save_animation(anim, animation_path)
    print(f"Animation saved to {animation_path}")
    
    print("\nAnalysis complete! Results saved to the 'output' directory.")


if __name__ == "__main__":
    main() 