"""
TelemetryClient - Optional cloud monitoring for premium users

Sends events to QALRON server for real-time dashboard updates.
Fails gracefully if network unavailable.
"""

import requests
from typing import Dict, Any, Optional
from datetime import datetime


class TelemetryClient:
    """
    Cloud telemetry client for premium tier.
    
    Sends events to QALRON server for:
    - Real-time dashboard updates
    - Usage tracking
    - Cost analytics
    - Alert notifications
    
    Designed to fail gracefully - network errors don't break core functionality.
    
    Example:
        >>> client = TelemetryClient(api_key="sk-premium-xyz")
        >>> client.track_event({
        ...     "type": "message_sent",
        ...     "from": "researcher",
        ...     "to": "analyst"
        ... })
    """
    
    def __init__(
        self,
        api_key: str,
        server_url: str = "https://api.QALRON.io",
        timeout: int = 5
    ):
        """
        Initialize telemetry client.
        
        Args:
            api_key: QALRON API key
            server_url: Server URL for telemetry endpoint
            timeout: Request timeout in seconds
        """
        self.api_key = api_key
        self.server_url = server_url.rstrip('/')
        self.timeout = timeout
        
        # Create session for connection pooling
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {self.api_key}",
            "User-Agent": "QALRON-SDK/2.0.0",
            "Content-Type": "application/json"
        })
    
    def track_event(self, event: Dict[str, Any]) -> bool:
        """
        Send event to cloud dashboard.
        
        Args:
            event: Event data dictionary
                Required fields:
                - type: Event type (e.g., "message_sent", "llm_call")
                Optional fields:
                - from: Sender agent ID
                - to: Receiver agent ID
                - cost: LLM cost (for llm_call events)
                - Any other metadata
        
        Returns:
            True if successful, False if failed
        """
        try:
            # Add timestamp if not present
            if "timestamp" not in event:
                event["timestamp"] = datetime.utcnow().isoformat()
            
            # Send to server
            response = self.session.post(
                f"{self.server_url}/v1/telemetry",
                json=event,
                timeout=self.timeout
            )
            
            # Check response
            if response.status_code == 200:
                return True
            else:
                print(f"[QALRON] Telemetry failed: HTTP {response.status_code}")
                return False
                
        except requests.exceptions.Timeout:
            print("[QALRON] Telemetry timeout (non-critical)")
            return False
        except requests.exceptions.ConnectionError:
            print("[QALRON] Telemetry connection failed (non-critical)")
            return False
        except Exception as e:
            print(f"[QALRON] Telemetry error: {e}")
            return False
    
    def check_quota(self) -> Optional[Dict[str, Any]]:
        """
        Check usage quota from server.
        
        Returns:
            Dictionary with quota info or None if failed
            {
                "used": 1234,
                "limit": 100000,
                "reset_date": "2026-03-01"
            }
        """
        try:
            response = self.session.get(
                f"{self.server_url}/v1/quota",
                timeout=self.timeout
            )
            
            if response.status_code == 200:
                data = response.json()
                return data.get("quota")
            else:
                return None
                
        except Exception as e:
            print(f"[QALRON] Quota check failed: {e}")
            return None
    
    def close(self):
        """Close session and cleanup"""
        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()
