"""
Synchronous usage example for uniWeather Python client
"""

from uniWeather import uniWeatherCloudSync
from datetime import datetime, timedelta


def main():
    # Use context manager for automatic cleanup
    with uniWeatherCloudSync(base_url="http://localhost:8080") as client:
        # Connect
        print("Connecting to uniWeather API...")
        client.connect(token="your-api-key-here")
        print("Connected successfully!")
        
        # Get devices
        print("\nFetching devices...")
        devices = client.my_devices()
        print(f"Found {len(devices)} devices")
        
        for device in devices:
            print(f"  - {device.device_id}")
        
        if not devices:
            print("No devices found.")
            return
        
        # Get data for first device
        device = devices[0]
        print(f"\nQuerying data for: {device.device_id}")
        
        # Last 24 hours
        end_date = datetime.now()
        start_date = end_date - timedelta(days=1)
        
        data = client.data(
            device=device,
            channels="all",
            from_date=start_date,
            to_date=end_date
        )
        
        print(f"\nReceived {len(data.channels)} channels")
        
        for channel in data.channels:
            print(f"  {channel.key}: {len(channel.entries)} entries")
        
        # Convert to DataFrame and save
        try:
            df = data.to_dataframe()
            print(f"\nDataFrame: {df.shape[0]} rows, {df.shape[1]} columns")
            
            # Save to CSV
            csv_file = f"{device.device_id}_last24h.csv"
            df.to_csv(csv_file)
            print(f"Saved to: {csv_file}")
            
        except ImportError:
            print("\nInstall pandas for DataFrame support: pip install pandas")


if __name__ == "__main__":
    main()

