"""
Debug Logger Module

Provides centralized debug logging that writes to both console and file.
"""

import os
from pathlib import Path
from datetime import datetime


def _resolve_debug_file() -> Path:
    """Locate emdsDebug.txt in the shared EMDS workspace (next to the master DB)."""
    try:
        from .app_paths import resolve_workspace_paths
        return resolve_workspace_paths().projects_dir / "emdsDebug.txt"
    except Exception:
        pass
    # Engine subprocesses inherit this from the plugin (app_paths.ensure_workspace).
    metadata_db = os.environ.get("EMDS_METADATA_DB_PATH")
    if metadata_db:
        return Path(metadata_db).parent / "emdsDebug.txt"
    # ponytail: folder name duplicated from app_paths.EMDS_PROJECTS_FOLDER_NAME —
    # importing it pulls Qt via qt_compat; rename both if the folder ever changes.
    return Path.home() / "Documents" / "EmdsProjects" / "emdsDebug.txt"


class DebugLogger:
    """Logs debug messages to both console and file"""

    DEBUG_FILE = _resolve_debug_file()

    def __init__(self):
        """Initialize debug logger"""
        self._ensure_debug_file_exists()
        self.debug("Debug logger initialized", {"debug_file": str(self.DEBUG_FILE)})

    @staticmethod
    def _ensure_debug_file_exists():
        """Create debug file and directory if they don't exist"""
        try:
            DebugLogger.DEBUG_FILE.parent.mkdir(parents=True, exist_ok=True)
            # Create file if it doesn't exist
            if not DebugLogger.DEBUG_FILE.exists():
                DebugLogger.DEBUG_FILE.touch()
        except Exception as e:
            print(f"Warning: Could not create debug file: {e}")

    @staticmethod
    def log(message: str):
        """
        Log a message to both console and file

        Args:
            message: Message to log
        """
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        formatted_message = f"[{timestamp}] {message}"

        # Print to console
        print(formatted_message)

        # Write to file
        try:
            with open(DebugLogger.DEBUG_FILE, 'a') as f:
                f.write(formatted_message + "\n")
                f.flush()
        except Exception as e:
            print(f"Warning: Could not write to debug file: {e}")

    @staticmethod
    def section(title: str):
        """
        Log a section separator

        Args:
            title: Section title
        """
        separator = "=" * 80
        DebugLogger.log(separator)
        DebugLogger.log(title)
        DebugLogger.log(separator)

    @staticmethod
    def debug(title: str, details: dict = None):
        """
        Log a debug step with optional details

        Args:
            title: Title of debug step
            details: Optional dictionary of details to log
        """
        DebugLogger.log(f"DEBUG: {title}")
        if details:
            for key, value in details.items():
                DebugLogger.log(f"  {key}: {value}")

    @staticmethod
    def error(title: str, details: dict = None):
        """
        Log an error with optional details

        Args:
            title: Error title
            details: Optional dictionary of details to log
        """
        DebugLogger.log(f"ERROR: {title}")
        if details:
            for key, value in details.items():
                DebugLogger.log(f"  {key}: {value}")

    @staticmethod
    def warning(title: str, details: dict = None):
        """
        Log a warning with optional details

        Args:
            title: Warning title
            details: Optional dictionary of details to log
        """
        DebugLogger.log(f"WARNING: {title}")
        if details:
            for key, value in details.items():
                DebugLogger.log(f"  {key}: {value}")

    @staticmethod
    def success(title: str, details: dict = None):
        """
        Log a success message with optional details

        Args:
            title: Success title
            details: Optional dictionary of details to log
        """
        DebugLogger.log(f"✓ SUCCESS: {title}")
        if details:
            for key, value in details.items():
                DebugLogger.log(f"  {key}: {value}")

    @staticmethod
    def clear_log():
        """Clear the debug log file"""
        try:
            with open(DebugLogger.DEBUG_FILE, 'w') as f:
                f.write("")
            print(f"Debug log cleared: {DebugLogger.DEBUG_FILE}")
        except Exception as e:
            print(f"Error clearing debug log: {e}")


# Global logger instance
_logger = DebugLogger()


def log(message: str):
    """Convenience function to log message"""
    _logger.log(message)


def section(title: str):
    """Convenience function to log section"""
    _logger.section(title)


def debug(title: str, details: dict = None):
    """Convenience function to log debug"""
    _logger.debug(title, details)


def error(title: str, details: dict = None):
    """Convenience function to log error"""
    _logger.error(title, details)


def warning(title: str, details: dict = None):
    """Convenience function to log warning"""
    _logger.warning(title, details)


def success(title: str, details: dict = None):
    """Convenience function to log success"""
    _logger.success(title, details)


def clear_log():
    """Convenience function to clear log"""
    _logger.clear_log()
