/**
 * Debug Utilities Module for AI Interactive Fiction
 * Provides debugging and testing tools
 */
import { BaseModule } from './base-module.js';

export class DebugUtilsModule extends BaseModule {
    constructor() {
        super('debug-utils', 'Debug Utilities');
        
        // Declare dependencies explicitly
        this.dependencies = ['text-buffer', 'socket-client', 'tts-factory', 'ui-controller', 'game-loop'];
    }
    
    /**
     * Initialize the debug utilities module
     * @returns {boolean} - Success status
     */
    async initialize() {
        console.log('Debug Utilities: Initializing');
        
        // Make utilities available globally for console access
        window.DebugUtils = {
            testSocketConnection: this.testSocketConnection.bind(this),
            testTTS: this.testTTS.bind(this),
            forceReconnect: this.forceReconnect.bind(this)
        };
        
        console.log('Debug Utilities: Debug tools are now available via window.DebugUtils');
        this.isReady = true;
        return true;
    }
    
    /**
     * Test the socket connection
     * @returns {boolean} - Success status
     */
    testSocketConnection() {
        console.log("Debug: Testing socket connection");
        
        // Get the socket client module properly through dependency system
        const socketClient = this.getModule('socket-client');
        if (!socketClient) {
            console.error("Debug: SocketClient module not found");
            return false;
        }
        
        if (socketClient.isConnected) {
            console.log("Debug: Socket is connected");
            return true;
        } else {
            console.log("Debug: Socket is not connected, attempting connection");
            socketClient.connect();
            return false;
        }
    }
    
    /**
     * Test the TTS system
     * @param {string} text - Test text to speak
     * @returns {boolean} - Success status
     */
    testTTS(text = "This is a test of the text to speech system.") {
        console.log("Debug: Testing TTS with:", text);

        // Get the TTS factory properly through dependency system
        const ttsFactory = this.getModule('tts-factory');
        if (!ttsFactory) {
            console.error("Debug: TTS factory not found");
            return false;
        }

        const activeHandler = ttsFactory.getActiveHandler();
        if (!activeHandler) {
            console.error("Debug: No active TTS handler");
            return false;
        }

        // Speak the text
        ttsFactory.speak(text).then((result) => {
            console.log("Debug: TTS completed with result:", result);
        }).catch((error) => {
            console.error("Debug: TTS error:", error);
        });

        return true;
    }
    
    /**
     * Force all modules to reconnect
     * @returns {boolean} - Success status
     */
    forceReconnect() {
        console.log("Debug: Forcing module reconnection");
        
        // Get all required modules properly through dependency system
        const uiController = this.getModule('ui-controller');
        const socketClient = this.getModule('socket-client');
        const gameLoop = this.getModule('game-loop');
        const textBuffer = this.getModule('text-buffer');
        const ttsFactory = this.getModule('tts-factory');

        // Check if all modules are available
        if (!uiController || !socketClient || !gameLoop || !textBuffer || !ttsFactory) {
            console.error("Debug: One or more required modules not found");
            return false;
        }
        
        // UI Controller
        if (uiController.textBuffer === null) {
            uiController.textBuffer = textBuffer;
            console.log("Debug: Reconnected UI Controller to Text Buffer");
            
            // Reinitialize text buffer
            if (uiController.initializeTextBuffer) {
                uiController.initializeTextBuffer();
            }
        }
        
        if (uiController.ttsHandler === null) {
            uiController.ttsHandler = ttsHandler;
            console.log("Debug: Reconnected UI Controller to TTS Player");
        }
        
        // Socket Client
        if (socketClient.textBuffer === null) {
            socketClient.textBuffer = textBuffer;
            console.log("Debug: Reconnected Socket Client to Text Buffer");
        }
        
        // Game Loop
        if (gameLoop.uiController === null) {
            gameLoop.uiController = uiController;
            console.log("Debug: Reconnected Game Loop to UI Controller");
        }
        
        if (gameLoop.socketClient === null) {
            gameLoop.socketClient = socketClient;
            console.log("Debug: Reconnected Game Loop to Socket Client");
        }
        
        if (gameLoop.textBuffer === null) {
            gameLoop.textBuffer = textBuffer;
            console.log("Debug: Reconnected Game Loop to Text Buffer");
        }
        
        return true;
    }
}

// Register the module with the module registry
if (window.moduleRegistry) {
    try {
        const debugUtilsModule = new DebugUtilsModule();
        window.moduleRegistry.register(debugUtilsModule);
        console.log('Debug Utilities Module registered successfully');
    } catch (err) {
        console.error('Failed to register Debug Utilities Module:', err);
    }
} else {
    console.error('Module registry not available when attempting to register Debug Utilities Module');
}
