"""Amplitude analytics service for Dash AI Chat."""

import logging
import os
import time
from enum import Enum
from typing import Any, Dict, Optional

from ._cloud_env import cloud_config

logger = logging.getLogger(__name__)


class ChatEvent(Enum):
    """Event types for Dash AI Chat analytics."""

    CHAT_MESSAGE_SUBMITTED = "dash_chat_message_submitted"
    CHAT_SESSION_STARTED = "dash_chat_session_started"
    CHAT_CHANGES_APPLIED = "dash_chat_changes_applied"


class AmplitudeService:
    """Service for tracking events with Amplitude Analytics."""

    def __init__(self):
        self.amplitude_api_key = cloud_config.get_amplitude_api_key()
        self.client = None

        try:
            from amplitude import Amplitude

            self.client = Amplitude(self.amplitude_api_key)
            logger.info("Amplitude analytics initialized for Dash AI Chat")
        except ImportError:
            logger.warning("Amplitude library not available. Events will not be tracked.")

    def track_event(
        self,
        event_type: str,
        user_id: Optional[str] = None,
        device_id: Optional[str] = None,
        event_properties: Optional[Dict[str, Any]] = None,
        user_properties: Optional[Dict[str, Any]] = None,
    ):
        """Track an event with Amplitude.

        Args:
            event_type: The name of the event to track
            user_id: Optional user identifier
            device_id: Optional device identifier
            event_properties: Properties specific to this event
            user_properties: Properties about the user
        """
        if not self.client:
            logger.debug(f"Amplitude not configured, skipping event: {event_type}")
            return

        try:
            from amplitude import BaseEvent

            event = BaseEvent(
                event_type=event_type,
                user_id=user_id,
                device_id=device_id,
                event_properties=event_properties or {},
                user_properties=user_properties or {},
            )

            self.client.track(event)
            logger.debug(f"Tracked Amplitude event: {event_type}")

        except Exception as e:
            logger.error(f"Failed to track Amplitude event {event_type}: {str(e)}")

    def track_chat_event(
        self,
        event_type: ChatEvent,
        user_id: Optional[str] = None,
        project_path: Optional[str] = None,
        start_time: Optional[float] = None,
        tool_calls_made: Optional[list] = None,
        success: bool = True,
        error_message: Optional[str] = None,
        **additional_properties,
    ):
        """Track a chat-related event.

        Args:
            event_type: The chat event type
            user_id: User identifier from OAuth
            project_path: Path to the project being worked on
            start_time: Start time in epoch seconds to calculate duration
            tool_calls_made: List of tool names that were called
            success: Whether the operation was successful
            error_message: Error message if operation failed
            **additional_properties: Any additional event properties
        """
        event_properties: Dict[str, Any] = {
            "success": success,
            **additional_properties,
        }

        if project_path:
            # Only include the project directory name, not full path for privacy
            event_properties["project_name"] = os.path.basename(project_path)

        if tool_calls_made:
            event_properties["tool_calls_count"] = len(tool_calls_made)
            event_properties["tools_used"] = list(set(tool_calls_made))

        if error_message:
            event_properties["error_message"] = error_message[:200]

        if start_time is not None:
            event_properties["duration_seconds"] = round(time.time() - start_time, 2)

        self.track_event(
            event_type=event_type.value,
            user_id=user_id,
            event_properties=event_properties,
        )


# Global instance
amplitude_service = AmplitudeService()
