import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import numpy as np

# Set style for better-looking plots
plt.style.use('default')
sns.set_palette("husl")

def load_and_plot_data():
    """Load the CSV data and create comprehensive plots"""
    
    # Load the data
    try:
        df = pd.read_csv('data/08072025_GliderFET001_noniso.csv')
        print(f"Data loaded successfully! Shape: {df.shape}")
        print(f"Columns: {list(df.columns)}")
        print(f"Data range: {df['DateTime'].min()} to {df['DateTime'].max()}")
        print(f"Number of measurements: {len(df)}")
    except FileNotFoundError:
        print("Error: Could not find the CSV file. Please check the path.")
        return
    except Exception as e:
        print(f"Error loading data: {e}")
        return
    
    # Convert DateTime to datetime object
    df['DateTime'] = pd.to_datetime(df['DateTime'])
    
    # Create a comprehensive figure with subplots
    fig, axes = plt.subplots(3, 2, figsize=(15, 12))
    fig.suptitle('GliderFET001 Non-ISO Sensor Data Analysis', fontsize=16, fontweight='bold')
    
    # Plot 1: Temperature over time
    axes[0, 0].plot(df['DateTime'], df['Temperature'], 'b-', linewidth=1, alpha=0.8)
    axes[0, 0].set_title('Temperature Over Time', fontweight='bold')
    axes[0, 0].set_ylabel('Temperature (°C)')
    axes[0, 0].grid(True, alpha=0.3)
    axes[0, 0].tick_params(axis='x', rotation=45)
    
    # Plot 2: Salinity over time
    axes[0, 1].plot(df['DateTime'], df['Salinity'], 'g-', linewidth=1, alpha=0.8)
    axes[0, 1].set_title('Salinity Over Time', fontweight='bold')
    axes[0, 1].set_ylabel('Salinity (PSU)')
    axes[0, 1].grid(True, alpha=0.3)
    axes[0, 1].tick_params(axis='x', rotation=45)
    
    # Plot 3: Vrse (Reference Electrode Voltage) over time
    axes[1, 0].plot(df['DateTime'], df['Vrse'], 'r-', linewidth=1, alpha=0.8)
    axes[1, 0].set_title('Vrse (Reference Electrode Voltage) Over Time', fontweight='bold')
    axes[1, 0].set_ylabel('Vrse (V)')
    axes[1, 0].grid(True, alpha=0.3)
    axes[1, 0].tick_params(axis='x', rotation=45)
    
    # Plot 4: Vk (Working Electrode Voltage) over time
    axes[1, 1].plot(df['DateTime'], df['Vk'], 'm-', linewidth=1, alpha=0.8)
    axes[1, 1].set_title('Vk (Working Electrode Voltage) Over Time', fontweight='bold')
    axes[1, 1].set_ylabel('Vk (V)')
    axes[1, 1].grid(True, alpha=0.3)
    axes[1, 1].tick_params(axis='x', rotation=45)
    
    # Plot 5: Current measurements (Ik and Ib) over time with dual y-axes
    ax5 = axes[2, 0]
    ax5_twin = ax5.twinx()
    
    # Plot Ik on left y-axis
    line1 = ax5.plot(df['DateTime'], df['Ik'], 'c-', linewidth=1, alpha=0.8, label='Ik (Working Current)')
    ax5.set_ylabel('Ik (Working Current) - nA', color='c')
    ax5.tick_params(axis='y', labelcolor='c')
    
    # Plot Ib on right y-axis
    line2 = ax5_twin.plot(df['DateTime'], df['Ib'], 'orange', linewidth=1, alpha=0.8, label='Ib (Bias Current)')
    ax5_twin.set_ylabel('Ib (Bias Current) - nA', color='orange')
    ax5_twin.tick_params(axis='y', labelcolor='orange')
    
    ax5.set_title('Current Measurements Over Time', fontweight='bold')
    ax5.grid(True, alpha=0.3)
    ax5.tick_params(axis='x', rotation=45)
    
    # Create combined legend
    lines = line1 + line2
    labels = [l.get_label() for l in lines]
    ax5.legend(lines, labels, loc='upper left')
    
    # Plot 6: VbiasPos (Bias Voltage) over time
    axes[2, 1].plot(df['DateTime'], df['VbiasPos'], 'purple', linewidth=1, alpha=0.8)
    axes[2, 1].set_title('VbiasPos (Bias Voltage) Over Time', fontweight='bold')
    axes[2, 1].set_ylabel('VbiasPos (V)')
    axes[2, 1].grid(True, alpha=0.3)
    axes[2, 1].tick_params(axis='x', rotation=45)
    
    # Adjust layout
    plt.tight_layout()
    
    # Save the plot
    plt.savefig('gliderfet_data_analysis.png', dpi=300, bbox_inches='tight')
    print("Plot saved as 'gliderfet_data_analysis.png'")
    
    # Show the plot
    plt.show()
    
    # Create additional analysis plots
    create_additional_plots(df)

def create_additional_plots(df):
    """Create additional analysis plots"""
    
    # Create a new figure for correlation and distribution analysis
    fig2, axes2 = plt.subplots(2, 2, figsize=(15, 10))
    fig2.suptitle('Additional Data Analysis', fontsize=16, fontweight='bold')
    
    # Plot 1: Temperature vs Salinity scatter plot
    axes2[0, 0].scatter(df['Temperature'], df['Salinity'], alpha=0.6, s=20)
    axes2[0, 0].set_xlabel('Temperature (°C)')
    axes2[0, 0].set_ylabel('Salinity (PSU)')
    axes2[0, 0].set_title('Temperature vs Salinity', fontweight='bold')
    axes2[0, 0].grid(True, alpha=0.3)
    
    # Plot 2: Vrse vs Vk scatter plot
    axes2[0, 1].scatter(df['Vrse'], df['Vk'], alpha=0.6, s=20)
    axes2[0, 1].set_xlabel('Vrse (V)')
    axes2[0, 1].set_ylabel('Vk (V)')
    axes2[0, 1].set_title('Vrse vs Vk', fontweight='bold')
    axes2[0, 1].grid(True, alpha=0.3)
    
    # Plot 3: Temperature distribution histogram
    axes2[1, 0].hist(df['Temperature'], bins=30, alpha=0.7, color='skyblue', edgecolor='black')
    axes2[1, 0].set_xlabel('Temperature (°C)')
    axes2[1, 0].set_ylabel('Frequency')
    axes2[1, 0].set_title('Temperature Distribution', fontweight='bold')
    axes2[1, 0].grid(True, alpha=0.3)
    
    # Plot 4: Salinity distribution histogram
    axes2[1, 1].hist(df['Salinity'], bins=30, alpha=0.7, color='lightgreen', edgecolor='black')
    axes2[1, 1].set_xlabel('Salinity (PSU)')
    axes2[1, 1].set_ylabel('Frequency')
    axes2[1, 1].set_title('Salinity Distribution', fontweight='bold')
    axes2[1, 1].grid(True, alpha=0.3)
    
    plt.tight_layout()
    
    # Save the additional plots
    plt.savefig('gliderfet_additional_analysis.png', dpi=300, bbox_inches='tight')
    print("Additional plots saved as 'gliderfet_additional_analysis.png'")
    
    # Show the additional plots
    plt.show()
    
    # Print summary statistics
    print_summary_statistics(df)

def print_summary_statistics(df):
    """Print summary statistics for the data"""
    
    print("\n" + "="*60)
    print("SUMMARY STATISTICS")
    print("="*60)
    
    # Basic statistics for numerical columns
    numerical_cols = ['Temperature', 'Salinity', 'VbiasPos', 'Vrse', 'Vk', 'Ik', 'Ib']
    
    for col in numerical_cols:
        if col in df.columns:
            print(f"\n{col}:")
            print(f"  Mean: {df[col].mean():.6f}")
            print(f"  Std:  {df[col].std():.6f}")
            print(f"  Min:  {df[col].min():.6f}")
            print(f"  Max:  {df[col].max():.6f}")
    
    # Time range information
    print(f"\nTime Range:")
    print(f"  Start: {df['DateTime'].min()}")
    print(f"  End:   {df['DateTime'].max()}")
    print(f"  Duration: {df['DateTime'].max() - df['DateTime'].min()}")
    
    # Data quality information
    print(f"\nData Quality:")
    print(f"  Total measurements: {len(df)}")
    print(f"  Missing values: {df.isnull().sum().sum()}")
    
    # Calculate measurement frequency
    time_diff = df['DateTime'].diff().dropna()
    avg_interval = time_diff.mean()
    print(f"  Average measurement interval: {avg_interval}")

if __name__ == "__main__":
    # Run the main analysis
    load_and_plot_data()
