"""Media service telemetry and progress tracking."""

import logging
import time
from typing import Any, Dict, List, Optional

from .media_types import (
    DownloadProgress,
    ProcessingProgress,
    ProgressCallback,
    TelemetryData,
)

logger = logging.getLogger(__name__)


class MediaTelemetry:
    """Telemetry service for media operations."""

    def __init__(self):
        self.telemetry_data: List[TelemetryData] = []

    def create_telemetry(self, operation: str) -> TelemetryData:
        """Create a new telemetry record."""
        return TelemetryData(operation=operation, start_time=time.time())

    def update_telemetry_success(self, telemetry: TelemetryData, file_size: Optional[int] = None) -> None:
        """Update telemetry record for successful operation."""
        telemetry.end_time = time.time()
        telemetry.duration = telemetry.end_time - telemetry.start_time
        telemetry.success = True
        if file_size:
            telemetry.file_size = file_size
        self.telemetry_data.append(telemetry)

    def update_telemetry_error(self, telemetry: TelemetryData, error: Exception) -> None:
        """Update telemetry record for failed operation."""
        telemetry.end_time = time.time()
        telemetry.duration = telemetry.end_time - telemetry.start_time
        telemetry.error_type = type(error).__name__
        telemetry.error_message = str(error)
        self.telemetry_data.append(telemetry)

    def get_telemetry_data(self) -> List[TelemetryData]:
        """Get telemetry data for monitoring."""
        return self.telemetry_data.copy()

    def clear_telemetry_data(self) -> None:
        """Clear telemetry data."""
        self.telemetry_data.clear()


class ProgressTracker:
    """Progress tracking for media operations."""

    @staticmethod
    def create_download_progress(
        downloaded_bytes: int,
        total_bytes: Optional[int],
        speed: Optional[float],
        eta: Optional[int],
        status: str,
    ) -> DownloadProgress:
        """Create download progress information."""
        percentage = 0.0
        if total_bytes:
            percentage = (downloaded_bytes / total_bytes) * 100

        return DownloadProgress(
            downloaded_bytes=downloaded_bytes,
            total_bytes=total_bytes,
            speed=speed,
            eta=eta,
            status=status,
            percentage=percentage,
        )

    @staticmethod
    def create_processing_progress(
        stage: str,
        current_step: int,
        total_steps: int,
        status: str,
        message: str,
        start_time: float,
        elapsed_time: float = 0.0,
    ) -> ProcessingProgress:
        """Create processing progress information."""
        return ProcessingProgress(
            stage=stage,
            current_step=current_step,
            total_steps=total_steps,
            status=status,
            message=message,
            start_time=start_time,
            elapsed_time=elapsed_time,
        )

    @staticmethod
    def notify_progress(
        progress: DownloadProgress | ProcessingProgress,
        progress_callback: Optional[ProgressCallback] = None,
    ) -> None:
        """Notify progress callback if available."""
        if progress_callback:
            progress_callback(progress)

    @staticmethod
    def log_download_progress(progress: DownloadProgress) -> None:
        """Log download progress information."""
        if progress.total_bytes:
            logger.info(
                f"Download progress: {progress.percentage:.1f}% "
                f"({progress.downloaded_bytes}/{progress.total_bytes} bytes)"
            )
        else:
            logger.info(f"Downloaded: {progress.downloaded_bytes} bytes")

    @staticmethod
    def log_processing_progress(progress: ProcessingProgress) -> None:
        """Log processing progress information."""
        logger.info(
            f"Processing: {progress.stage} - {progress.current_step}/{progress.total_steps} - {progress.status}"
        )
