"""Logging configuration for migration tool."""

import logging
import sys
import threading
from datetime import datetime
from pathlib import Path


class MigrationLogger:
    """Manages logging for migration operations."""
    
    def __init__(self):
        self.log_file = None
        self._local = threading.local()
        self.logger = self._setup_logger()

    def set_prefix(self, prefix: str):
        """Set a thread-local prefix for log messages (e.g., collection name)."""
        self._local.prefix = prefix

    def clear_prefix(self):
        """Clear the thread-local prefix."""
        self._local.prefix = None

    def _format_message(self, message: str) -> str:
        """Prepend thread-local prefix if set."""
        prefix = getattr(self._local, 'prefix', None)
        if prefix:
            return f"{prefix} {message}"
        return message
        
    def _setup_logger(self) -> logging.Logger:
        """Configure logging with console and file handlers."""
        # Create logger
        logger = logging.getLogger('h2ogpte_migration')
        logger.setLevel(logging.DEBUG)  # Capture everything
        logger.handlers = []  # Clear any existing handlers
        
        # Create formatters
        console_formatter = logging.Formatter(
            '[%(asctime)s] %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        file_formatter = logging.Formatter(
            '[%(asctime)s] %(levelname)s: %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # Console handler - always show all logs (DEBUG level)
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(console_formatter)
        logger.addHandler(console_handler)
        
        # File handler - always DEBUG (full details)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.log_file = str(Path.cwd() / f"migration_{timestamp}.log")
        file_handler = logging.FileHandler(self.log_file)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(file_formatter)
        logger.addHandler(file_handler)
        
        return logger
    
    def info(self, message: str):
        """Log info message."""
        self.logger.info(self._format_message(message))

    def warning(self, message: str):
        """Log warning message."""
        self.logger.warning(self._format_message(message))

    def error(self, message: str):
        """Log error message."""
        self.logger.error(self._format_message(message))
    
    def separator(self, char: str = "=", length: int = 70):
        """Print a separator line."""
        self.info(char * length)
    
    def header(self, message: str):
        """Print a header with separators."""
        self.info("")
        self.separator()
        self.info(message)
        self.separator()
    
    def section(self, message: str):
        """Print a section header."""
        self.info("")
        self.info(f"=== {message} ===")
    
    def success(self, message: str):
        """Log success message with checkmark."""
        stripped = message.lstrip()
        indent = message[:len(message) - len(stripped)]
        # Prefix is applied by info/error, so pass the formatted message directly
        self.logger.info(self._format_message(f"{indent}✓ {stripped}"))

    def failure(self, message: str):
        """Log failure message with X mark."""
        stripped = message.lstrip()
        indent = message[:len(message) - len(stripped)]
        self.logger.error(self._format_message(f"{indent}✗ {stripped}"))
    
    def progress(self, current: int, total: int, item: str):
        """Log progress."""
        self.logger.info(self._format_message(f"[{current}/{total}] {item}"))
    
    def get_log_file(self) -> str:
        """Get the log file path."""
        return self.log_file or "migration.log"
