/**
 * GrammarAnalysisModule - Open grammar correction with AI feedback
 * Presents grammar exercises with open correction fields, validates using real AI
 * Implements DRSExerciseInterface for strict contract enforcement
 */

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

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

        // Validate dependencies
        if (!orchestrator || !llmValidator || !prerequisiteEngine || !contextMemory) {
            throw new Error('GrammarAnalysisModule 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.currentSentences = [];
        this.sentenceIndex = 0;
        this.userCorrections = [];
        this.validationInProgress = false;
        this.lastValidationResult = null;

        // Configuration
        this.config = {
            requiredProvider: 'openai', // Grammar analysis needs precision
            model: 'gpt-4o-mini',
            temperature: 0.1, // Very low for grammar precision
            maxTokens: 800,
            timeout: 45000,
            sentencesPerExercise: 3, // Number of sentences to correct
            showOriginalSentence: true, // Keep original visible during correction
            allowMultipleAttempts: true,
            correctnessThreshold: 0.8 // Minimum score to consider correct
        };

        // Progress tracking
        this.progress = {
            sentencesCompleted: 0,
            sentencesCorrect: 0,
            averageAccuracy: 0,
            grammarRulesLearned: new Set(),
            commonMistakes: new Set(),
            totalTimeSpent: 0,
            lastActivity: null,
            improvementAreas: []
        };

        // UI elements cache
        this.elements = {
            sentenceContainer: null,
            originalSentence: null,
            correctionArea: null,
            submitButton: null,
            feedbackContainer: null,
            progressIndicator: null,
            rulesPanel: null
        };
    }

    /**
     * Check if module can run with current content
     */
    canRun(prerequisites, chapterContent) {
        // Check if we have grammar content or can generate it
        const hasGrammarContent = chapterContent &&
            (chapterContent.grammar || chapterContent.sentences || chapterContent.texts);

        if (!hasGrammarContent) {
            console.log('❌ GrammarAnalysisModule: No grammar content available');
            return false;
        }

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

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

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

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

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

            // Prepare grammar sentences
            await this._prepareSentences();

            // Create UI layout
            this._createUI();

            // Show first sentence
            this._displayCurrentSentence();

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

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

    /**
     * Validate user correction with AI
     */
    async validate(userCorrection, context) {
        console.log('🔍 GrammarAnalysisModule: Validating grammar correction');

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

        const originalSentence = this.currentSentences[this.sentenceIndex];

        // Basic input validation
        if (!userCorrection || userCorrection.trim().length === 0) {
            return {
                success: false,
                score: 0,
                feedback: 'Please provide a correction for the sentence.',
                suggestions: ['Read the sentence carefully', 'Look for grammar errors', 'Make your corrections']
            };
        }

        // Check if user actually made changes
        if (userCorrection.trim() === originalSentence.incorrect.trim()) {
            return {
                success: false,
                score: 0,
                feedback: 'You haven\'t made any changes to the original sentence. Please identify and correct the grammar errors.',
                suggestions: [
                    'Look for verb tense errors',
                    'Check subject-verb agreement',
                    'Review word order',
                    'Check for missing or extra words'
                ]
            };
        }

        this.validationInProgress = true;

        try {
            // Prepare context for grammar validation
            const grammarContext = {
                originalSentence: originalSentence.incorrect,
                correctSentence: originalSentence.correct || null,
                userCorrection: userCorrection.trim(),
                grammarRule: originalSentence.rule || null,
                difficulty: this.currentExerciseData.difficulty || 'medium',
                language: 'English',
                errorType: originalSentence.errorType || 'general',
                ...context
            };

            // Use LLMValidator for grammar analysis
            const result = await this.llmValidator.validateGrammar(
                userCorrection.trim(),
                grammarContext
            );

            // Process and enhance the result
            const enhancedResult = this._processGrammarResult(result, userCorrection, originalSentence);

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

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

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

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

        } finally {
            this.validationInProgress = false;
        }
    }

    /**
     * Get current progress
     */
    getProgress() {
        return {
            ...this.progress,
            currentSentence: this.sentenceIndex + 1,
            totalSentences: this.currentSentences.length,
            moduleType: 'grammar-analysis',
            completionRate: this._calculateCompletionRate(),
            accuracyRate: this.progress.sentencesCompleted > 0 ?
                this.progress.sentencesCorrect / this.progress.sentencesCompleted : 0
        };
    }

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

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

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

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

    /**
     * Get module metadata
     */
    getMetadata() {
        return {
            name: 'GrammarAnalysisModule',
            version: '1.0.0',
            description: 'Open grammar correction with AI feedback',
            author: 'DRS System',
            capabilities: [
                'grammar-correction',
                'ai-validation',
                'rule-explanation',
                'mistake-analysis',
                'progress-tracking'
            ],
            requiredServices: ['llmValidator', 'orchestrator', 'prerequisiteEngine', 'contextMemory'],
            supportedLanguages: ['English'],
            exerciseTypes: ['error-correction', 'sentence-improvement', 'grammar-rules']
        };
    }

    // Private methods

    async _prepareSentences() {
        // Extract or generate grammar sentences
        if (this.currentExerciseData.sentences && this.currentExerciseData.sentences.length > 0) {
            // Use provided sentences
            this.currentSentences = this.currentExerciseData.sentences.slice(0, this.config.sentencesPerExercise);
        } else if (this.currentExerciseData.grammar && this.currentExerciseData.grammar.length > 0) {
            // Use grammar exercises
            this.currentSentences = this.currentExerciseData.grammar.slice(0, this.config.sentencesPerExercise);
        } else {
            // Generate sentences using AI
            await this._generateSentencesWithAI();
        }

        // Ensure we have the required format
        this.currentSentences = this.currentSentences.map(sentence => {
            if (typeof sentence === 'string') {
                return {
                    incorrect: sentence,
                    rule: 'Grammar correction',
                    errorType: 'general'
                };
            }
            return {
                incorrect: sentence.incorrect || sentence.text || sentence,
                correct: sentence.correct || null,
                rule: sentence.rule || 'Grammar correction',
                errorType: sentence.errorType || sentence.type || 'general',
                explanation: sentence.explanation || null
            };
        });

        console.log('📚 Grammar sentences prepared:', this.currentSentences.length);
    }

    async _generateSentencesWithAI() {
        // Use the orchestrator's IAEngine to generate grammar exercises
        try {
            const difficulty = this.currentExerciseData.difficulty || 'medium';
            const topic = this.currentExerciseData.topic || 'general grammar';

            const prompt = `Generate 3 grammar correction exercises for ${difficulty} level English learners.

Topic focus: ${topic}
Requirements:
- Create sentences with common grammar mistakes that students need to correct
- Include variety: verb tenses, subject-verb agreement, word order, articles, etc.
- Make errors realistic but clear
- Suitable for ${difficulty} level
- Each sentence should have 1-2 clear grammar errors

Return ONLY valid JSON:
[
    {
        "incorrect": "She don't likes to swimming in the cold water",
        "errorType": "verb-agreement",
        "rule": "Subject-verb agreement and gerund usage",
        "explanation": "Use 'doesn't' with third person singular and 'like swimming' not 'likes to swimming'"
    }
]`;

            const sharedServices = this.orchestrator.getSharedServices();
            if (sharedServices && sharedServices.iaEngine) {
                const result = await sharedServices.iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are a grammar expert. Create realistic grammar mistakes for students to correct.',
                    temperature: 0.3
                });

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

        // Fallback: basic grammar sentences
        this.currentSentences = [
            {
                incorrect: "She don't like to go shopping on weekends.",
                errorType: "verb-agreement",
                rule: "Subject-verb agreement",
                explanation: "Use 'doesn't' with third person singular subjects"
            },
            {
                incorrect: "I have been living here since five years.",
                errorType: "preposition",
                rule: "Prepositions with time expressions",
                explanation: "Use 'for' with duration, 'since' with point in time"
            },
            {
                incorrect: "The book what I reading is very interesting.",
                errorType: "relative-pronoun",
                rule: "Relative pronouns and present continuous",
                explanation: "Use 'that/which' as relative pronoun and 'am reading' for present continuous"
            }
        ];
    }

    _createUI() {
        const container = this.container;

        container.innerHTML = `
            <div class="grammar-analysis-module">
                <div class="progress-indicator" id="progressIndicator">
                    Sentence <span id="currentSentence">1</span> of <span id="totalSentences">${this.currentSentences.length}</span>
                </div>

                <div class="sentence-display" id="sentenceContainer">
                    <h3>🔍 Find and Correct the Grammar Errors</h3>
                    <div class="original-sentence" id="originalSentence"></div>
                    <div class="error-info" id="errorInfo"></div>
                </div>

                <div class="correction-section">
                    <h3>✏️ Your Correction</h3>
                    <div class="correction-container">
                        <textarea
                            id="correctionArea"
                            placeholder="Type the corrected sentence here..."
                            rows="3"
                        ></textarea>
                        <div class="correction-tips">
                            <strong>💡 Tips:</strong> Look for verb tenses, subject-verb agreement, word order, articles, and prepositions
                        </div>
                    </div>
                    <button id="submitButton" class="submit-correction" disabled>
                        ✅ Check My Correction
                    </button>
                </div>

                <div class="feedback-section" id="feedbackContainer" style="display: none;">
                    <h3>📋 Grammar Analysis</h3>
                    <div class="feedback-content" id="feedbackContent"></div>
                    <div class="grammar-rules" id="grammarRules"></div>
                    <div class="action-buttons" id="actionButtons"></div>
                </div>
            </div>
        `;

        // Cache elements
        this.elements = {
            sentenceContainer: container.querySelector('#sentenceContainer'),
            originalSentence: container.querySelector('#originalSentence'),
            correctionArea: container.querySelector('#correctionArea'),
            submitButton: container.querySelector('#submitButton'),
            feedbackContainer: container.querySelector('#feedbackContainer'),
            progressIndicator: container.querySelector('#progressIndicator')
        };

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

    _displayCurrentSentence() {
        const sentence = this.currentSentences[this.sentenceIndex];

        // Update sentence display
        this.elements.originalSentence.innerHTML = `
            <div class="sentence-text">"${sentence.incorrect}"</div>
        `;

        // Update error info
        const errorInfo = document.getElementById('errorInfo');
        if (sentence.rule || sentence.errorType) {
            errorInfo.innerHTML = `
                <div class="error-type">
                    <strong>Focus:</strong> ${sentence.rule || sentence.errorType}
                </div>
            `;
        }

        // Update progress
        document.getElementById('currentSentence').textContent = this.sentenceIndex + 1;
        document.getElementById('totalSentences').textContent = this.currentSentences.length;

        // Reset correction area
        this.elements.correctionArea.value = sentence.incorrect; // Start with original sentence
        this.elements.correctionArea.disabled = false;
        this.elements.submitButton.disabled = true;

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

        // Focus on correction area
        setTimeout(() => this.elements.correctionArea.focus(), 100);
    }

    _handleInputChange() {
        const originalSentence = this.currentSentences[this.sentenceIndex].incorrect;
        const userInput = this.elements.correctionArea.value.trim();

        // Enable submit if user made changes
        const hasChanges = userInput !== originalSentence && userInput.length > 0;
        this.elements.submitButton.disabled = !hasChanges;
    }

    async _handleSubmit() {
        const userCorrection = this.elements.correctionArea.value.trim();
        const originalSentence = this.currentSentences[this.sentenceIndex];

        if (!userCorrection || userCorrection === originalSentence.incorrect) {
            this._showValidationError('Please make corrections to the sentence.');
            return;
        }

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

        try {
            // Validate with AI
            const result = await this.validate(userCorrection, {
                expectedRule: originalSentence.rule,
                errorType: originalSentence.errorType
            });

            // Show feedback
            this._displayFeedback(result, originalSentence);

            // Store correction
            this.userCorrections[this.sentenceIndex] = {
                original: originalSentence.incorrect,
                userCorrection: userCorrection,
                result: result,
                timestamp: new Date().toISOString()
            };

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

        // Re-enable UI
        this.elements.correctionArea.disabled = false;
        this.elements.submitButton.textContent = '✅ Check My Correction';
        this._handleInputChange();
    }

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

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

        if (result.success && result.score >= this.config.correctnessThreshold) {
            feedbackHTML = `
                <div class="feedback-score">
                    <span class="score-label">Accuracy:</span>
                    <span class="score-value correct">${Math.round(result.score * 100)}%</span>
                </div>
                <div class="feedback-text correct">
                    <strong>✅ Excellent correction!</strong><br>
                    ${result.feedback}
                </div>
            `;
        } else {
            feedbackHTML = `
                <div class="feedback-score">
                    <span class="score-label">Accuracy:</span>
                    <span class="score-value needs-work">${Math.round((result.score || 0) * 100)}%</span>
                </div>
                <div class="feedback-text needs-improvement">
                    <strong>📝 Needs improvement:</strong><br>
                    ${result.feedback}
                </div>
            `;
        }

        feedbackContent.innerHTML = feedbackHTML;

        // Show grammar rules and explanations
        let rulesHTML = '';
        if (originalSentence.rule) {
            rulesHTML += `
                <div class="grammar-rule">
                    <strong>📚 Grammar Rule:</strong> ${originalSentence.rule}
                </div>
            `;
        }

        if (result.explanation) {
            rulesHTML += `
                <div class="detailed-explanation">
                    <strong>💡 Explanation:</strong><br>
                    ${result.explanation}
                </div>
            `;
        }

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

        grammarRules.innerHTML = rulesHTML;

        // Create action buttons
        let buttonsHTML = '';

        if (this.config.allowMultipleAttempts && result.score < this.config.correctnessThreshold) {
            buttonsHTML += `<button class="retry-button" onclick="this.closest('.grammar-analysis-module').querySelector('#correctionArea').focus()">🔄 Try Again</button>`;
        }

        if (this.sentenceIndex < this.currentSentences.length - 1) {
            buttonsHTML += `<button class="next-button" onclick="this._nextSentence()">➡️ Next Sentence</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' });
    }

    _nextSentence() {
        if (this.sentenceIndex < this.currentSentences.length - 1) {
            this.sentenceIndex++;
            this._displayCurrentSentence();
        }
    }

    _finishExercise() {
        // Calculate final statistics
        const totalCorrect = this.userCorrections.filter(c =>
            c.result && c.result.score >= this.config.correctnessThreshold
        ).length;

        const completionData = {
            moduleType: 'grammar-analysis',
            corrections: this.userCorrections,
            progress: this.getProgress(),
            finalStats: {
                totalSentences: this.currentSentences.length,
                correctSentences: totalCorrect,
                accuracyRate: totalCorrect / this.currentSentences.length,
                grammarRulesLearned: this.progress.grammarRulesLearned.size,
                improvementAreas: this.progress.improvementAreas
            }
        };

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

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

    _processGrammarResult(result, userCorrection, originalSentence) {
        // Enhance the raw LLM result
        const enhanced = {
            ...result,
            inputLength: userCorrection.length,
            originalLength: originalSentence.incorrect.length,
            timestamp: new Date().toISOString(),
            moduleType: 'grammar-analysis',
            grammarRule: originalSentence.rule,
            errorType: originalSentence.errorType
        };

        return enhanced;
    }

    _updateProgress(result, originalSentence) {
        this.progress.sentencesCompleted++;
        this.progress.lastActivity = new Date().toISOString();

        // Count as correct if above threshold
        if (result.score >= this.config.correctnessThreshold) {
            this.progress.sentencesCorrect++;
        }

        // Update average accuracy
        const totalAccuracy = this.progress.averageAccuracy * (this.progress.sentencesCompleted - 1) + (result.score || 0);
        this.progress.averageAccuracy = totalAccuracy / this.progress.sentencesCompleted;

        // Track grammar rules learned
        if (originalSentence.rule) {
            this.progress.grammarRulesLearned.add(originalSentence.rule);
        }

        // Track improvement areas
        if (result.score < this.config.correctnessThreshold) {
            this.progress.improvementAreas.push(originalSentence.errorType || 'general');
        }
    }

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

    _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: #e74c3c; padding: 10px; margin: 10px 0; border: 1px solid #e74c3c; border-radius: 4px; background: #ffebee;';

        this.elements.correctionArea.parentNode.insertBefore(errorDiv, this.elements.correctionArea);

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

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

    async init(config = {}, content = {}) {
        this.config = { ...this.config, ...config };
        this.currentExerciseData = content;
        this.startTime = Date.now();
        this.initialized = true;
    }

    async render(container) {
        if (!this.initialized) throw new Error('GrammarAnalysisModule must be initialized before rendering');
        await this.present(container, this.currentExerciseData);
    }

    async destroy() {
        this.cleanup();
    }

    getResults() {
        const totalSentences = this.currentSentences.length;
        const correctedSentences = this.userCorrections.length;
        const correctSentences = this.progress.sentencesCorrect;
        const score = totalSentences > 0 ? Math.round((correctSentences / totalSentences) * 100) : 0;

        return {
            score,
            attempts: correctedSentences,
            timeSpent: this.startTime ? Date.now() - this.startTime : 0,
            completed: correctedSentences >= totalSentences,
            details: {
                totalSentences,
                correctedSentences,
                correctSentences,
                accuracy: this.progress.averageAccuracy,
                grammarRulesLearned: Array.from(this.progress.grammarRulesLearned),
                corrections: this.userCorrections
            }
        };
    }

    handleUserInput(event, data) {
        if (event && event.type === 'input') this._handleInputChange?.(event);
        if (event && event.type === 'click' && event.target.id === 'submitButton') this._handleSubmit?.(event);
    }

    async markCompleted(results) {
        const { score, details } = results || this.getResults();
        if (this.contextMemory) {
            this.contextMemory.recordInteraction({
                type: 'grammar-analysis',
                subtype: 'completion',
                content: { sentences: this.currentSentences },
                userResponse: this.userCorrections,
                validation: { score, accuracy: details.accuracy, grammarRulesLearned: details.grammarRulesLearned },
                context: { moduleType: 'grammar-analysis', totalSentences: details.totalSentences }
            });
        }
    }

    getExerciseType() {
        return 'grammar-analysis';
    }

    getExerciseConfig() {
        const sentenceCount = this.currentSentences ? this.currentSentences.length : this.config.sentencesPerExercise;
        return {
            type: this.getExerciseType(),
            difficulty: this.currentExerciseData?.difficulty || 'medium',
            estimatedTime: sentenceCount * 2, // 2 min per sentence
            prerequisites: [],
            metadata: { ...this.config, sentenceCount, requiresAI: true, model: this.config.model }
        };
    }
}

export default GrammarAnalysisModule;