"""Anonymous telemetry tracker using Segment."""

import logging
import platform
import sys
from datetime import datetime
from typing import Any, Dict, Optional

from ..observability import DataRedactor, ObservabilitySession

from .config import TelemetryConfig, TelemetryMode
from .events import ConnectorInitEvent, OperationEvent, SessionEndEvent

logger = logging.getLogger(__name__)


class SegmentTracker:
    """Anonymous telemetry tracker using Segment."""

    def __init__(
        self,
        session: ObservabilitySession,
        mode: Optional[TelemetryMode] = None,
    ):
        self.session = session
        self.mode = mode or TelemetryConfig.get_mode()
        self.redactor = DataRedactor()
        self.success_count = 0
        self.failure_count = 0
        self.enabled = TelemetryConfig.is_enabled()
        self._analytics = None

        if self.enabled:
            write_key = TelemetryConfig.get_write_key()
            try:
                import segment.analytics as analytics

                analytics.write_key = write_key
                self._analytics = analytics
                self._log_startup_message()
            except ImportError:
                logger.warning(
                    "Telemetry disabled: segment-analytics-python not installed"
                )
                self.enabled = False
        elif self.mode != TelemetryMode.DISABLED:
            # Mode is not disabled but write key is missing
            logger.warning("Telemetry disabled: SEGMENT_WRITE_KEY not set")

    def _log_startup_message(self):
        """Log message when telemetry is enabled."""
        logger.info(f"Anonymous telemetry enabled (mode: {self.mode.value})")
        logger.info("To opt-out: export TELEMETRY_MODE=disabled")

    def track_connector_init(
        self,
        connector_version: Optional[str] = None,
    ) -> None:
        """Track connector initialization."""
        if not self.enabled or not self._analytics:
            return

        try:
            event = ConnectorInitEvent(
                timestamp=datetime.utcnow(),
                anonymous_id=self.session.session_id,
                execution_context=self.session.execution_context,
                connector_name=self.session.connector_name,
                connector_version=connector_version,
                python_version=f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
                os_name=platform.system(),
                os_version=platform.release(),
            )

            self._analytics.track(
                user_id=None,
                anonymous_id=event.anonymous_id,
                event="Connector Initialized",
                properties=event.to_dict(),
            )
        except Exception as e:
            # Never fail on tracking errors
            logger.error(f"Telemetry error: {e}")

    def track_operation(
        self,
        resource: str,
        verb: str,
        status_code: Optional[int],
        timing_ms: float,
        error_type: Optional[str] = None,
        error_message: Optional[str] = None,
        params: Optional[Dict[str, Any]] = None,
    ) -> None:
        """Track API operation."""
        # Always track success/failure counts (useful even when tracking is disabled)
        if status_code and 200 <= status_code < 300:
            self.success_count += 1
        else:
            self.failure_count += 1

        if not self.enabled or not self._analytics:
            return

        try:
            # Redact params if tracking detailed mode
            safe_params = None
            if self.mode == TelemetryMode.DETAILED and params:
                safe_params = self.redactor.redact_params(params)

            # Redact error message in basic mode
            safe_error_message = None
            if error_message:
                if self.mode == TelemetryMode.DETAILED:
                    safe_error_message = error_message  # Keep full message in detailed
                else:
                    safe_error_message = None  # Omit in basic mode

            event = OperationEvent(
                timestamp=datetime.utcnow(),
                anonymous_id=self.session.session_id,
                execution_context=self.session.execution_context,
                connector_name=self.session.connector_name,
                resource=resource,
                verb=verb,
                status_code=status_code,
                timing_ms=timing_ms,
                error_type=error_type,
                error_message=safe_error_message,
                params=safe_params,
            )

            self._analytics.track(
                user_id=None,
                anonymous_id=event.anonymous_id,
                event="Operation Executed",
                properties=event.to_dict(),
            )
        except Exception as e:
            logger.error(f"Telemetry error: {e}")

    def track_session_end(self) -> None:
        """Track session end."""
        if not self.enabled or not self._analytics:
            return

        try:
            event = SessionEndEvent(
                timestamp=datetime.utcnow(),
                anonymous_id=self.session.session_id,
                execution_context=self.session.execution_context,
                connector_name=self.session.connector_name,
                duration_seconds=self.session.duration_seconds(),
                operation_count=self.session.operation_count,
                success_count=self.success_count,
                failure_count=self.failure_count,
            )

            self._analytics.track(
                user_id=None,
                anonymous_id=event.anonymous_id,
                event="Session Ended",
                properties=event.to_dict(),
            )

            # Ensure events are sent before shutdown
            self._analytics.flush()
        except Exception as e:
            logger.error(f"Telemetry error: {e}")
