#!/usr/bin/env python3
"""
Performance Monitor for Screenshare Bot - Task #118 Stream B

Tracks real-time performance metrics including FPS, memory usage, CPU usage,
frame capture timing, and command latency. Provides monitoring loop and
summary statistics for performance analysis.
"""

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

try:
    import psutil
    PSUTIL_AVAILABLE = True
except ImportError:
    PSUTIL_AVAILABLE = False

logger = logging.getLogger(__name__)


class PerformanceMonitor:
    """
    Monitors bot performance with real-time metrics tracking.

    Tracks:
    - FPS: Frames per second achieved
    - Memory: Memory usage in MB
    - CPU: CPU percentage
    - Frame capture time: Time to capture each frame in ms
    - Command latency: Slide command response time in ms

    Usage:
        monitor = PerformanceMonitor("bot-123")
        asyncio.create_task(monitor.start_monitoring(interval_seconds=30))
        monitor.record_fps(9.8)
        summary = monitor.get_summary()
    """

    def __init__(self, bot_id: str) -> None:
        """
        Initialize performance monitor.

        Args:
            bot_id: Unique identifier for the bot being monitored
        """
        self.bot_id: str = bot_id
        self.metrics: Dict[str, List[float]] = {
            'fps': [],
            'memory_mb': [],
            'cpu_percent': [],
            'frame_capture_ms': [],
            'command_latency_ms': []
        }

        # Process handle for system metrics
        self.process: Any = None
        if PSUTIL_AVAILABLE:
            try:
                self.process = psutil.Process()
            except Exception as e:
                logger.warning(f"Failed to initialize psutil Process: {e}")
        else:
            logger.warning("psutil not available - system metrics will not be collected")

        # Monitoring state
        self.is_monitoring: bool = False
        self.monitoring_task: Optional[asyncio.Task[None]] = None

        # FPS calculation helpers
        self.last_fps_check: Optional[float] = None
        self.frames_since_last_check: int = 0

        logger.info(f"PerformanceMonitor initialized for bot {bot_id}")

    async def start_monitoring(self, interval_seconds: int = 30) -> None:
        """
        Start background monitoring loop that collects system metrics.

        This runs continuously in the background, logging metrics every
        interval_seconds. Should be started as an asyncio task.

        Args:
            interval_seconds: How often to collect and log metrics (default: 30)
        """
        if not PSUTIL_AVAILABLE or not self.process:
            logger.warning("Performance monitoring disabled - psutil not available")
            return

        logger.info(f"Starting performance monitoring (interval: {interval_seconds}s)")
        self.is_monitoring = True

        try:
            while self.is_monitoring:
                await asyncio.sleep(interval_seconds)

                # Collect system metrics
                try:
                    # Memory usage in MB
                    memory_info = self.process.memory_info()
                    memory_mb = memory_info.rss / 1024 / 1024
                    self.metrics['memory_mb'].append(memory_mb)

                    # CPU percentage (measured over 1 second)
                    cpu_percent = self.process.cpu_percent(interval=1)
                    self.metrics['cpu_percent'].append(cpu_percent)

                    # Log current metrics
                    logger.info(
                        f"Bot {self.bot_id} Performance - "
                        f"Memory: {memory_mb:.1f}MB, "
                        f"CPU: {cpu_percent:.1f}%, "
                        f"FPS: {self._get_latest_fps():.1f}, "
                        f"Frame Capture: {self._get_latest_frame_capture():.1f}ms, "
                        f"Command Latency: {self._get_latest_command_latency():.1f}ms"
                    )

                except Exception as e:
                    logger.error(f"Error collecting metrics: {e}", exc_info=True)

        except asyncio.CancelledError:
            logger.info("Performance monitoring cancelled")
        except Exception as e:
            logger.error(f"Performance monitoring error: {e}", exc_info=True)
        finally:
            self.is_monitoring = False
            logger.info("Performance monitoring stopped")

    def record_fps(self, fps: float) -> None:
        """
        Record current frames per second.

        Args:
            fps: Current FPS measurement
        """
        self.metrics['fps'].append(fps)

    def record_frame_capture_time(self, ms: float) -> None:
        """
        Record frame capture timing.

        Args:
            ms: Time taken to capture frame in milliseconds
        """
        self.metrics['frame_capture_ms'].append(ms)

    def record_command_latency(self, ms: float) -> None:
        """
        Record slide command latency.

        Args:
            ms: Time from command received to execution in milliseconds
        """
        self.metrics['command_latency_ms'].append(ms)

    def _get_latest_fps(self) -> float:
        """Get latest FPS value or 0 if none recorded."""
        return self.metrics['fps'][-1] if self.metrics['fps'] else 0.0

    def _get_latest_frame_capture(self) -> float:
        """Get latest frame capture time or 0 if none recorded."""
        return self.metrics['frame_capture_ms'][-1] if self.metrics['frame_capture_ms'] else 0.0

    def _get_latest_command_latency(self) -> float:
        """Get latest command latency or 0 if none recorded."""
        return self.metrics['command_latency_ms'][-1] if self.metrics['command_latency_ms'] else 0.0

    def get_summary(self) -> Dict[str, Any]:
        """
        Calculate performance summary statistics.

        Returns average and maximum values for all tracked metrics.

        Returns:
            Dictionary with avg/max for each metric:
            {
                'avg_fps': float,
                'min_fps': float,
                'max_fps': float,
                'avg_memory_mb': float,
                'max_memory_mb': float,
                'avg_cpu_percent': float,
                'max_cpu_percent': float,
                'avg_frame_capture_ms': float,
                'max_frame_capture_ms': float,
                'avg_command_latency_ms': float,
                'max_command_latency_ms': float,
                'total_samples': int
            }
        """
        summary = {
            'bot_id': self.bot_id,
            'total_samples': max(len(v) for v in self.metrics.values())
        }

        # Calculate statistics for each metric
        for metric_name, values in self.metrics.items():
            if values:
                avg = sum(values) / len(values)
                max_val = max(values)
                min_val = min(values)

                # Format metric names for summary
                summary[f'avg_{metric_name}'] = round(avg, 2)
                summary[f'max_{metric_name}'] = round(max_val, 2)

                # Only include min for FPS (lower is worse)
                if metric_name == 'fps':
                    summary[f'min_{metric_name}'] = round(min_val, 2)
            else:
                summary[f'avg_{metric_name}'] = 0.0
                summary[f'max_{metric_name}'] = 0.0
                if metric_name == 'fps':
                    summary[f'min_{metric_name}'] = 0.0

        return summary

    def stop_monitoring(self) -> None:
        """Stop the monitoring loop."""
        logger.info(f"Stopping performance monitoring for bot {self.bot_id}")
        self.is_monitoring = False

    def reset_metrics(self) -> None:
        """Clear all recorded metrics."""
        logger.info(f"Resetting metrics for bot {self.bot_id}")
        for key in self.metrics:
            self.metrics[key] = []
