"""Simple monitoring engine implementation."""

from typing import List, Optional
from datetime import datetime, timedelta
from .execution_log import ExecutionLog


class SimpleMonitoringEngine:
    """Simple in-memory monitoring engine."""

    def __init__(self, max_logs: int = 1000):
        """Initialize monitoring engine.
        
        Args:
            max_logs: Maximum number of logs to keep in memory
        """
        self._logs: List[ExecutionLog] = []
        self._max_logs = max_logs

    def log_execution_start(self, action_id: str, details: dict = None) -> ExecutionLog:
        """Log execution start.
        
        Args:
            action_id: Action identifier
            details: Additional details
            
        Returns:
            ExecutionLog entry
        """
        log = ExecutionLog(
            timestamp=datetime.now(),
            action_id=action_id,
            status="started",
            details=details or {}
        )
        self._add_log(log)
        return log

    def log_execution_end(self, action_id: str, details: dict = None) -> ExecutionLog:
        """Log execution success.
        
        Args:
            action_id: Action identifier
            details: Additional details
            
        Returns:
            ExecutionLog entry
        """
        log = ExecutionLog(
            timestamp=datetime.now(),
            action_id=action_id,
            status="success",
            details=details or {}
        )
        self._add_log(log)
        return log

    def log_failure(self, action_id: str, error: str, details: dict = None) -> ExecutionLog:
        """Log execution failure.
        
        Args:
            action_id: Action identifier
            error: Error message
            details: Additional details
            
        Returns:
            ExecutionLog entry
        """
        details = details or {}
        details["error"] = error
        
        log = ExecutionLog(
            timestamp=datetime.now(),
            action_id=action_id,
            status="failed",
            details=details
        )
        self._add_log(log)
        return log

    def get_recent_events(self, limit: int = 10) -> List[ExecutionLog]:
        """Get recent execution events.
        
        Args:
            limit: Maximum number of events to return
            
        Returns:
            List of recent logs
        """
        return self._logs[-limit:]

    def get_events_by_action(self, action_id: str, limit: int = 10) -> List[ExecutionLog]:
        """Get events for specific action.
        
        Args:
            action_id: Action identifier
            limit: Maximum number of events
            
        Returns:
            List of logs for action
        """
        filtered = [log for log in self._logs if log.action_id == action_id]
        return filtered[-limit:]

    def get_events_by_status(self, status: str, limit: int = 10) -> List[ExecutionLog]:
        """Get events by status.
        
        Args:
            status: Status filter (started, success, failed)
            limit: Maximum number of events
            
        Returns:
            List of logs with status
        """
        filtered = [log for log in self._logs if log.status == status]
        return filtered[-limit:]

    def get_events_since(self, since: datetime) -> List[ExecutionLog]:
        """Get events since timestamp.
        
        Args:
            since: Timestamp to filter from
            
        Returns:
            List of logs since timestamp
        """
        return [log for log in self._logs if log.timestamp >= since]

    def get_statistics(self) -> dict:
        """Get execution statistics.
        
        Returns:
            Statistics dictionary
        """
        total = len(self._logs)
        started = sum(1 for log in self._logs if log.status == "started")
        success = sum(1 for log in self._logs if log.status == "success")
        failed = sum(1 for log in self._logs if log.status == "failed")
        
        return {
            "total_events": total,
            "started": started,
            "success": success,
            "failed": failed,
            "success_rate": success / total if total > 0 else 0.0
        }

    def clear_logs(self) -> int:
        """Clear all logs.
        
        Returns:
            Number of logs cleared
        """
        count = len(self._logs)
        self._logs.clear()
        return count

    def _add_log(self, log: ExecutionLog) -> None:
        """Add log entry and maintain max size.
        
        Args:
            log: Log entry to add
        """
        self._logs.append(log)
        
        # Trim if exceeds max
        if len(self._logs) > self._max_logs:
            self._logs = self._logs[-self._max_logs:]
