"""
Basic usage example for uniWeather Python client
"""

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


async def main():
    # Initialize the client
    client = uniWeatherCloud(base_url="http://localhost:8080")
    
    # Connect with your API token
    print("Connecting to uniWeather API...")
    await client.connect(token="your-api-key-here")
    print("Connected successfully!")
    
    # Get assigned devices
    print("\nFetching assigned devices...")
    devices = await client.my_devices()
    print(f"Found {len(devices)} assigned device(s)")
    
    # If no assigned devices, try getting all devices (including unhandled)
    if not devices:
        print("No assigned devices. Checking all devices (including unhandled)...")
        devices = await client.my_devices(all=True)
        print(f"Found {len(devices)} total device(s)")
    
    for device in devices:
        print(f"\nDevice: {device.device_id}")
        
        # Get available channels for this device
        channels = await client.get_channels(device)
        print(f"  Channels: {', '.join(channels)}")
    
    if not devices:
        print("\nNo devices found. Make sure your API key has device access.")
        await client.close()
        return
    
    # Query data for the first device
    device = devices[0]
    print(f"\n\nQuerying data for device: {device.device_id}")
    
    # Get data for the last 7 days
    end_date = datetime.now()
    start_date = end_date - timedelta(days=7)
    
    print(f"Time range: {start_date.date()} to {end_date.date()}")
    
    data = await client.data(
        device=device,
        channels="all",
        from_date=start_date,
        to_date=end_date
    )
    
    print(f"\nReceived data:")
    print(f"  Device: {data.device_id}")
    print(f"  Channels: {len(data.channels)}")
    print(f"  Channel names: {', '.join(data.channels)}")
    print(f"  Time range: {datetime.fromtimestamp(data.start_time)} to {datetime.fromtimestamp(data.end_time)}")
    
    # Convert to pandas DataFrame (if pandas is installed)
    try:
        print("\nConverting to pandas DataFrame...")
        df = data.to_dataframe()
        print(df.head())
        print(f"\nDataFrame shape: {df.shape}")
    except ImportError:
        print("\nPandas not installed. Install with: pip install pandas")
    
    # Download as CSV
    csv_filename = f"{device.device_id}_data.csv"
    print(f"\nDownloading CSV to: {csv_filename}")
    await client.download_csv(
        device=device,
        filename=csv_filename,
        from_date=start_date,
        to_date=end_date
    )
    print("CSV download complete!")
    
    # Close connection
    await client.close()
    print("\nConnection closed.")


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

