"""
Trace querier for releaseops analytics.

Provides convenient query methods on top of TracePlatform.
"""

from __future__ import annotations

from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple


class TraceQuerier:
    """Queries traces from a TracePlatform with bundle-aware filters."""

    def __init__(self, platform) -> None:
        self._platform = platform

    def query_by_bundle(
        self,
        bundle_id: str,
        version: str,
        env: str,
        limit: int = 100,
        time_range: Optional[Tuple[str, str]] = None,
    ) -> List[Dict[str, Any]]:
        """Query traces for a specific bundle version in an environment."""
        filter = {
            "bundle_id": bundle_id,
            "bundle_version": version,
            "environment": env,
        }
        return self._platform.query_traces(filter, limit=limit, time_range=time_range)

    def query_by_time_range(
        self,
        bundle_id: str,
        env: str,
        start: str,
        end: str,
        limit: int = 100,
    ) -> List[Dict[str, Any]]:
        """Query traces for a bundle within a time range."""
        filter = {
            "bundle_id": bundle_id,
            "environment": env,
        }
        return self._platform.query_traces(
            filter, limit=limit, time_range=(start, end)
        )

    def query_recent(
        self,
        bundle_id: str,
        env: str,
        hours: int = 24,
        limit: int = 100,
    ) -> List[Dict[str, Any]]:
        """Query recent traces for a bundle."""
        now = datetime.now(timezone.utc)
        start = (now - timedelta(hours=hours)).isoformat()
        end = now.isoformat()
        filter = {
            "bundle_id": bundle_id,
            "environment": env,
        }
        return self._platform.query_traces(
            filter, limit=limit, time_range=(start, end)
        )
