"""
Example: Data analysis with pandas and matplotlib
"""

import asyncio
from datetime import datetime, timedelta
from uniWeather import uniWeatherCloud


async def main():
    # Initialize client
    client = uniWeatherCloud(base_url="http://localhost:8080")
    await client.connect(token="your-api-key-here")
    
    # Get first device
    devices = await client.my_devices()
    if not devices:
        print("No devices found")
        return
    
    device = devices[0]
    print(f"Analyzing data from: {device.device_id}")
    
    # Get last 30 days of data
    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)
    
    print(f"Fetching data from {start_date.date()} to {end_date.date()}...")
    
    data = await client.data(
        device=device,
        channels="all",
        from_date=start_date,
        to_date=end_date
    )
    
    # Convert to DataFrame
    try:
        import pandas as pd
        import matplotlib.pyplot as plt
    except ImportError:
        print("This example requires pandas and matplotlib")
        print("Install with: pip install pandas matplotlib")
        return
    
    df = data.to_dataframe()
    print(f"\nDataFrame shape: {df.shape}")
    print(f"Columns: {', '.join(df.columns)}")
    
    # Basic statistics
    print("\n" + "="*50)
    print("SUMMARY STATISTICS")
    print("="*50)
    print(df.describe())
    
    # Plot time series
    print("\nGenerating plots...")
    
    fig, axes = plt.subplots(len(df.columns), 1, figsize=(12, 3*len(df.columns)))
    
    if len(df.columns) == 1:
        axes = [axes]
    
    for ax, column in zip(axes, df.columns):
        df[column].plot(ax=ax, title=f"{column} over time")
        ax.set_ylabel(column)
        ax.grid(True, alpha=0.3)
    
    plt.tight_layout()
    
    # Save plot
    plot_file = f"{device.device_id}_analysis.png"
    plt.savefig(plot_file, dpi=150)
    print(f"Plot saved to: {plot_file}")
    
    # Show plot
    plt.show()
    
    # Export to Excel (if openpyxl is installed)
    try:
        excel_file = f"{device.device_id}_data.xlsx"
        df.to_excel(excel_file)
        print(f"Excel file saved to: {excel_file}")
    except ImportError:
        print("\nInstall openpyxl for Excel export: pip install openpyxl")
    
    await client.close()


if __name__ == "__main__":
    asyncio.run(main())

