"""
Example: Batch download data from multiple devices
"""

import asyncio
from datetime import datetime
from uniWeather import uniWeatherCloud


async def download_device_data(client: uniWeatherCloud, device, start_date: str, end_date: str, output_dir: str = "."):
    """Download data for a single device"""
    try:
        print(f"Downloading data for {device.device_id}...")
        
        filename = f"{output_dir}/{device.device_id}_{start_date}_to_{end_date}.csv"
        
        await client.download_csv(
            device=device,
            filename=filename,
            channels="all",
            from_date=start_date,
            to_date=end_date
        )
        
        print(f"  Downloaded: {filename}")
        return True
        
    except Exception as e:
        print(f"  Error downloading {device.device_id}: {e}")
        return False


async def main():
    # Configuration
    BASE_URL = "http://localhost:8080"
    API_TOKEN = "your-api-key-here"
    START_DATE = "2025-05-01"
    END_DATE = "2025-05-31"
    OUTPUT_DIR = "./weather_data"
    
    # Create output directory
    import os
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    # Initialize client
    client = uniWeatherCloud(base_url=BASE_URL)
    await client.connect(token=API_TOKEN)
    
    print("Fetching devices...")
    devices = await client.my_devices()
    print(f"Found {len(devices)} devices\n")
    
    # Download data for all devices in parallel
    tasks = [
        download_device_data(client, device, START_DATE, END_DATE, OUTPUT_DIR)
        for device in devices
    ]
    
    results = await asyncio.gather(*tasks)
    
    # Summary
    successful = sum(results)
    print(f"\n{'='*50}")
    print(f"Download complete!")
    print(f"Successful: {successful}/{len(devices)}")
    print(f"Output directory: {OUTPUT_DIR}")
    
    await client.close()


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

