"""
Integrity Logger Module
Provides structured logging with severity levels and audit trail support.
"""

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


class IntegrityLogger:
    """
    Enhanced logger for integrity check operations with structured output.
    Supports both file and console logging with different formats.
    """
    
    # Log levels
    DEBUG = logging.DEBUG
    INFO = logging.INFO
    WARNING = logging.WARNING
    ERROR = logging.ERROR
    CRITICAL = logging.CRITICAL
    
    # Action types for structured logging
    ACTION_CHECK = "CHECK"
    ACTION_OK = "OK"
    ACTION_WARNING = "WARNING"
    ACTION_ERROR = "ERROR"
    ACTION_REPAIR = "REPAIR"
    ACTION_BACKUP = "BACKUP"
    
    def __init__(self, log_file: str = '/var/log/stellarmate/integrity.log', 
                 console_output: bool = True):
        """
        Initialize the integrity logger.
        
        Args:
            log_file: Path to the log file
            console_output: Whether to also output to console
        """
        self.log_file = log_file
        self.console_output = console_output
        self.start_time = datetime.now()
        self.stats = {
            'checked': 0,
            'passed': 0,
            'repaired': 0,
            'failed': 0,
            'skipped': 0
        }
        
        # Create log directory if it doesn't exist
        log_dir = os.path.dirname(log_file)
        os.makedirs(log_dir, exist_ok=True)
        
        # Configure logging
        self._setup_logger()
    
    def _setup_logger(self):
        """Setup the Python logging infrastructure."""
        # Create logger
        self.logger = logging.getLogger('stellarmate.integrity')
        self.logger.setLevel(logging.DEBUG)
        
        # Clear any existing handlers
        self.logger.handlers.clear()
        
        # File handler with detailed format
        file_handler = logging.FileHandler(self.log_file, mode='a')
        file_handler.setLevel(logging.DEBUG)
        file_formatter = logging.Formatter(
            '[%(asctime)s] %(levelname)s: %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        file_handler.setFormatter(file_formatter)
        self.logger.addHandler(file_handler)
        
        # Console handler with simpler format
        if self.console_output:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setLevel(logging.INFO)
            console_formatter = logging.Formatter('%(message)s')
            console_handler.setFormatter(console_formatter)
            self.logger.addHandler(console_handler)
    
    def log_start(self, version: str, model: str):
        """Log the start of an integrity check."""
        self.logger.info("=" * 70)
        self.logger.info(f"Starting StellarMate OS Integrity Check v{version}")
        self.logger.info(f"Detected model: {model}")
        self.logger.info(f"Timestamp: {self.start_time.isoformat()}")
        self.logger.info("=" * 70)
    
    def log_check(self, file_path: str, file_type: str):
        """Log the start of checking a file."""
        self.logger.info(f"CHECK: {file_path} [{file_type}]")
        self.stats['checked'] += 1
    
    def log_ok(self, file_path: str, message: str = "All checks passed"):
        """Log a successful check."""
        self.logger.info(f"OK: {file_path} - {message}")
        self.stats['passed'] += 1
    
    def log_warning(self, file_path: str, message: str):
        """Log a warning."""
        self.logger.warning(f"WARNING: {file_path} - {message}")
    
    def log_error(self, file_path: str, message: str):
        """Log an error."""
        self.logger.error(f"ERROR: {file_path} - {message}")
        self.stats['failed'] += 1
    
    def log_repair(self, file_path: str, action: str):
        """Log a repair action."""
        self.logger.info(f"REPAIR: {file_path} - {action}")
        self.stats['repaired'] += 1
    
    def log_backup(self, file_path: str, backup_path: str):
        """Log a backup operation."""
        self.logger.info(f"BACKUP: Created backup at {backup_path} for {file_path}")
    
    def log_skip(self, file_path: str, reason: str):
        """Log a skipped file."""
        self.logger.info(f"SKIP: {file_path} - {reason}")
        self.stats['skipped'] += 1
    
    def log_finish(self):
        """Log the completion of integrity check with statistics."""
        end_time = datetime.now()
        duration = (end_time - self.start_time).total_seconds()
        
        self.logger.info("=" * 70)
        self.logger.info("Integrity Check Complete")
        self.logger.info(f"Duration: {duration:.2f} seconds")
        self.logger.info(f"Files checked: {self.stats['checked']}")
        self.logger.info(f"Passed: {self.stats['passed']}")
        self.logger.info(f"Repaired: {self.stats['repaired']}")
        self.logger.info(f"Failed: {self.stats['failed']}")
        self.logger.info(f"Skipped: {self.stats['skipped']}")
        self.logger.info("=" * 70)
        
        return self.stats
    
    def debug(self, message: str):
        """Log a debug message."""
        self.logger.debug(message)
    
    def info(self, message: str):
        """Log an info message."""
        self.logger.info(message)
    
    def warning(self, message: str):
        """Log a warning message."""
        self.logger.warning(message)
    
    def error(self, message: str):
        """Log an error message."""
        self.logger.error(message)
    
    def critical(self, message: str):
        """Log a critical message."""
        self.logger.critical(message)
