"""
Telemetry service for sending data to SudoDog backend.

Handles all communication with the dashboard backend.
"""

import requests
import logging
import json
from typing import Dict, Any
import time

logger = logging.getLogger(__name__)


class TelemetryService:
    """Service for sending telemetry data to backend"""

    def __init__(self, config: Dict[str, Any]):
        """
        Initialize telemetry service.

        Args:
            config: Configuration dict with api_key and endpoint
        """
        self.config = config
        self.api_key = config.get('api_key', '')
        # BUG-003 FIX: Standardize endpoint URL to match backend route
        self.endpoint = config.get('endpoint', 'https://api.sudodog.com/api/v1/telemetry')
        self.enabled = config.get('telemetry_enabled', True)
        self.session = requests.Session()

        # Set default headers
        self.session.headers.update({
            'Content-Type': 'application/json',
            'User-Agent': 'SudoDog-CLI/1.0',
        })

        if self.api_key:
            self.session.headers.update({
                'Authorization': f'Bearer {self.api_key}'
            })

    def send(self, data: Dict[str, Any]) -> bool:
        """
        Send telemetry data to backend.

        Args:
            data: Telemetry data to send

        Returns:
            True if successful, False otherwise
        """
        if not self.enabled:
            logger.debug("Telemetry disabled, skipping send")
            return False

        try:
            # Add timestamp if not present
            if 'timestamp' not in data:
                data['timestamp'] = time.time()

            # Send to backend
            response = self.session.post(
                self.endpoint,
                json=data,
                timeout=5  # 5 second timeout
            )

            if response.status_code == 200:
                logger.debug("Telemetry sent successfully")
                return True
            else:
                logger.warning(
                    f"Telemetry send failed: {response.status_code} - {response.text}"
                )
                return False

        except requests.exceptions.Timeout:
            logger.warning("Telemetry send timed out")
            return False

        except requests.exceptions.RequestException as e:
            logger.warning(f"Telemetry send failed: {e}")
            return False

        except Exception as e:
            logger.error(f"Unexpected error sending telemetry: {e}")
            return False

    def send_batch(self, data_list: list) -> bool:
        """
        Send batch of telemetry data.

        Args:
            data_list: List of telemetry data dicts

        Returns:
            True if successful, False otherwise
        """
        if not self.enabled:
            return False

        try:
            response = self.session.post(
                f"{self.endpoint}/batch",
                json={"events": data_list},
                timeout=10
            )

            return response.status_code == 200

        except Exception as e:
            logger.error(f"Batch telemetry send failed: {e}")
            return False

    def send_event(self, event_type: str, event_data: Dict[str, Any]) -> bool:
        """
        Send a single event.

        Args:
            event_type: Type of event (e.g., 'agent_start', 'agent_stop')
            event_data: Event data

        Returns:
            True if successful
        """
        data = {
            "event_type": event_type,
            "data": event_data,
            "timestamp": time.time()
        }

        return self.send(data)

    def close(self):
        """Close the telemetry session"""
        self.session.close()

    def __enter__(self):
        """Context manager entry"""
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Context manager exit"""
        self.close()
        return False
