"""
ARTOS Module Interface Definition.

This module defines the abstract base class that all ARTOS modules must implement.
Based on ARTOS design specification v1.0.
"""
import abc
from datetime import datetime
from typing import Any, Dict, Optional


class BaseModule(abc.ABC):
    """
    Abstract Base Class defining the mandatory interface for all ARTOS modules.
    
    All specialized modules (BusMonitor1553, VideoReceiver, TargetSimulator) 
    must inherit from this class and implement its abstract methods.
    
    This ensures the ARTOS Collector can orchestrate all modules using a 
    uniform interface without knowing implementation details.
    """

    def __init__(self, name: str):
        """
        Initialize the base module.
        
        Args:
            name: Unique identifier for this module instance
        """
        self.module_name = name
        self.is_running = False

    @abc.abstractmethod
    def initialize(self, config: Dict[str, Any]) -> bool:
        """
        Setup communication and resources.
        
        This method is called once before the module is used. It should:
        - Parse configuration parameters
        - Initialize hardware/network connections
        - Prepare internal data structures
        - Return success/failure status
        
        Args:
            config: Dictionary containing module-specific parameters
                   (e.g., IP addresses, ports, file paths)
        
        Returns:
            True if initialization successful, False otherwise
        """
        pass

    @abc.abstractmethod
    def start_session(self) -> None:
        """
        Start data acquisition or simulation.
        
        After this call, the module should begin:
        - Capturing data from its source
        - Processing incoming packets
        - Making data available via get_status() or data streams
        
        This method sets is_running = True
        """
        self.is_running = True

    @abc.abstractmethod
    def stop_session(self) -> None:
        """
        Stop the module and release resources.
        
        This method should:
        - Stop all threads/processes
        - Close network connections
        - Flush buffers to disk if recording
        - Release hardware resources
        
        This method sets is_running = False
        """
        self.is_running = False

    @abc.abstractmethod
    def get_status(self) -> Dict[str, Any]:
        """
        Return the health status of the module.
        
        The ARTOS Collector uses this to monitor module health during test execution.
        
        Returns:
            Dictionary with status information. Should include at minimum:
            - 'is_running': bool
            - 'connected': bool (hardware/network link status)
            - 'errors': list of error messages (if any)
            - Module-specific metrics (packets received, buffer usage, etc.)
        """
        pass

    def get_system_timestamp(self) -> float:
        """
        Helper to get uniform system timestamp for data normalization.
        
        This provides a reference clock for cross-module synchronization.
        All timestamps should be captured using this method to ensure 
        consistency across the ARTOS system.
        
        Returns:
            Current system time in seconds since epoch (float with microsecond precision)
        """
        return datetime.now().timestamp()

    def shutdown(self) -> None:
        """
        Clean shutdown sequence (optional override).
        
        Default implementation calls stop_session().
        Subclasses can override for additional cleanup logic.
        """
        if self.is_running:
            self.stop_session()
