"""Telemetry query example.

This example demonstrates how to:
1. Query telemetry data with filters
2. Get latest telemetry points
3. Aggregate data over time
4. Downsample data for visualization
"""

import asyncio
from datetime import datetime, UTC, timedelta
from uuid import UUID

from fishinfo import (
    FishinfoClient,
    DataType,
    AggregationType,
    OrderDirection,
)
from fishinfo.api import TelemetryApi


async def main():
    """Run telemetry query example."""
    # Configure client
    async with FishinfoClient(
        base_url="https://fishinfo.example.com",
        api_key="vk_live_test123",
    ) as client:
        # Create telemetry API client
        telemetry = TelemetryApi(client)

        vessel_id = UUID("550e8400-e29b-41d4-a716-446655440000")

        # 1. Query recent position data
        print("1. Querying recent position data...")
        response = await telemetry.query(
            vessel_id=vessel_id,
            data_type="position",
            start_time=datetime.now(UTC) - timedelta(hours=1),
            limit=100,
            order=OrderDirection.DESC,
        )
        print(f"   Found {len(response.data)} points")
        print(f"   Total: {response.meta.total}, Has more: {response.meta.has_more}")

        if response.data:
            latest = response.data[0]
            print(f"   Latest: {latest.time}, Lat: {latest.latitude}, Lon: {latest.longitude}")

        # 2. Get latest telemetry for multiple types
        print("\n2. Getting latest telemetry...")
        latest_response = await telemetry.get_latest(
            vessel_id=vessel_id,
            data_type="position,speed,course",
        )
        print(f"   Found {len(latest_response.data)} latest points:")
        for point in latest_response.data:
            print(f"   - {point.data_type}: {point.time}")

        # 3. Get aggregated speed data (hourly average)
        print("\n3. Getting hourly average speed...")
        agg_response = await telemetry.aggregate(
            vessel_id=vessel_id,
            data_type=DataType.SPEED,
            start_time=datetime.now(UTC) - timedelta(days=1),
            end_time=datetime.now(UTC),
            interval="1 hour",
            agg_type=AggregationType.AVG,
        )
        print(f"   Interval: {agg_response.interval}")
        print(f"   Aggregation: {agg_response.agg_type}")
        print(f"   Data points: {len(agg_response.data)}")

        if agg_response.data:
            for i, bucket in enumerate(agg_response.data[:5]):  # Show first 5
                print(f"   [{i}] {bucket.bucket}: {bucket.value:.2f} (count: {bucket.count})")

        # 4. Downsample position data for chart rendering
        print("\n4. Downsampling position data for visualization...")
        downsample_response = await telemetry.downsample(
            vessel_id=vessel_id,
            data_type=DataType.POSITION,
            start_time=datetime.now(UTC) - timedelta(days=7),
            end_time=datetime.now(UTC),
            target_points=500,
        )
        print(f"   Requested: 500 points")
        print(f"   Received: {len(downsample_response.data)} points")
        print(f"   Has more: {downsample_response.meta.has_more}")

        # 5. Query with pagination
        print("\n5. Paginated query...")
        offset = 0
        limit = 100
        total_fetched = 0

        while True:
            page = await telemetry.query(
                vessel_id=vessel_id,
                data_type="position",
                start_time=datetime.now(UTC) - timedelta(hours=24),
                limit=limit,
                offset=offset,
            )

            total_fetched += len(page.data)
            print(f"   Page: {offset // limit + 1}, Points: {len(page.data)}")

            if not page.meta.has_more:
                break

            offset += limit

            # Limit to first 3 pages for example
            if offset >= 300:
                break

        print(f"   Total fetched: {total_fetched} points")


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