/**
 * TextAnalysisModule - Open-text comprehension with AI validation
 * Presents text passages with open questions, validates free-text responses using AI
 * Implements DRSExerciseInterface for strict contract enforcement
 */

import DRSExerciseInterface from '../interfaces/DRSExerciseInterface.js';

class TextAnalysisModule extends DRSExerciseInterface {
    constructor(orchestrator, llmValidator, prerequisiteEngine, contextMemory) {
        super('TextAnalysisModule');

        // Validate dependencies
        if (!orchestrator || !llmValidator || !prerequisiteEngine || !contextMemory) {
            throw new Error('TextAnalysisModule requires all service dependencies');
        }

        this.orchestrator = orchestrator;
        this.llmValidator = llmValidator;
        this.prerequisiteEngine = prerequisiteEngine;
        this.contextMemory = contextMemory;

        // Module state
        this.initialized = false;
        this.container = null;
        this.currentExerciseData = null;
        this.currentText = null;
        this.currentQuestion = null;
        this.questionIndex = 0;
        this.userResponses = [];
        this.validationInProgress = false;
        this.lastValidationResult = null;

        // Configuration
        this.config = {
            requiredProvider: 'openai', // OpenAI for comprehensive text analysis
            model: 'gpt-4o-mini',
            temperature: 0.3, // Balanced creativity for nuanced feedback
            maxTokens: 1000, // More tokens for detailed feedback
            timeout: 60000, // Longer timeout for deep analysis
            questionsPerText: 2, // Fewer but deeper questions
            minResponseLength: 20, // Minimum response length in characters
            maxResponseLength: 500, // Maximum response length
            showTextDuringAnswer: true, // Keep text visible while answering
            allowMultipleAttempts: true // Allow user to revise answer
        };

        // Progress tracking
        this.progress = {
            textsCompleted: 0,
            questionsAnswered: 0,
            averageScore: 0,
            totalTimeSpent: 0,
            lastActivity: null,
            qualityMetrics: {
                insightfulness: 0,
                accuracy: 0,
                completeness: 0,
                clarity: 0
            }
        };

        // UI elements cache
        this.elements = {
            textContainer: null,
            questionContainer: null,
            responseArea: null,
            submitButton: null,
            feedbackContainer: null,
            progressIndicator: null
        };
    }

    /**
     * Check if module can run with current content
     */
    canRun(prerequisites, chapterContent) {
        // Check if we have text content to analyze
        if (!chapterContent || !chapterContent.texts || chapterContent.texts.length === 0) {
            console.log('❌ TextAnalysisModule: No text content available');
            return false;
        }

        // Check if LLM validator is available
        if (!this.llmValidator || !this.llmValidator.isAvailable()) {
            console.log('❌ TextAnalysisModule: LLM validator not available');
            return false;
        }

        console.log('✅ TextAnalysisModule: Can run with available text content');
        return true;
    }

    /**
     * Present exercise UI and content
     */
    async present(container, exerciseData) {
        console.log('📖 TextAnalysisModule: Starting presentation');

        this.container = container;
        this.currentExerciseData = exerciseData;

        try {
            // Clear container
            container.innerHTML = '';

            // Generate or extract text and questions
            await this._prepareContent();

            // Create UI layout
            this._createUI();

            // Show first question
            this._displayCurrentQuestion();

            this.initialized = true;
            console.log('✅ TextAnalysisModule: Presentation ready');

        } catch (error) {
            console.error('❌ TextAnalysisModule presentation failed:', error);
            this._showError('Failed to load text analysis exercise. Please try again.');
        }
    }

    /**
     * Validate user response with AI
     */
    async validate(userInput, context) {
        console.log('🔍 TextAnalysisModule: Validating user response');

        if (this.validationInProgress) {
            console.log('⏳ Validation already in progress');
            return this.lastValidationResult;
        }

        // Input validation
        if (!userInput || userInput.trim().length < this.config.minResponseLength) {
            return {
                success: false,
                score: 0,
                feedback: `Please provide a more detailed response (at least ${this.config.minResponseLength} characters).`,
                suggestions: ['Try to explain your reasoning', 'Include specific details from the text', 'Consider different perspectives']
            };
        }

        if (userInput.length > this.config.maxResponseLength) {
            return {
                success: false,
                score: 0,
                feedback: `Your response is too long. Please keep it under ${this.config.maxResponseLength} characters.`,
                suggestions: ['Focus on the main points', 'Be more concise', 'Remove unnecessary details']
            };
        }

        this.validationInProgress = true;

        try {
            // Prepare context for LLM validation
            const validationContext = {
                text: this.currentText,
                question: this.currentQuestion,
                userResponse: userInput.trim(),
                difficulty: this.currentExerciseData.difficulty || 'medium',
                language: 'English',
                expectations: context.expectations || 'Demonstrate understanding of the text',
                ...context
            };

            // Use LLMValidator for comprehensive text analysis
            const result = await this.llmValidator.validateTextComprehension(
                this.currentText,
                userInput.trim(),
                validationContext
            );

            // Process and enhance the result
            const enhancedResult = this._processValidationResult(result, userInput);

            // Store result and update progress
            this.lastValidationResult = enhancedResult;
            this._updateProgress(enhancedResult);

            console.log('✅ TextAnalysisModule: Validation completed', enhancedResult);
            return enhancedResult;

        } catch (error) {
            console.error('❌ TextAnalysisModule validation failed:', error);

            return {
                success: false,
                score: 0,
                feedback: 'Unable to analyze your response due to a technical issue. Please try again.',
                error: error.message,
                suggestions: ['Check your internet connection', 'Try a shorter response', 'Contact support if the problem persists']
            };

        } finally {
            this.validationInProgress = false;
        }
    }

    /**
     * Get current progress
     */
    getProgress() {
        return {
            ...this.progress,
            currentQuestion: this.questionIndex + 1,
            totalQuestions: this.currentExerciseData?.questions?.length || 0,
            moduleType: 'text-analysis',
            completionRate: this._calculateCompletionRate()
        };
    }

    /**
     * Clean up resources
     */
    cleanup() {
        // Remove event listeners
        if (this.elements.submitButton) {
            this.elements.submitButton.removeEventListener('click', this._handleSubmit.bind(this));
        }

        if (this.elements.responseArea) {
            this.elements.responseArea.removeEventListener('input', this._handleInputChange.bind(this));
        }

        // Clear references
        this.container = null;
        this.currentExerciseData = null;
        this.elements = {};
        this.initialized = false;

        console.log('🧹 TextAnalysisModule: Cleaned up');
    }

    /**
     * Get module metadata
     */
    getMetadata() {
        return {
            name: 'TextAnalysisModule',
            version: '1.0.0',
            description: 'Open-text comprehension with AI validation',
            author: 'DRS System',
            capabilities: [
                'open-text-response',
                'ai-validation',
                'detailed-feedback',
                'progress-tracking',
                'quality-assessment'
            ],
            requiredServices: ['llmValidator', 'orchestrator', 'prerequisiteEngine', 'contextMemory'],
            supportedLanguages: ['English', 'French'],
            exerciseTypes: ['comprehension', 'analysis', 'interpretation', 'critical-thinking']
        };
    }

    // Private methods

    async _prepareContent() {
        // Extract or generate text content
        if (this.currentExerciseData.text) {
            this.currentText = this.currentExerciseData.text;
        } else if (this.currentExerciseData.content) {
            this.currentText = this.currentExerciseData.content;
        } else {
            throw new Error('No text content provided for analysis');
        }

        // Extract or generate questions
        if (this.currentExerciseData.questions && this.currentExerciseData.questions.length > 0) {
            // Use provided questions
            this.questions = this.currentExerciseData.questions.map(q => ({
                question: q.question || q.text || q,
                expectations: q.expectations || 'Provide a thoughtful response based on the text',
                hints: q.hints || [],
                targetLength: q.targetLength || 100
            }));
        } else {
            // Generate questions using AI if none provided
            await this._generateQuestionsWithAI();
        }

        this.currentQuestion = this.questions[this.questionIndex];
        console.log('📚 Content prepared:', {
            textLength: this.currentText.length,
            questionsCount: this.questions.length
        });
    }

    async _generateQuestionsWithAI() {
        // Use the orchestrator's IAEngine to generate thoughtful open questions
        try {
            const prompt = `Generate 2 thoughtful, open-ended comprehension questions for this text that require analytical thinking:

Text: "${this.currentText}"

Requirements:
- Questions should test deep understanding, not just facts
- Encourage critical thinking and personal interpretation
- Suitable for ${this.currentExerciseData.difficulty || 'medium'} level
- Questions should require 2-3 sentence responses
- Focus on themes, implications, or connections

Return ONLY a JSON array:
[
    {
        "question": "What is the main message of this text and how does it relate to real life?",
        "expectations": "Student should identify the central theme and make connections to practical situations",
        "targetLength": 120
    }
]`;

            const sharedServices = this.orchestrator.getSharedServices();
            if (sharedServices && sharedServices.iaEngine) {
                const result = await sharedServices.iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are an expert educator. Create thoughtful questions that promote deep thinking.',
                    temperature: 0.4
                });

                if (result && result.content) {
                    try {
                        this.questions = JSON.parse(result.content);
                        console.log('✅ Generated questions with AI:', this.questions.length);
                        return;
                    } catch (parseError) {
                        console.warn('Failed to parse AI-generated questions');
                    }
                }
            }
        } catch (error) {
            console.warn('Failed to generate questions with AI:', error);
        }

        // Fallback: create basic questions
        this.questions = [
            {
                question: "What is the main idea or message of this text? Explain in your own words.",
                expectations: "Student should identify and explain the central theme or message",
                targetLength: 100
            },
            {
                question: "How does this text relate to real-world situations or your personal experience?",
                expectations: "Student should make connections between the text and practical applications",
                targetLength: 120
            }
        ];
    }

    _createUI() {
        const container = this.container;

        container.innerHTML = `
            <div class="text-analysis-module">
                <div class="progress-indicator" id="progressIndicator">
                    Question <span id="currentQ">1</span> of <span id="totalQ">${this.questions.length}</span>
                </div>

                <div class="text-display" id="textContainer">
                    <h3>📖 Text to Analyze</h3>
                    <div class="text-content">${this._formatText(this.currentText)}</div>
                </div>

                <div class="question-section" id="questionContainer">
                    <h3>💭 Your Analysis</h3>
                    <div class="question-text" id="questionText"></div>
                    <div class="response-area-container">
                        <textarea
                            id="responseArea"
                            placeholder="Type your thoughtful response here..."
                            rows="6"
                            maxlength="${this.config.maxResponseLength}"
                        ></textarea>
                        <div class="input-info">
                            <span id="charCount">0</span>/${this.config.maxResponseLength} characters
                            <span class="min-chars">(minimum ${this.config.minResponseLength})</span>
                        </div>
                    </div>
                    <button id="submitButton" class="submit-response" disabled>
                        🔍 Analyze My Response
                    </button>
                </div>

                <div class="feedback-section" id="feedbackContainer" style="display: none;">
                    <h3>🎯 AI Feedback</h3>
                    <div class="feedback-content" id="feedbackContent"></div>
                    <div class="action-buttons" id="actionButtons"></div>
                </div>
            </div>
        `;

        // Cache elements
        this.elements = {
            textContainer: container.querySelector('#textContainer'),
            questionContainer: container.querySelector('#questionContainer'),
            responseArea: container.querySelector('#responseArea'),
            submitButton: container.querySelector('#submitButton'),
            feedbackContainer: container.querySelector('#feedbackContainer'),
            progressIndicator: container.querySelector('#progressIndicator')
        };

        // Add event listeners
        this.elements.responseArea.addEventListener('input', this._handleInputChange.bind(this));
        this.elements.submitButton.addEventListener('click', this._handleSubmit.bind(this));
    }

    _displayCurrentQuestion() {
        const question = this.questions[this.questionIndex];

        // Update question text
        document.getElementById('questionText').textContent = question.question;

        // Update progress
        document.getElementById('currentQ').textContent = this.questionIndex + 1;
        document.getElementById('totalQ').textContent = this.questions.length;

        // Reset response area
        this.elements.responseArea.value = '';
        this.elements.responseArea.disabled = false;
        this.elements.submitButton.disabled = true;

        // Hide previous feedback
        this.elements.feedbackContainer.style.display = 'none';

        this._updateCharCount();
    }

    _handleInputChange() {
        this._updateCharCount();
        this._updateSubmitButton();
    }

    _updateCharCount() {
        const count = this.elements.responseArea.value.length;
        document.getElementById('charCount').textContent = count;

        // Update styling based on length
        const charCountEl = document.getElementById('charCount');
        if (count < this.config.minResponseLength) {
            charCountEl.style.color = '#ff6b6b';
        } else if (count > this.config.maxResponseLength * 0.9) {
            charCountEl.style.color = '#ff9f43';
        } else {
            charCountEl.style.color = '#2ed573';
        }
    }

    _updateSubmitButton() {
        const responseLength = this.elements.responseArea.value.trim().length;
        const isValid = responseLength >= this.config.minResponseLength &&
                       responseLength <= this.config.maxResponseLength;

        this.elements.submitButton.disabled = !isValid;
    }

    async _handleSubmit() {
        const userResponse = this.elements.responseArea.value.trim();

        if (!userResponse || userResponse.length < this.config.minResponseLength) {
            this._showValidationError('Please provide a more detailed response.');
            return;
        }

        // Disable UI during validation
        this.elements.responseArea.disabled = true;
        this.elements.submitButton.disabled = true;
        this.elements.submitButton.textContent = '🔄 Analyzing...';

        try {
            // Validate with AI
            const result = await this.validate(userResponse, {
                expectations: this.currentQuestion.expectations,
                targetLength: this.currentQuestion.targetLength
            });

            // Show feedback
            this._displayFeedback(result);

            // Store response
            this.userResponses[this.questionIndex] = {
                question: this.currentQuestion.question,
                response: userResponse,
                result: result,
                timestamp: new Date().toISOString()
            };

        } catch (error) {
            console.error('Validation error:', error);
            this._showValidationError('Failed to analyze your response. Please try again.');
        }

        // Re-enable UI
        this.elements.responseArea.disabled = false;
        this.elements.submitButton.textContent = '🔍 Analyze My Response';
        this._updateSubmitButton();
    }

    _displayFeedback(result) {
        const feedbackContent = document.getElementById('feedbackContent');
        const actionButtons = document.getElementById('actionButtons');

        // Format feedback based on result
        let feedbackHTML = '';

        if (result.success) {
            feedbackHTML = `
                <div class="feedback-score">
                    <span class="score-label">Quality Score:</span>
                    <span class="score-value">${Math.round(result.score * 100)}%</span>
                </div>
                <div class="feedback-text positive">
                    <strong>✅ Good analysis!</strong><br>
                    ${result.feedback}
                </div>
            `;
        } else {
            feedbackHTML = `
                <div class="feedback-text needs-improvement">
                    <strong>💡 Room for improvement:</strong><br>
                    ${result.feedback}
                </div>
            `;
        }

        if (result.suggestions && result.suggestions.length > 0) {
            feedbackHTML += `
                <div class="suggestions">
                    <strong>💭 Suggestions for improvement:</strong>
                    <ul>
                        ${result.suggestions.map(s => `<li>${s}</li>`).join('')}
                    </ul>
                </div>
            `;
        }

        feedbackContent.innerHTML = feedbackHTML;

        // Create action buttons
        let buttonsHTML = '';

        if (this.config.allowMultipleAttempts && !result.success) {
            buttonsHTML += `<button class="retry-button" onclick="this.closest('.text-analysis-module').querySelector('#responseArea').focus()">🔄 Revise Answer</button>`;
        }

        if (this.questionIndex < this.questions.length - 1) {
            buttonsHTML += `<button class="next-button" onclick="this._nextQuestion()">➡️ Next Question</button>`;
        } else {
            buttonsHTML += `<button class="finish-button" onclick="this._finishExercise()">🎉 Finish Exercise</button>`;
        }

        actionButtons.innerHTML = buttonsHTML;

        // Show feedback section
        this.elements.feedbackContainer.style.display = 'block';
        this.elements.feedbackContainer.scrollIntoView({ behavior: 'smooth' });
    }

    _nextQuestion() {
        if (this.questionIndex < this.questions.length - 1) {
            this.questionIndex++;
            this.currentQuestion = this.questions[this.questionIndex];
            this._displayCurrentQuestion();
        }
    }

    _finishExercise() {
        // Emit completion event
        const completionData = {
            moduleType: 'text-analysis',
            responses: this.userResponses,
            progress: this.getProgress(),
            totalTimeSpent: this.progress.totalTimeSpent
        };

        // Use orchestrator to handle completion
        if (this.orchestrator && this.orchestrator.handleExerciseCompletion) {
            this.orchestrator.handleExerciseCompletion(completionData);
        }

        console.log('🎉 TextAnalysisModule: Exercise completed', completionData);
    }

    _processValidationResult(result, userInput) {
        // Enhance the raw LLM result with module-specific processing
        const enhanced = {
            ...result,
            inputLength: userInput.length,
            timestamp: new Date().toISOString(),
            moduleType: 'text-analysis'
        };

        // Calculate quality metrics if not provided
        if (!enhanced.qualityMetrics) {
            enhanced.qualityMetrics = this._calculateQualityMetrics(result, userInput);
        }

        return enhanced;
    }

    _calculateQualityMetrics(result, userInput) {
        // Simple quality assessment based on response characteristics
        const length = userInput.length;
        const score = result.score || 0;

        return {
            insightfulness: Math.min(score + (length > 80 ? 0.1 : 0), 1),
            accuracy: score,
            completeness: length >= this.config.minResponseLength ? score : score * 0.7,
            clarity: userInput.split('.').length > 1 ? score : score * 0.8
        };
    }

    _updateProgress(result) {
        this.progress.questionsAnswered++;
        this.progress.lastActivity = new Date().toISOString();

        // Update average score
        const totalScore = this.progress.averageScore * (this.progress.questionsAnswered - 1) + (result.score || 0);
        this.progress.averageScore = totalScore / this.progress.questionsAnswered;

        // Update quality metrics
        if (result.qualityMetrics) {
            Object.keys(result.qualityMetrics).forEach(metric => {
                this.progress.qualityMetrics[metric] =
                    (this.progress.qualityMetrics[metric] + result.qualityMetrics[metric]) / 2;
            });
        }
    }

    _calculateCompletionRate() {
        if (!this.questions || this.questions.length === 0) return 0;
        return (this.questionIndex + 1) / this.questions.length;
    }

    _formatText(text) {
        // Simple text formatting for better readability
        return text
            .split('\n\n')
            .map(paragraph => `<p>${paragraph.trim()}</p>`)
            .join('');
    }

    _showError(message) {
        this.container.innerHTML = `
            <div class="error-message">
                <h3>❌ Error</h3>
                <p>${message}</p>
                <button onclick="location.reload()">🔄 Try Again</button>
            </div>
        `;
    }

    _showValidationError(message) {
        // Show temporary error message
        const errorDiv = document.createElement('div');
        errorDiv.className = 'validation-error';
        errorDiv.textContent = message;
        errorDiv.style.cssText = 'color: #ff6b6b; padding: 10px; margin: 10px 0; border: 1px solid #ff6b6b; border-radius: 4px; background: #fff5f5;';

        this.elements.questionContainer.insertBefore(errorDiv, this.elements.responseArea.parentNode);

        setTimeout(() => errorDiv.remove(), 5000);
    }

    // ========================================
    // DRSExerciseInterface REQUIRED METHODS
    // ========================================

    /**
     * Initialize the exercise module
     * @param {Object} config - Exercise configuration
     * @param {Object} content - Exercise content data
     * @returns {Promise<void>}
     */
    async init(config = {}, content = {}) {
        console.log('📖 Initializing TextAnalysisModule...');

        // Merge provided config with defaults
        this.config = {
            ...this.config,
            ...config
        };

        // Store content
        this.currentExerciseData = content;
        this.startTime = Date.now();
        this.initialized = true;

        console.log('✅ TextAnalysisModule initialized');
    }

    /**
     * Render the exercise UI
     * @param {HTMLElement} container - Container element to render into
     * @returns {Promise<void>}
     */
    async render(container) {
        if (!this.initialized) {
            throw new Error('TextAnalysisModule must be initialized before rendering');
        }

        // Use existing present() logic
        await this.present(container, this.currentExerciseData);
    }

    /**
     * Clean up and destroy the exercise
     * @returns {Promise<void>}
     */
    async destroy() {
        console.log('🧹 Destroying TextAnalysisModule...');

        // Use existing cleanup
        this.cleanup();

        console.log('✅ TextAnalysisModule destroyed');
    }

    /**
     * Get exercise results and statistics
     * @returns {Object} - Results data
     */
    getResults() {
        const totalQuestions = this.questions ? this.questions.length : 0;
        const answeredQuestions = this.userResponses.length;
        const averageScore = this.progress.averageScore;
        const timeSpent = this.startTime ? Date.now() - this.startTime : 0;

        return {
            score: Math.round(averageScore * 100),
            attempts: answeredQuestions,
            timeSpent,
            completed: answeredQuestions >= totalQuestions,
            details: {
                totalQuestions,
                answeredQuestions,
                averageScore,
                qualityMetrics: this.progress.qualityMetrics,
                responses: this.userResponses
            }
        };
    }

    /**
     * Handle user input during exercise
     * @param {Event} event - User input event
     * @param {*} data - Input data
     * @returns {void}
     */
    handleUserInput(event, data) {
        // Delegate to existing handlers
        if (event && event.type) {
            switch (event.type) {
                case 'input':
                    this._handleInputChange(event);
                    break;
                case 'click':
                    if (event.target.id === 'submitButton') {
                        this._handleSubmit(event);
                    }
                    break;
            }
        }
    }

    /**
     * Mark exercise as completed and save progress
     * @param {Object} results - Exercise results
     * @returns {Promise<void>}
     */
    async markCompleted(results) {
        console.log('💾 Marking TextAnalysisModule as completed...');

        const { score, details } = results || this.getResults();

        // Save completion metadata
        if (this.contextMemory) {
            this.contextMemory.recordInteraction({
                type: 'text-analysis',
                subtype: 'completion',
                content: {
                    text: this.currentText,
                    questions: this.questions
                },
                userResponse: this.userResponses,
                validation: {
                    score,
                    averageScore: details.averageScore,
                    qualityMetrics: details.qualityMetrics
                },
                context: {
                    moduleType: 'text-analysis',
                    totalQuestions: details.totalQuestions,
                    answeredQuestions: details.answeredQuestions
                }
            });
        }

        console.log('✅ TextAnalysisModule completion saved');
    }

    /**
     * Get exercise type identifier
     * @returns {string} - Exercise type
     */
    getExerciseType() {
        return 'text-analysis';
    }

    /**
     * Get exercise configuration
     * @returns {Object} - Configuration object
     */
    getExerciseConfig() {
        const questionCount = this.questions ? this.questions.length : 2;
        const estimatedTimePerQuestion = 3; // 3 minutes per question

        return {
            type: this.getExerciseType(),
            difficulty: this.currentExerciseData?.difficulty || 'medium',
            estimatedTime: questionCount * estimatedTimePerQuestion,
            prerequisites: [], // Text analysis requires no specific prerequisites
            metadata: {
                ...this.config,
                questionCount,
                textLength: this.currentText ? this.currentText.length : 0,
                requiresAI: true,
                model: this.config.model
            }
        };
    }
}

export default TextAnalysisModule;