/**
 * LLMValidator - LLM integration service for exercise validation
 * Uses IAEngine for intelligent evaluation of all exercise types
 */

import IAEngine from './IAEngine.js';
import AIReportSystem from './AIReportSystem.js';

class LLMValidator {
    constructor(config = {}) {
        this.config = {
            provider: config.provider || 'openai',
            temperature: config.temperature || 0.3,
            maxTokens: config.maxTokens || 1000,
            timeout: config.timeout || 30000,
            debug: config.debug || false,
            enableReporting: config.enableReporting !== false, // Enabled by default
            ...config
        };

        // Initialize the IAEngine - DeepSeek as REAL AI fallback
        this.iaEngine = new IAEngine({
            defaultProvider: this.config.provider,
            fallbackProviders: ['deepseek'], // REAL AI FALLBACK ONLY
            timeout: this.config.timeout,
            debug: this.config.debug
        });

        // Initialize AI Report System
        this.reportSystem = new AIReportSystem({
            includeTimestamps: true,
            formatStyle: 'detailed',
            language: 'fr',
            includeScores: true
        });

        console.log('🧠 LLMValidator initialized with IAEngine and AI Report System');
    }

    /**
     * Start a new AI report session
     * @param {Object} sessionInfo - Session information
     * @returns {string} - Session ID
     */
    startReportSession(sessionInfo = {}) {
        if (!this.config.enableReporting) {
            return null;
        }
        return this.reportSystem.startSession(sessionInfo);
    }

    /**
     * End the current AI report session
     */
    endReportSession() {
        if (!this.config.enableReporting) {
            return;
        }
        this.reportSystem.endSession();
    }

    /**
     * Add AI response to the report system
     * @private
     */
    _addToReport(aiResponse, exerciseContext) {
        if (!this.config.enableReporting) {
            return;
        }
        this.reportSystem.addAIResponse(aiResponse, exerciseContext);
    }

    /**
     * Generate and export a report
     * @param {string} format - Report format ('text', 'html', 'json')
     * @param {string} filename - Optional filename
     * @returns {string} - Download URL
     */
    exportReport(format = 'text', filename = null) {
        if (!this.config.enableReporting) {
            throw new Error('Reporting is disabled');
        }
        return this.reportSystem.exportReport(null, format, filename);
    }

    /**
     * Get a formatted report as string
     * @param {string} format - Report format ('text', 'html', 'json')
     * @returns {string} - Formatted report
     */
    getReport(format = 'text') {
        if (!this.config.enableReporting) {
            throw new Error('Reporting is disabled');
        }
        return this.reportSystem.generateReport(null, format);
    }

    /**
     * Validate translation exercise
     * @param {string} originalText - Original text
     * @param {string} userAnswer - User's translation
     * @param {Object} context - Exercise context
     * @returns {Promise<ValidationResult>}
     */
    async validateTranslation(originalText, userAnswer, context = {}) {
        try {
            console.log(`🔍 Validating translation: "${originalText}" -> "${userAnswer}"`);

            const result = await this.iaEngine.validateTranslation(originalText, userAnswer, {
                exerciseType: context.exerciseType || 'vocabulary',
                targetLanguage: context.targetLanguage || 'French/Chinese',
                contextHistory: context.contextHistory || '',
                wordType: context.wordType || 'general'
            });

            // Add to AI report system
            this._addToReport(result, {
                exerciseType: 'vocabulary',
                originalContent: originalText,
                userAnswer: userAnswer,
                difficulty: context.difficulty,
                exerciseStep: context.exerciseStep
            });

            // Ensure backward compatibility with expected format
            return this._normalizeResult(result, 'translation');

        } catch (error) {
            console.error('❌ Translation validation error:', error);
            throw new Error(`Translation validation failed: ${error.message}. No fallback available.`);
        }
    }

    /**
     * Validate audio comprehension
     * @param {string} transcription - Audio transcription
     * @param {string} userAnswer - User's comprehension response
     * @param {Object} context - Exercise context
     * @returns {Promise<ValidationResult>}
     */
    async validateAudioComprehension(transcription, userAnswer, context = {}) {
        try {
            console.log(`🎵 Validating audio comprehension: "${transcription}" -> "${userAnswer}"`);

            const result = await this.iaEngine.validateComprehension(transcription, userAnswer, {
                exerciseType: 'audio',
                languageLevel: context.languageLevel || 'beginner'
            });

            // Add to AI report system
            this._addToReport(result, {
                exerciseType: 'audio',
                originalContent: transcription,
                userAnswer: userAnswer,
                difficulty: context.difficulty,
                exerciseStep: context.exerciseStep
            });

            return this._normalizeResult(result, 'audio');

        } catch (error) {
            console.error('❌ Audio comprehension validation error:', error);
            throw new Error(`Audio validation failed: ${error.message}. No fallback available.`);
        }
    }

    /**
     * Validate image description
     * @param {string} userAnswer - User's description
     * @param {Object} context - Exercise context with target vocabulary
     * @returns {Promise<ValidationResult>}
     */
    async validateImageDescription(userAnswer, context = {}) {
        try {
            console.log(`🖼️ Validating image description: "${userAnswer}"`);

            const prompt = `Evaluate image description:
- Student description: "${userAnswer}"
- Target vocabulary: ${JSON.stringify(context.targetVocabulary || {})}
- Exercise type: free description

Evaluate vocabulary usage, accuracy, and creativity.
Return JSON: {
    "score": 0-100,
    "correct": boolean,
    "feedback": "constructive feedback",
    "vocabularyUsed": ["words from target vocabulary used"],
    "creativityScore": 0-100
}`;

            const result = await this.iaEngine.validateEducationalContent(prompt, {
                preferredProvider: this.config.provider
            });

            return this._normalizeResult(result, 'image');

        } catch (error) {
            console.error('❌ Image description validation error:', error);
            throw new Error(`Image validation failed: ${error.message}. No fallback available.`);
        }
    }

    /**
     * Validate grammar exercise
     * @param {string} userAnswer - User's grammar response
     * @param {Object} context - Exercise context with grammar concepts
     * @returns {Promise<ValidationResult>}
     */
    async validateGrammar(userAnswer, context = {}) {
        try {
            console.log(`📝 Validating grammar: "${userAnswer}"`);

            const result = await this.iaEngine.validateGrammar(userAnswer, {
                grammarConcepts: context.grammarConcepts || {},
                languageLevel: context.languageLevel || 'beginner'
            });

            // Add to AI report system
            this._addToReport(result, {
                exerciseType: 'grammar',
                originalContent: context.grammarPrompt || '',
                userAnswer: userAnswer,
                difficulty: context.difficulty,
                exerciseStep: context.exerciseStep
            });

            return this._normalizeResult(result, 'grammar');

        } catch (error) {
            console.error('❌ Grammar validation error:', error);
            throw new Error(`Grammar validation failed: ${error.message}. No fallback available.`);
        }
    }

    /**
     * Validate text comprehension
     * @param {string} text - Original text
     * @param {string} userAnswer - User's comprehension response
     * @param {Object} context - Exercise context
     * @returns {Promise<ValidationResult>}
     */
    async validateTextComprehension(text, userAnswer, context = {}) {
        try {
            console.log(`📖 Validating text comprehension: "${text}" -> "${userAnswer}"`);

            const result = await this.iaEngine.validateComprehension(text, userAnswer, {
                exerciseType: 'text',
                contextHistory: context.contextHistory || ''
            });

            // Add to AI report system
            this._addToReport(result, {
                exerciseType: 'text',
                originalContent: text,
                userAnswer: userAnswer,
                difficulty: context.difficulty,
                exerciseStep: context.exerciseStep
            });

            return this._normalizeResult(result, 'text');

        } catch (error) {
            console.error('❌ Text comprehension validation error:', error);
            throw new Error(`Text comprehension validation failed: ${error.message}. No fallback available.`);
        }
    }

    /**
     * Normalize result to ensure backward compatibility
     * @private
     */
    _normalizeResult(result, exerciseType) {
        // If result is already in the expected format, return as is
        if (result.score !== undefined && result.correct !== undefined) {
            return {
                score: result.score,
                correct: result.correct,
                feedback: result.feedback || result.encouragement || 'Good effort!',
                timestamp: result.timestamp || new Date().toISOString(),
                provider: result.provider || 'unknown',
                cached: result.cached || false,

                // Include exercise-specific fields
                ...(exerciseType === 'translation' && {
                    keyPoints: result.keyPoints || [],
                    suggestions: result.suggestions || []
                }),
                ...(exerciseType === 'audio' && {
                    mainPointsUnderstood: result.mainPointsUnderstood || [],
                    missedPoints: result.missedPoints || []
                }),
                ...(exerciseType === 'image' && {
                    vocabularyUsed: result.vocabularyUsed || [],
                    creativityScore: result.creativityScore || 70
                }),
                ...(exerciseType === 'grammar' && {
                    grammarErrors: result.grammarErrors || [],
                    grammarStrengths: result.grammarStrengths || [],
                    suggestion: result.suggestion || null
                }),
                ...(exerciseType === 'text' && {
                    keyConceptsUnderstood: result.keyConceptsUnderstood || [],
                    missedPoints: result.missedPoints || []
                })
            };
        }

        // If result has unexpected format, try to extract content
        return {
            score: 75, // Default score
            correct: true,
            feedback: result.content || result.feedback || 'Response received',
            timestamp: new Date().toISOString(),
            provider: result.provider || 'unknown',
            cached: false
        };
    }

    /**
     * Generate fallback result when validation fails
     * @private
     */
    // FALLBACK SYSTEM COMPLETELY REMOVED
    // NO MORE FAKE RESPONSES - SYSTEM FAILS HARD IF AI NOT AVAILABLE

    /**
     * Get validation statistics
     */
    getStats() {
        return this.iaEngine.getStats();
    }

    /**
     * Clear cache
     */
    clearCache() {
        this.iaEngine.clearCache();
        console.log('🧹 LLMValidator cache cleared');
    }

    /**
     * Test connectivity
     */
    async testConnectivity() {
        try {
            const testResult = await this.iaEngine.testConnectivity();
            console.log('🧪 LLMValidator connectivity test:', testResult.success ? '✅ OK' : '❌ Failed');
            return testResult;
        } catch (error) {
            console.error('❌ LLMValidator connectivity test failed:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }

    /**
     * Cleanup resources
     */
    cleanup() {
        this.clearCache();
        console.log('🧹 LLMValidator cleaned up');
    }
}

export default LLMValidator;