"""
Logging utilities for the sensor data processing system.

Converts MATLAB log file management to Python logging.
"""

import logging
from pathlib import Path
from datetime import datetime
from typing import Optional


def setup_logger(
    control_unit_id: str,
    chain: str,
    module_name: str = "RSN",
    log_dir: str = ".",
    level: int = logging.INFO
) -> logging.Logger:
    """
    Setup logger for a processing module.

    Creates a log file following the MATLAB naming convention:
    LogFile_MODULE-UNITID-CHAIN-YYYY_MM_DD-HH_MM_SS.txt

    Args:
        control_unit_id: Control unit identifier
        chain: Chain identifier
        module_name: Module name (RSN, Tilt, ATD, etc.)
        log_dir: Directory for log files
        level: Logging level

    Returns:
        Configured logger instance
    """
    # Create log directory if it doesn't exist
    log_path = Path(log_dir)
    log_path.mkdir(parents=True, exist_ok=True)

    # Generate log filename with timestamp
    now = datetime.now()
    date_str = now.strftime("%Y_%m_%d")
    time_str = now.strftime("%H_%M_%S")
    log_filename = f"LogFile_{module_name}-{control_unit_id}-{chain}-{date_str}-{time_str}.txt"
    log_file = log_path / log_filename

    # Create logger
    logger = logging.getLogger(f"{module_name}.{control_unit_id}.{chain}")
    logger.setLevel(level)

    # Remove existing handlers to avoid duplicates
    logger.handlers.clear()

    # Create file handler
    file_handler = logging.FileHandler(log_file, mode='w', encoding='utf-8')
    file_handler.setLevel(level)

    # Create console handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)

    # Create formatter
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # Add handlers to logger
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    # Log initial message
    logger.info(f"Elaboration of {module_name} chain {chain} of control unit {control_unit_id} started correctly")

    return logger


def log_function_start(logger: logging.Logger, function_name: str) -> None:
    """
    Log function start message.

    Args:
        logger: Logger instance
        function_name: Name of the function
    """
    logger.info(f"{function_name} function started")


def log_function_end(logger: logging.Logger, function_name: str, success: bool = True) -> None:
    """
    Log function end message.

    Args:
        logger: Logger instance
        function_name: Name of the function
        success: Whether function completed successfully
    """
    if success:
        logger.info(f"{function_name} function closed successfully")
    else:
        logger.error(f"{function_name} function FAILED")


def log_elapsed_time(logger: logging.Logger, elapsed_seconds: float) -> None:
    """
    Log elapsed time for processing.

    Args:
        logger: Logger instance
        elapsed_seconds: Elapsed time in seconds
    """
    logger.info(f"Processing completed in {elapsed_seconds:.2f} seconds")


class LogFileWriter:
    """
    Context manager for writing to log files.

    Provides compatibility with MATLAB-style log file writing.
    """

    def __init__(self, filename: str, mode: str = 'a'):
        """
        Initialize log file writer.

        Args:
            filename: Log file path
            mode: File open mode ('a' for append, 'w' for write)
        """
        self.filename = filename
        self.mode = mode
        self.file: Optional[object] = None

    def __enter__(self):
        """Open file for writing."""
        self.file = open(self.filename, self.mode, encoding='utf-8')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Close file."""
        if self.file:
            self.file.close()

    def write(self, message: str) -> None:
        """
        Write message to log file.

        Args:
            message: Message to write
        """
        if self.file:
            self.file.write(f"{message}\n")
            self.file.flush()


def create_error_file(control_unit_id: str, error_message: str) -> str:
    """
    Create error file with exception details.

    Converts MATLAB error file creation.

    Args:
        control_unit_id: Control unit identifier
        error_message: Error message to write

    Returns:
        Error file path
    """
    now = datetime.now()
    date_str = now.strftime("%Y-%m-%d")
    time_str = now.strftime("%H%M%S")
    error_filename = f"ErrorFile-{control_unit_id}-{date_str}-{time_str}.txt"

    with open(error_filename, 'w', encoding='utf-8') as f:
        f.write(error_message)

    return error_filename
