/**
 * ContentLoader - Loads exercise content for DRS modules
 * Provides consistent interface for loading educational content
 */

import Module from './Module.js';

class ContentLoader extends Module {
    constructor(name, dependencies, config = {}) {
        super(name, ['eventBus']);

        if (!dependencies.eventBus) {
            throw new Error('ContentLoader requires EventBus dependency');
        }

        this._eventBus = dependencies.eventBus;
        this._config = {
            contentPath: config.contentPath || './content/',
            exerciseTypes: config.exerciseTypes || ['text', 'audio', 'image', 'grammar'],
            difficulties: config.difficulties || ['easy', 'medium', 'hard'],
            ...config
        };

        // Content cache
        this._contentCache = new Map();
        this._loadingPromises = new Map();

        Object.seal(this);
    }

    async init() {
        this._validateNotDestroyed();

        console.log('📚 Initializing ContentLoader...');

        // Set up event listeners
        this._eventBus.on('content:request', this._handleContentRequest.bind(this), this.name);
        this._eventBus.on('content:clear-cache', this._handleClearCache.bind(this), this.name);

        this._setInitialized();
        console.log('✅ ContentLoader initialized');
    }

    async destroy() {
        this._validateNotDestroyed();

        console.log('🧹 Destroying ContentLoader...');

        // Clear cache
        this._contentCache.clear();
        this._loadingPromises.clear();

        this._setDestroyed();
        console.log('✅ ContentLoader destroyed');
    }

    // Public API

    /**
     * Load exercise content
     * @param {Object} request - Content request
     * @returns {Promise<Object>} - Exercise content
     */
    async loadExercise(request) {
        this._validateInitialized();

        const { type, subtype, difficulty = 'medium', ...options } = request;

        console.log(`📖 Loading ${subtype || type} exercise (${difficulty})...`);

        try {
            // Generate cache key
            const cacheKey = this._generateCacheKey(request);

            // Check cache first
            if (this._contentCache.has(cacheKey)) {
                console.log(`💾 Found cached content for ${cacheKey}`);
                return this._contentCache.get(cacheKey);
            }

            // Check if already loading
            if (this._loadingPromises.has(cacheKey)) {
                console.log(`⏳ Already loading ${cacheKey}, waiting...`);
                return await this._loadingPromises.get(cacheKey);
            }

            // Load content
            const loadingPromise = this._loadContent(request);
            this._loadingPromises.set(cacheKey, loadingPromise);

            try {
                const content = await loadingPromise;

                // Cache the result
                this._contentCache.set(cacheKey, content);

                // Emit success event
                this._eventBus.emit('content:loaded', {
                    request,
                    content,
                    cached: false
                }, this.name);

                console.log(`✅ Content loaded: ${content.title || cacheKey}`);
                return content;

            } finally {
                this._loadingPromises.delete(cacheKey);
            }

        } catch (error) {
            console.error(`❌ Failed to load exercise content:`, error);

            // Emit error event
            this._eventBus.emit('content:error', {
                request,
                error: error.message
            }, this.name);

            throw error;
        }
    }

    /**
     * Get available content types
     * @returns {Object} - Available content information
     */
    getAvailableContent() {
        return {
            types: [...this._config.exerciseTypes],
            difficulties: [...this._config.difficulties],
            cached: this._contentCache.size,
            loading: this._loadingPromises.size
        };
    }

    /**
     * Clear content cache
     * @param {string} pattern - Optional pattern to match keys
     */
    clearCache(pattern = null) {
        if (pattern) {
            const regex = new RegExp(pattern);
            for (const [key] of this._contentCache) {
                if (regex.test(key)) {
                    this._contentCache.delete(key);
                }
            }
            console.log(`🧹 Cleared cache entries matching: ${pattern}`);
        } else {
            this._contentCache.clear();
            console.log('🧹 Cleared entire content cache');
        }

        this._eventBus.emit('content:cache-cleared', { pattern }, this.name);
    }

    // Private methods

    /**
     * Generate cache key for request
     * @param {Object} request - Content request
     * @returns {string} - Cache key
     * @private
     */
    _generateCacheKey(request) {
        const { type, subtype, difficulty, ...options } = request;
        const key = `${type}_${subtype || 'default'}_${difficulty}`;

        // Add hash of options if present
        if (Object.keys(options).length > 0) {
            const optionsHash = JSON.stringify(options);
            return `${key}_${this._simpleHash(optionsHash)}`;
        }

        return key;
    }

    /**
     * Simple hash function for options
     * @param {string} str - String to hash
     * @returns {string} - Hash
     * @private
     */
    _simpleHash(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32-bit integer
        }
        return Math.abs(hash).toString(16);
    }

    /**
     * Load content based on request type
     * @param {Object} request - Content request
     * @returns {Promise<Object>} - Content data
     * @private
     */
    async _loadContent(request) {
        const { subtype, bookId, chapterId } = request;

        // Load real content from file system first
        try {
            const contentPath = `/content/chapters/${chapterId || bookId}.json`;
            console.log(`📂 Loading content from: ${contentPath}`);

            const response = await fetch(contentPath);
            if (!response.ok) {
                console.warn(`❌ Failed to load content from ${contentPath}, using mock content`);
                return this._generateMockContent(request);
            }

            const realContent = await response.json();
            console.log('📚 Real content loaded from', contentPath);
            console.log('📊 Content structure:', {
                hasVocabulary: !!realContent.vocabulary,
                vocabularyCount: realContent.vocabulary ? Object.keys(realContent.vocabulary).length : 0,
                contentKeys: Object.keys(realContent)
            });

            // Generate exercise based on real content
            return this._generateExerciseFromRealContent(realContent, request);

        } catch (error) {
            console.warn(`❌ Error loading real content:`, error);
            console.log('🔄 Falling back to mock content');
            return this._generateMockContent(request);
        }
    }

    /**
     * Generate exercise from real content
     */
    _generateExerciseFromRealContent(realContent, request) {
        const { subtype, difficulty } = request;

        switch (subtype) {
            case 'text':
                // Text = vocabulary questions
                return this._generateTextFromRealContent(realContent, difficulty);
            case 'reading':
                // Reading = comprehension with real passages
                return this._generateReadingFromRealContent(realContent, difficulty);
            case 'audio':
                return this._generateAudioFromRealContent(realContent, difficulty);
            case 'image':
                return this._generateImageFromRealContent(realContent, difficulty);
            case 'grammar':
                return this._generateGrammarFromRealContent(realContent, difficulty);
            default:
                throw new Error(`Unknown exercise subtype: ${subtype}`);
        }
    }

    /**
     * Fallback to mock content
     */
    _generateMockContent(request) {
        const { subtype } = request;

        switch (subtype) {
            case 'text':
                return this._generateTextExercise(request);
            case 'audio':
                return this._generateAudioExercise(request);
            case 'image':
                return this._generateImageExercise(request);
            case 'grammar':
                return this._generateGrammarExercise(request);
            default:
                return this._generateDefaultExercise(request);
        }
    }

    // Real content generation methods

    /**
     * Generate text exercise from real content
     */
    async _generateTextFromRealContent(realContent, difficulty) {
        console.log('🎯 Generating text comprehension exercise with AI');

        // Check if we have sentences/texts for phrase-by-phrase analysis
        if (realContent.sentences && realContent.sentences.length > 0) {
            console.log('📖 Using sentences for phrase-by-phrase comprehension');
            return await this._generateSentenceComprehensionWithAI(realContent, difficulty);
        }

        // Check for dialogue texts
        if (realContent.dialogs && Object.keys(realContent.dialogs).length > 0) {
            console.log('💬 Using dialogue texts for comprehension');
            return await this._generateDialogTextComprehensionWithAI(realContent, difficulty);
        }

        // Fallback to vocabulary if no sentences/texts available
        console.log('📚 Falling back to vocabulary comprehension');
        return this._generateVocabularyTextExercise(realContent, difficulty);
    }

    _generateVocabularyTextExercise(realContent, difficulty) {
        console.log('📚 Available vocabulary:', realContent.vocabulary ? Object.keys(realContent.vocabulary).length : 'NONE');

        if (!realContent.vocabulary) {
            console.error('❌ No vocabulary found in content!');
            throw new Error('No vocabulary found in content');
        }

        const vocab = Object.entries(realContent.vocabulary);
        const numQuestions = this._getQuestionCount(difficulty);

        // Get or initialize used words for this content
        const contentId = realContent.id || 'unknown';
        if (!this._usedWords) {
            this._usedWords = new Map();
        }

        if (!this._usedWords.has(contentId)) {
            this._usedWords.set(contentId, new Set());
        }

        const usedWordsSet = this._usedWords.get(contentId);

        // Filter out already used words
        const availableWords = vocab.filter(([word]) => !usedWordsSet.has(word));

        // If we've used most words, reset the used set but keep the last few
        if (availableWords.length < numQuestions) {
            console.log('🔄 Resetting used words set, keeping recent ones');
            const recentWords = Array.from(usedWordsSet).slice(-Math.floor(vocab.length * 0.3));
            usedWordsSet.clear();
            recentWords.forEach(word => usedWordsSet.add(word));
        }

        // Select from available words
        const finalAvailable = vocab.filter(([word]) => !usedWordsSet.has(word));
        const selectedWords = this._selectRandomItems(finalAvailable, numQuestions);

        // Mark these words as used
        selectedWords.forEach(([word]) => usedWordsSet.add(word));

        console.log(`🎯 Selected ${selectedWords.length} NEW words for ${difficulty} difficulty (requested: ${numQuestions})`);
        console.log('📝 Selected words:', selectedWords.map(([word]) => word));

        const steps = selectedWords.map(([word, data], index) => ({
            id: `text-step-${index + 1}`,
            type: 'multiple-choice',
            content: {
                passage: `What does "${word}" mean?`,
                question: `Choose the correct definition for "${word}":`,
                options: this._generateTextOptions(word, data, vocab),
                correctAnswer: 0 // Real answer is always first, then shuffled
            },
            hint: `Remember: "${word}" is a ${data.type}. Pronunciation: ${data.pronunciation || 'N/A'}`
        }));

        // Shuffle options for each step
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `text-exercise-${Date.now()}`,
            type: 'text',
            title: `Vocabulary: ${realContent.name}`,
            description: `Learn vocabulary from ${realContent.name}`,
            difficulty,
            steps,
            metadata: {
                source: 'vocabulary-fallback',
                chapterInfo: realContent.metadata
            }
        };
    }

    _generateReadingFromRealContent(realContent, difficulty) {
        console.log('📖 Generating reading exercise from real content');

        // Priority 1: Check if reading exercises are defined in JSON
        if (realContent.exercises) {
            const readingExercise = this._findReadingExerciseInJSON(realContent.exercises);
            if (readingExercise) {
                console.log('✅ Using predefined reading exercises from JSON');
                return this._convertJSONExerciseToReading(readingExercise, realContent, difficulty);
            }
        }

        // Priority 2: Use stories if available AND they have questions
        if (realContent.stories && realContent.stories.length > 0) {
            const storiesWithQuestions = realContent.stories.filter(story => story.questions && story.questions.length > 0);
            if (storiesWithQuestions.length > 0) {
                console.log('✅ Using real stories with questions from chapter content');
                return this._generateStoryReadingExercise(realContent, difficulty, storiesWithQuestions);
            }
        }

        // Priority 3: Use texts if available AND they have questions
        if (realContent.texts && realContent.texts.length > 0) {
            const textsWithQuestions = realContent.texts.filter(text => text.questions && text.questions.length > 0);
            if (textsWithQuestions.length > 0) {
                console.log('✅ Using real texts with questions from chapter content');
                return this._generateTextReadingExercise(realContent, difficulty, textsWithQuestions);
            }
        }

        // Priority 4: Use dialogs if available AND they have questions
        if (realContent.dialogs && Object.keys(realContent.dialogs).length > 0) {
            const dialogsWithQuestions = Object.values(realContent.dialogs).filter(dialog =>
                dialog.questions && dialog.questions.length > 0
            );
            if (dialogsWithQuestions.length > 0) {
                console.log('✅ Using real dialogs with questions from chapter content');
                return this._generateDialogReadingExercise(realContent, difficulty, dialogsWithQuestions);
            }
        }

        // Priority 5: Use AI to generate questions for available content
        console.log('🤖 No predefined questions found - attempting to use AI to generate reading questions');

        try {
            return await this._generateAIReadingExercise(realContent, difficulty);
        } catch (error) {
            console.log('⚠️ AI question generation failed - skipping reading exercises');
            throw new Error('SKIP_READING: No reading content with predefined questions available and AI generation failed');
        }
    }

    _generateDialogReadingExercise(realContent, difficulty) {
        const dialogs = Object.values(realContent.dialogs);
        const numDialogs = difficulty === 'easy' ? 1 : Math.min(dialogs.length, 2);
        const selectedDialogs = this._selectRandomItems(dialogs, numDialogs);

        const steps = [];

        selectedDialogs.forEach((dialog, dialogIndex) => {
            // Create dialog text
            const dialogText = this._formatDialogAsText(dialog);

            // Generate comprehension questions based on dialog content
            const questions = this._generateDialogQuestions(dialog, difficulty);

            questions.forEach((questionData, questionIndex) => {
                steps.push({
                    id: `dialog-reading-${dialogIndex}-${questionIndex}`,
                    type: 'multiple-choice',
                    content: {
                        passage: dialogText,
                        question: questionData.question,
                        options: questionData.options,
                        correctAnswer: 0
                    },
                    hint: `Dialog: "${dialog.title}" - ${questionData.hint}`
                });
            });
        });

        // Shuffle options for each step
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `dialog-reading-${Date.now()}`,
            type: 'reading',
            title: `Dialog Comprehension: ${realContent.name}`,
            description: `Read real dialogues and answer comprehension questions`,
            difficulty,
            steps,
            metadata: {
                source: 'real-dialogs',
                chapterInfo: realContent.metadata,
                dialogsUsed: selectedDialogs.map(d => d.title)
            }
        };
    }

    _formatDialogAsText(dialog) {
        const lines = dialog.lines.map(line => `${line.speaker}: ${line.text}`);
        return `**${dialog.title}**\n\n${lines.join('\n')}`;
    }

    _generateDialogQuestions(dialog, difficulty) {
        const questions = [];
        const vocab = this._extractVocabFromDialog(dialog);

        // Question 1: Who said what
        const randomLine = dialog.lines[Math.floor(Math.random() * dialog.lines.length)];
        questions.push({
            question: `Who said: "${randomLine.text}"?`,
            options: [
                randomLine.speaker,
                ...dialog.participants.filter(p => p !== randomLine.speaker),
                'The narrator'
            ].slice(0, 4),
            hint: `Look for the speaker in the dialog`
        });

        // Question 2: Content comprehension
        if (dialog.title.includes('Apartment')) {
            questions.push({
                question: "What is Alex looking for?",
                options: [
                    "A two-bedroom apartment",
                    "A one-bedroom apartment",
                    "A house",
                    "A hotel room"
                ],
                hint: "Read Alex's first line carefully"
            });
        } else if (dialog.title.includes('Clothes') || dialog.title.includes('Shopping')) {
            questions.push({
                question: "What does the customer need?",
                options: [
                    "A shirt for work",
                    "A jacket for winter",
                    "Shoes for running",
                    "A dress for party"
                ],
                hint: "Check what the customer asks for"
            });
        } else {
            // Generic content question
            const firstLine = dialog.lines[0];
            questions.push({
                question: `According to the dialog, what does ${firstLine.speaker} want?`,
                options: [
                    firstLine.text,
                    "Something different",
                    "Nothing specific",
                    "To leave"
                ],
                hint: `Focus on ${firstLine.speaker}'s first statement`
            });
        }

        return questions.slice(0, difficulty === 'easy' ? 1 : 2);
    }

    _extractVocabFromDialog(dialog) {
        // Extract vocabulary words used in the dialog
        const dialogText = dialog.lines.map(line => line.text.toLowerCase()).join(' ');
        const words = dialogText.match(/\b\w+\b/g) || [];
        return [...new Set(words)];
    }

    _generateStoryReadingExercise(realContent, difficulty) {
        const stories = realContent.stories;
        const numStories = difficulty === 'easy' ? 1 : Math.min(stories.length, 2);
        const selectedStories = this._selectRandomItems(stories, numStories);

        const steps = [];

        selectedStories.forEach((story, storyIndex) => {
            // Generate comprehension questions based on story content
            const questions = this._generateStoryQuestions(story, difficulty);

            questions.forEach((questionData, questionIndex) => {
                steps.push({
                    id: `story-reading-${storyIndex}-${questionIndex}`,
                    type: 'multiple-choice',
                    content: {
                        passage: this._formatStoryText(story),
                        question: questionData.question,
                        options: questionData.options,
                        correctAnswer: 0
                    },
                    hint: `Story: "${story.title}" - ${questionData.hint}`
                });
            });
        });

        // Shuffle options for each step
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `story-reading-${Date.now()}`,
            type: 'reading',
            title: `Story Comprehension: ${realContent.name}`,
            description: `Read real stories and answer comprehension questions`,
            difficulty,
            steps,
            metadata: {
                source: 'real-stories',
                chapterInfo: realContent.metadata,
                storiesUsed: selectedStories.map(s => s.title || s.name)
            }
        };
    }

    _generateTextReadingExercise(realContent, difficulty) {
        const texts = realContent.texts;
        const numTexts = difficulty === 'easy' ? 1 : Math.min(texts.length, 2);
        const selectedTexts = this._selectRandomItems(texts, numTexts);

        const steps = [];

        selectedTexts.forEach((text, textIndex) => {
            // Generate comprehension questions based on text content
            const questions = this._generateTextQuestions(text, difficulty);

            questions.forEach((questionData, questionIndex) => {
                steps.push({
                    id: `text-reading-${textIndex}-${questionIndex}`,
                    type: 'multiple-choice',
                    content: {
                        passage: this._formatTextContent(text),
                        question: questionData.question,
                        options: questionData.options,
                        correctAnswer: 0
                    },
                    hint: `Text: "${text.title}" - ${questionData.hint}`
                });
            });
        });

        // Shuffle options for each step
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `text-reading-${Date.now()}`,
            type: 'reading',
            title: `Text Comprehension: ${realContent.name}`,
            description: `Read real texts and answer comprehension questions`,
            difficulty,
            steps,
            metadata: {
                source: 'real-texts',
                chapterInfo: realContent.metadata,
                textsUsed: selectedTexts.map(t => t.title || t.name)
            }
        };
    }

    _formatStoryText(story) {
        return `**${story.title || story.name}**\n\n${story.content || story.text}`;
    }

    _formatTextContent(text) {
        return `**${text.title || text.name}**\n\n${text.content || text.text}`;
    }

    _generateStoryQuestions(story, difficulty) {
        const questions = [];
        const storyText = story.content || story.text;
        const sentences = storyText.split(/[.!?]+/).filter(s => s.trim().length > 10);

        // Question 1: Main idea/theme
        questions.push({
            question: `What is this story mainly about?`,
            options: [
                this._extractMainTheme(story, sentences),
                "A different topic",
                "Nothing specific",
                "A random event"
            ],
            hint: "Look at the overall theme and key events"
        });

        // Question 2: Specific detail (if medium/hard difficulty)
        if (difficulty !== 'easy' && sentences.length > 1) {
            const randomSentence = sentences[Math.floor(Math.random() * sentences.length)].trim();
            questions.push({
                question: `According to the story, what happens?`,
                options: [
                    randomSentence,
                    "Something completely different",
                    "The story doesn't mention this",
                    "Nothing important"
                ],
                hint: "Look for specific details mentioned in the text"
            });
        }

        return questions.slice(0, difficulty === 'easy' ? 1 : 2);
    }

    _generateTextQuestions(text, difficulty) {
        const questions = [];
        const textContent = text.content || text.text;
        const sentences = textContent.split(/[.!?]+/).filter(s => s.trim().length > 10);

        // Question 1: Main topic
        questions.push({
            question: `What is the main topic of this text?`,
            options: [
                this._extractMainTheme(text, sentences),
                "A different subject",
                "No clear topic",
                "Random information"
            ],
            hint: "Focus on the key subject discussed"
        });

        // Question 2: Supporting detail (if medium/hard difficulty)
        if (difficulty !== 'easy' && sentences.length > 1) {
            const detailSentence = sentences[Math.floor(Math.random() * sentences.length)].trim();
            questions.push({
                question: `What does the text mention?`,
                options: [
                    detailSentence,
                    "Something not in the text",
                    "No specific details",
                    "Unrelated information"
                ],
                hint: "Find the specific information mentioned"
            });
        }

        return questions.slice(0, difficulty === 'easy' ? 1 : 2);
    }

    _extractMainTheme(content, sentences) {
        // Simple theme extraction based on title and first sentence
        const title = content.title || content.name || "";
        const firstSentence = sentences[0] || "";

        if (title) {
            return title;
        } else if (firstSentence.length > 50) {
            return firstSentence.substring(0, 50) + "...";
        } else {
            return firstSentence || "The main topic";
        }
    }

    _findReadingExerciseInJSON(exercises) {
        // Look for reading comprehension exercises in various forms
        for (const [key, exercise] of Object.entries(exercises)) {
            if (key.includes('reading') || key.includes('comprehension') ||
                exercise.type === 'reading' || exercise.type === 'comprehension') {
                return exercise;
            }

            // Check if exercise has passages with questions
            if (exercise.passages || exercise.texts || exercise.stories) {
                return exercise;
            }
        }
        return null;
    }

    _convertJSONExerciseToReading(exercise, realContent, difficulty) {
        const steps = [];

        // Handle different JSON exercise formats
        if (exercise.passages) {
            exercise.passages.forEach((passage, index) => {
                if (passage.questions) {
                    passage.questions.forEach((question, qIndex) => {
                        steps.push(this._createReadingStep(
                            `json-passage-${index}-${qIndex}`,
                            passage.text || passage.content,
                            question
                        ));
                    });
                }
            });
        } else if (exercise.texts) {
            exercise.texts.forEach((text, index) => {
                if (text.questions) {
                    text.questions.forEach((question, qIndex) => {
                        steps.push(this._createReadingStep(
                            `json-text-${index}-${qIndex}`,
                            text.content || text.text,
                            question
                        ));
                    });
                }
            });
        } else if (exercise.stories) {
            exercise.stories.forEach((story, index) => {
                if (story.questions) {
                    story.questions.forEach((question, qIndex) => {
                        steps.push(this._createReadingStep(
                            `json-story-${index}-${qIndex}`,
                            story.content || story.text,
                            question
                        ));
                    });
                }
            });
        }

        // If no steps created, return null
        if (steps.length === 0) {
            return null;
        }

        // Shuffle options for each step
        steps.forEach(step => {
            if (step.content.options) {
                const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
                step.content.options = shuffled.options;
                step.content.correctAnswer = shuffled.correctAnswer;
            }
        });

        return {
            id: `json-reading-${Date.now()}`,
            type: 'reading',
            title: exercise.title || `Reading Comprehension: ${realContent.name}`,
            description: exercise.instructions || exercise.description || 'Read and answer questions',
            difficulty,
            steps,
            metadata: {
                source: 'json-exercises',
                chapterInfo: realContent.metadata,
                originalExercise: exercise
            }
        };
    }

    _createReadingStep(stepId, passageText, question) {
        return {
            id: stepId,
            type: question.type || 'multiple-choice',
            content: {
                passage: passageText,
                question: question.question || question.text,
                options: question.options || question.choices,
                correctAnswer: question.correctAnswer || question.correct || 0
            },
            hint: question.hint || question.explanation || "Read the passage carefully"
        };
    }

    async _generateAIReadingExercise(realContent, difficulty) {
        // Import IAEngine dynamically
        let IAEngine;
        try {
            const module = await import('../DRS/services/IAEngine.js');
            IAEngine = module.default;
        } catch (error) {
            throw new Error('IAEngine not available');
        }

        const iaEngine = new IAEngine();

        // Select the best content for AI question generation
        const contentForAI = this._selectContentForAI(realContent);
        if (!contentForAI) {
            throw new Error('No suitable content found for AI question generation');
        }

        console.log(`🤖 Using AI to generate questions for: ${contentForAI.type}`);

        const steps = [];

        for (let i = 0; i < contentForAI.items.length; i++) {
            const item = contentForAI.items[i];
            const contentText = this._extractTextFromContent(item, contentForAI.type);

            try {
                // Generate questions using AI
                const aiQuestions = await this._generateQuestionsWithAI(iaEngine, contentText, difficulty);

                if (aiQuestions && aiQuestions.length > 0) {
                    aiQuestions.forEach((aiQuestion, qIndex) => {
                        steps.push({
                            id: `ai-${contentForAI.type}-${i}-${qIndex}`,
                            type: 'multiple-choice',
                            content: {
                                passage: contentText,
                                question: aiQuestion.question,
                                options: aiQuestion.options,
                                correctAnswer: 0 // AI puts correct answer first
                            },
                            hint: aiQuestion.hint || "Read the content carefully and think about the meaning"
                        });
                    });
                }
            } catch (aiError) {
                console.warn(`⚠️ AI failed for item ${i}:`, aiError.message);
                continue; // Try next item
            }
        }

        if (steps.length === 0) {
            throw new Error('AI could not generate any questions');
        }

        // Shuffle options for each step
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `ai-reading-${Date.now()}`,
            type: 'reading',
            title: `AI-Generated Reading: ${realContent.name}`,
            description: `Read content and answer AI-generated comprehension questions`,
            difficulty,
            steps,
            metadata: {
                source: 'ai-generated',
                chapterInfo: realContent.metadata,
                aiProvider: 'multiple-providers',
                contentType: contentForAI.type
            }
        };
    }

    _selectContentForAI(realContent) {
        // Priority order for AI question generation
        if (realContent.dialogs && Object.keys(realContent.dialogs).length > 0) {
            return {
                type: 'dialogs',
                items: Object.values(realContent.dialogs)
            };
        }

        if (realContent.stories && realContent.stories.length > 0) {
            return {
                type: 'stories',
                items: realContent.stories
            };
        }

        if (realContent.texts && realContent.texts.length > 0) {
            return {
                type: 'texts',
                items: realContent.texts
            };
        }

        return null;
    }

    _extractTextFromContent(item, contentType) {
        switch (contentType) {
            case 'dialogs':
                return this._formatDialogAsText(item);
            case 'stories':
                return this._formatStoryText(item);
            case 'texts':
                return this._formatTextContent(item);
            default:
                return item.content || item.text || '';
        }
    }

    async _generateQuestionsWithAI(iaEngine, contentText, difficulty) {
        const prompt = `Generate reading comprehension questions for this content:

Content:
${contentText}

Requirements:
- Create ${difficulty === 'easy' ? '1' : '2'} multiple choice questions
- Questions should test understanding of the content
- Each question needs exactly 4 answer options
- Put the correct answer FIRST in the options list
- Make questions appropriate for ${difficulty} level
- Be encouraging and educational

Return ONLY valid JSON in this format:
[
    {
        "question": "What is the main topic discussed?",
        "options": ["Correct answer", "Wrong option 1", "Wrong option 2", "Wrong option 3"],
        "hint": "Focus on the key subject"
    }
]`;

        try {
            const result = await iaEngine.validateEducationalContent(prompt, {
                systemPrompt: 'You are an expert reading comprehension teacher. Generate clear, educational questions. Return ONLY valid JSON.',
                temperature: 0.4
            });

            // Parse AI response
            let questions = [];

            if (result.content) {
                // If it's text content, try to parse as JSON
                try {
                    questions = JSON.parse(result.content);
                } catch (parseError) {
                    console.warn('AI returned non-JSON content, trying to extract JSON...');
                    const jsonMatch = result.content.match(/\[[\s\S]*\]/);
                    if (jsonMatch) {
                        questions = JSON.parse(jsonMatch[0]);
                    }
                }
            } else if (Array.isArray(result)) {
                questions = result;
            } else if (result.questions) {
                questions = result.questions;
            }

            if (!Array.isArray(questions) || questions.length === 0) {
                throw new Error('AI did not return valid questions array');
            }

            return questions.slice(0, difficulty === 'easy' ? 1 : 2); // Limit based on difficulty

        } catch (error) {
            console.warn('AI question generation failed:', error.message);
            throw new Error(`AI generation failed: ${error.message}`);
        }
    }

    async _generateSentenceComprehensionWithAI(realContent, difficulty) {
        // Import IAEngine
        let IAEngine;
        try {
            const module = await import('../DRS/services/IAEngine.js');
            IAEngine = module.default;
        } catch (error) {
            throw new Error('IAEngine not available for sentence comprehension');
        }

        const iaEngine = new IAEngine();
        const sentences = realContent.sentences.slice(0, difficulty === 'easy' ? 2 : 3);
        const steps = [];

        for (let i = 0; i < sentences.length; i++) {
            const sentence = sentences[i];
            const sentenceText = sentence.english || sentence.text || sentence.content;
            const translation = sentence.chinese || sentence.user_language || sentence.translation;

            try {
                console.log(`🤖 Generating comprehension questions for sentence: "${sentenceText}"`);

                const prompt = `Analyze this English sentence phrase by phrase for language learning comprehension:

Sentence: "${sentenceText}"
Translation: "${translation}"

Create ONE comprehension question that tests understanding of:
- Key meaning or main action
- Important vocabulary within context
- Phrase structure understanding

Requirements:
- Make it ${difficulty} level appropriate
- Focus on comprehension, not just vocabulary
- Provide 4 multiple choice options
- Put correct answer FIRST

Return ONLY valid JSON:
{
    "question": "What is the main meaning of this sentence?",
    "options": ["Correct interpretation", "Wrong option 1", "Wrong option 2", "Wrong option 3"],
    "hint": "Focus on the key action or meaning"
}`;

                const result = await iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are a language comprehension expert. Create questions that test real understanding, not just vocabulary. Return ONLY valid JSON.',
                    temperature: 0.4
                });

                const aiQuestion = this._parseAIQuestionResponse(result);
                if (aiQuestion) {
                    steps.push({
                        id: `sentence-ai-${i}`,
                        type: 'multiple-choice',
                        content: {
                            passage: `**Sentence Analysis**\n\n"${sentenceText}"\n\n*Translation: ${translation}*`,
                            question: aiQuestion.question,
                            options: aiQuestion.options,
                            correctAnswer: 0
                        },
                        hint: aiQuestion.hint || "Think about the overall meaning and context"
                    });
                }
            } catch (aiError) {
                console.warn(`⚠️ AI failed for sentence ${i}:`, aiError.message);
                continue;
            }
        }

        if (steps.length === 0) {
            throw new Error('AI could not generate sentence comprehension questions');
        }

        // Shuffle options
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `sentence-comprehension-${Date.now()}`,
            type: 'text',
            title: `AI Sentence Comprehension: ${realContent.name}`,
            description: `Understand sentences phrase by phrase with AI analysis`,
            difficulty,
            steps,
            metadata: {
                source: 'ai-sentence-comprehension',
                chapterInfo: realContent.metadata
            }
        };
    }

    async _generateDialogTextComprehensionWithAI(realContent, difficulty) {
        // Import IAEngine
        let IAEngine;
        try {
            const module = await import('../DRS/services/IAEngine.js');
            IAEngine = module.default;
        } catch (error) {
            throw new Error('IAEngine not available for dialog comprehension');
        }

        const iaEngine = new IAEngine();
        const dialogs = Object.values(realContent.dialogs).slice(0, difficulty === 'easy' ? 1 : 2);
        const steps = [];

        for (let i = 0; i < dialogs.length; i++) {
            const dialog = dialogs[i];
            const dialogText = dialog.lines.map(line =>
                `${line.speaker}: ${line.text} (${line.user_language})`
            ).join('\n');

            try {
                console.log(`🤖 Generating text comprehension for dialog: "${dialog.title}"`);

                const prompt = `Analyze this dialogue for detailed text comprehension:

**${dialog.title}**
${dialogText}

Create ONE comprehensive question that tests:
- Understanding of the conversation flow
- Grasp of context and situation
- Key information exchange
- Communication purpose

Requirements:
- ${difficulty} difficulty level
- Focus on comprehension and analysis
- Test deeper understanding than surface meaning
- 4 multiple choice options, correct answer FIRST

Return ONLY valid JSON:
{
    "question": "What is the main purpose or outcome of this conversation?",
    "options": ["Correct analysis", "Wrong interpretation 1", "Wrong interpretation 2", "Wrong interpretation 3"],
    "hint": "Consider the overall context and what the speakers achieve"
}`;

                const result = await iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are a dialogue analysis expert for language learning. Focus on comprehension and communication context. Return ONLY valid JSON.',
                    temperature: 0.4
                });

                const aiQuestion = this._parseAIQuestionResponse(result);
                if (aiQuestion) {
                    steps.push({
                        id: `dialog-text-ai-${i}`,
                        type: 'multiple-choice',
                        content: {
                            passage: `**${dialog.title}**\n\n${dialog.lines.map(line => `**${line.speaker}:** ${line.text}`).join('\n')}`,
                            question: aiQuestion.question,
                            options: aiQuestion.options,
                            correctAnswer: 0
                        },
                        hint: aiQuestion.hint || "Think about what the speakers are trying to accomplish"
                    });
                }
            } catch (aiError) {
                console.warn(`⚠️ AI failed for dialog ${i}:`, aiError.message);
                continue;
            }
        }

        if (steps.length === 0) {
            throw new Error('AI could not generate dialog text comprehension questions');
        }

        // Shuffle options
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `dialog-text-comprehension-${Date.now()}`,
            type: 'text',
            title: `AI Dialog Analysis: ${realContent.name}`,
            description: `Analyze conversations for deeper comprehension`,
            difficulty,
            steps,
            metadata: {
                source: 'ai-dialog-text-comprehension',
                chapterInfo: realContent.metadata
            }
        };
    }

    _parseAIQuestionResponse(result) {
        try {
            let question = null;

            if (result.content) {
                // Try to parse as JSON
                try {
                    question = JSON.parse(result.content);
                } catch (parseError) {
                    // Try to extract JSON from text
                    const jsonMatch = result.content.match(/\{[\s\S]*?\}/);
                    if (jsonMatch) {
                        question = JSON.parse(jsonMatch[0]);
                    }
                }
            } else if (result.question) {
                question = result;
            }

            if (question && question.question && question.options && Array.isArray(question.options)) {
                return question;
            }

            return null;
        } catch (error) {
            console.warn('Failed to parse AI question response:', error.message);
            return null;
        }
    }

    _generateReadingPassages(vocabEntries, difficulty) {
        const passages = [];
        const numPassages = difficulty === 'easy' ? 2 : difficulty === 'medium' ? 3 : 4;

        for (let i = 0; i < numPassages; i++) {
            const wordsForPassage = vocabEntries.slice(i * 2, (i * 2) + 3); // 3 words per passage

            if (wordsForPassage.length === 0) break;

            const focusWords = wordsForPassage.map(([word]) => word);
            const text = this._createReadingPassage(wordsForPassage, difficulty);
            const question = this._createReadingQuestion(wordsForPassage, difficulty);
            const options = this._createReadingOptions(wordsForPassage, vocabEntries);

            passages.push({
                text,
                question,
                options,
                focusWords
            });
        }

        return passages;
    }

    _createReadingPassage(wordsForPassage, difficulty) {
        const templates = {
            easy: [
                `Today I learned about {word1}. It means {meaning1}. I also saw a {word2} and it was {word3}. These words help me understand daily life better.`,
                `In my English class, we studied {word1}. The teacher explained that {word1} is {meaning1}. Then we learned {word2} and {word3}.`
            ],
            medium: [
                `During our conversation, she mentioned that the {word1} was quite {word3}. I didn't understand what she meant by {word1} at first, but then I remembered it means {meaning1}. We also talked about the {word2} nearby.`,
                `The lesson focused on practical vocabulary. When discussing {word1}, which means {meaning1}, the instructor emphasized its importance. We also covered {word2} and {word3} in the same context.`
            ],
            hard: [
                `The comprehensive discussion about {word1} revealed its significance in everyday communication. Understanding that {word1} refers to {meaning1} helped clarify many previous conversations. The correlation between {word2} and {word3} became apparent through practical examples.`,
                `Contemporary language learning emphasizes contextual understanding. The term {word1}, meaning {meaning1}, frequently appears in discussions about {word2}. Students often find {word3} challenging initially.`
            ]
        };

        const templateArray = templates[difficulty] || templates.medium;
        const template = templateArray[Math.floor(Math.random() * templateArray.length)];

        let passage = template;
        wordsForPassage.forEach(([word, data], index) => {
            passage = passage.replace(`{word${index + 1}}`, word);
            passage = passage.replace(`{meaning${index + 1}}`, data.user_language);
        });

        return passage;
    }

    _createReadingQuestion(wordsForPassage, difficulty) {
        const questions = [
            `What does "${wordsForPassage[0][0]}" mean in this context?`,
            `According to the passage, "${wordsForPassage[0][0]}" refers to:`,
            `The text suggests that "${wordsForPassage[0][0]}" means:`,
            `In this passage, what is the meaning of "${wordsForPassage[0][0]}"?`
        ];

        return questions[Math.floor(Math.random() * questions.length)];
    }

    _createReadingOptions(wordsForPassage, allVocab) {
        const correctWord = wordsForPassage[0];
        const options = [correctWord[1].user_language]; // Correct answer

        // Add 3 wrong answers from other vocabulary
        const otherWords = allVocab.filter(([w]) => w !== correctWord[0]);
        const wrongAnswers = this._selectRandomItems(otherWords, 3);
        wrongAnswers.forEach(([, data]) => options.push(data.user_language));

        return options;
    }

    async _generateAudioFromRealContent(realContent, difficulty) {
        console.log('🎧 Generating audio comprehension exercise with AI');

        // Check if we have audio content for AI comprehension
        if (realContent.audio && realContent.audio.length > 0) {
            console.log('🎵 Using real audio content for AI comprehension');
            return await this._generateAudioComprehensionWithAI(realContent, difficulty);
        }

        // Check if we have dialogues for audio comprehension simulation
        if (realContent.dialogs && Object.keys(realContent.dialogs).length > 0) {
            console.log('💬 Using dialogues for simulated audio comprehension');
            return await this._generateDialogAudioComprehensionWithAI(realContent, difficulty);
        }

        // Fallback to vocabulary
        console.log('📚 Falling back to vocabulary audio');
        return this._generateVocabularyAudioExercise(realContent, difficulty);
    }

    _generateVocabularyAudioExercise(realContent, difficulty) {
        if (!realContent.vocabulary) {
            throw new Error('No vocabulary found in content');
        }

        const vocab = Object.entries(realContent.vocabulary);
        const numQuestions = this._getQuestionCount(difficulty);
        const selectedWords = this._selectRandomItems(vocab, numQuestions);

        const steps = selectedWords.map(([word, data], index) => ({
            id: `audio-step-${index + 1}`,
            type: 'multiple-choice',
            content: {
                audioText: `Listen to this word: ${word}. What does it mean?`,
                question: `You heard "${word}". What does it mean?`,
                options: this._generateTextOptions(word, data, vocab),
                correctAnswer: 0,
                audioUrl: null // Would use real audio in production
            },
            hint: `The word was "${word}". It's pronounced: ${data.pronunciation || word}`
        }));

        // Shuffle options for each step
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `audio-exercise-${Date.now()}`,
            type: 'audio',
            title: `Audio Vocabulary: ${realContent.name}`,
            description: `Listen and learn vocabulary from ${realContent.name}`,
            difficulty,
            steps,
            metadata: {
                source: 'real-content',
                chapterInfo: realContent.metadata
            }
        };
    }

    async _generateAudioComprehensionWithAI(realContent, difficulty) {
        // Import IAEngine
        let IAEngine;
        try {
            const module = await import('../DRS/services/IAEngine.js');
            IAEngine = module.default;
        } catch (error) {
            throw new Error('IAEngine not available for audio comprehension');
        }

        const iaEngine = new IAEngine();
        const audioItems = realContent.audio.slice(0, difficulty === 'easy' ? 2 : 3);
        const steps = [];

        for (let i = 0; i < audioItems.length; i++) {
            const audio = audioItems[i];
            const transcript = audio.transcript || audio.text || audio.content;
            const title = audio.title || `Audio ${i + 1}`;

            try {
                console.log(`🤖 Generating audio comprehension for: "${title}"`);

                const prompt = `Create a listening comprehension question for this audio content:

**${title}**
Audio transcript: "${transcript}"

Create ONE question that tests:
- Main idea or key information from the audio
- Understanding of spoken content context
- Ability to extract important details from listening

Requirements:
- ${difficulty} difficulty level
- Focus on comprehension skills
- Simulate "What did you hear?" type questions
- 4 multiple choice options, correct answer FIRST

Return ONLY valid JSON:
{
    "question": "What is the main information you heard?",
    "options": ["Correct comprehension", "Misunderstood info 1", "Misunderstood info 2", "Misunderstood info 3"],
    "hint": "Focus on the key message of what was said"
}`;

                const result = await iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are a listening comprehension expert. Create questions that test understanding of spoken content. Return ONLY valid JSON.',
                    temperature: 0.4
                });

                const aiQuestion = this._parseAIQuestionResponse(result);
                if (aiQuestion) {
                    steps.push({
                        id: `audio-ai-${i}`,
                        type: 'multiple-choice',
                        content: {
                            passage: `**🎧 Audio Comprehension: ${title}**\n\n*Listen carefully and answer based on what you heard.*\n\n**Transcript:** "${transcript}"`,
                            question: aiQuestion.question,
                            options: aiQuestion.options,
                            correctAnswer: 0,
                            audioText: `Audio content: ${transcript}`,
                            audioUrl: audio.audioUrl || null
                        },
                        hint: aiQuestion.hint || "Think about the main message you heard"
                    });
                }
            } catch (aiError) {
                console.warn(`⚠️ AI failed for audio ${i}:`, aiError.message);
                continue;
            }
        }

        if (steps.length === 0) {
            throw new Error('AI could not generate audio comprehension questions');
        }

        // Shuffle options
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `audio-comprehension-${Date.now()}`,
            type: 'audio',
            title: `AI Audio Comprehension: ${realContent.name}`,
            description: `Listen and understand audio content with AI questions`,
            difficulty,
            steps,
            metadata: {
                source: 'ai-audio-comprehension',
                chapterInfo: realContent.metadata
            }
        };
    }

    async _generateDialogAudioComprehensionWithAI(realContent, difficulty) {
        // Import IAEngine
        let IAEngine;
        try {
            const module = await import('../DRS/services/IAEngine.js');
            IAEngine = module.default;
        } catch (error) {
            throw new Error('IAEngine not available for dialog audio comprehension');
        }

        const iaEngine = new IAEngine();
        const dialogs = Object.values(realContent.dialogs).slice(0, difficulty === 'easy' ? 1 : 2);
        const steps = [];

        for (let i = 0; i < dialogs.length; i++) {
            const dialog = dialogs[i];
            const dialogScript = dialog.lines.map(line => `${line.speaker}: ${line.text}`).join('\n');

            try {
                console.log(`🤖 Generating dialog audio comprehension for: "${dialog.title}"`);

                const prompt = `Create a listening comprehension question for this dialogue as if it were heard as audio:

**${dialog.title}**
Dialogue:
${dialogScript}

Create ONE question that tests:
- Understanding of the conversation when heard
- Ability to follow speakers and their messages
- Comprehension of the overall exchange
- What listeners would catch from hearing this

Requirements:
- ${difficulty} difficulty level
- Simulate listening comprehension skills
- Test understanding of spoken interaction
- 4 multiple choice options, correct answer FIRST

Return ONLY valid JSON:
{
    "question": "What did you hear in this conversation?",
    "options": ["Correct understanding", "Wrong interpretation 1", "Wrong interpretation 2", "Wrong interpretation 3"],
    "hint": "Focus on what the speakers were discussing"
}`;

                const result = await iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are an expert in dialogue listening comprehension. Focus on what learners would understand from hearing spoken conversation. Return ONLY valid JSON.',
                    temperature: 0.4
                });

                const aiQuestion = this._parseAIQuestionResponse(result);
                if (aiQuestion) {
                    steps.push({
                        id: `dialog-audio-ai-${i}`,
                        type: 'multiple-choice',
                        content: {
                            passage: `**🎧 Listen to this conversation: ${dialog.title}**\n\n*Imagine you are listening to this dialogue.*\n\n${dialog.lines.map(line => `**${line.speaker}:** "${line.text}"`).join('\n')}`,
                            question: aiQuestion.question,
                            options: aiQuestion.options,
                            correctAnswer: 0,
                            audioText: `Conversation between ${dialog.participants.join(' and ')}: ${dialogScript}`
                        },
                        hint: aiQuestion.hint || "Think about what you heard the speakers saying"
                    });
                }
            } catch (aiError) {
                console.warn(`⚠️ AI failed for dialog audio ${i}:`, aiError.message);
                continue;
            }
        }

        if (steps.length === 0) {
            throw new Error('AI could not generate dialog audio comprehension questions');
        }

        // Shuffle options
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `dialog-audio-comprehension-${Date.now()}`,
            type: 'audio',
            title: `AI Dialog Listening: ${realContent.name}`,
            description: `Listen to conversations and test your comprehension`,
            difficulty,
            steps,
            metadata: {
                source: 'ai-dialog-audio-comprehension',
                chapterInfo: realContent.metadata
            }
        };
    }

    async _generateImageFromRealContent(realContent, difficulty) {
        console.log('🖼️ Generating image analysis exercise with AI');

        // Check if we have real images for AI analysis
        if (realContent.images && realContent.images.length > 0) {
            console.log('📸 Using real images for AI analysis');
            return await this._generateImageAnalysisWithAI(realContent, difficulty);
        }

        // Check for visual vocabulary concepts for AI explanation
        if (realContent.vocabulary) {
            const vocab = Object.entries(realContent.vocabulary);
            const visualWords = vocab.filter(([word, data]) =>
                data.type === 'noun' || word.includes('shirt') || word.includes('apartment') || word.includes('building')
            );

            if (visualWords.length > 0) {
                console.log('👁️ Using vocabulary for AI visual analysis');
                return await this._generateVocabularyImageAnalysisWithAI(realContent, difficulty, visualWords);
            }
        }

        // Fallback to basic image vocabulary
        console.log('📚 Falling back to basic image vocabulary');
        return this._generateBasicImageExercise(realContent, difficulty);
    }

    _generateBasicImageExercise(realContent, difficulty) {
        if (!realContent.vocabulary) {
            throw new Error('No vocabulary found in content');
        }

        const vocab = Object.entries(realContent.vocabulary);
        const imageableWords = vocab.filter(([word, data]) =>
            data.type === 'noun' || word.includes(' ') === false
        );

        if (imageableWords.length === 0) {
            throw new Error('No imageable vocabulary found');
        }

        const numQuestions = this._getQuestionCount(difficulty);
        const selectedWords = this._selectRandomItems(imageableWords, numQuestions);

        const steps = selectedWords.map(([word, data], index) => ({
            id: `image-step-${index + 1}`,
            type: 'multiple-choice',
            content: {
                imageUrl: `https://via.placeholder.com/300x200?text=${encodeURIComponent(word)}`,
                imageAlt: `Image representing ${word}`,
                question: `What word does this image represent?`,
                options: this._generateWordOptions(word, imageableWords),
                correctAnswer: 0
            },
            hint: `This is a ${data.type}. Think about: ${data.user_language}`
        }));

        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `image-exercise-${Date.now()}`,
            type: 'image',
            title: `Visual Vocabulary: ${realContent.name}`,
            description: `Identify vocabulary from ${realContent.name} using images`,
            difficulty,
            steps,
            metadata: {
                source: 'real-content',
                chapterInfo: realContent.metadata
            }
        };
    }

    _generateGrammarFromRealContent(realContent, difficulty) {
        if (!realContent.vocabulary) {
            throw new Error('No vocabulary found in content');
        }

        const vocab = Object.entries(realContent.vocabulary);
        const numQuestions = this._getQuestionCount(difficulty);
        const selectedWords = this._selectRandomItems(vocab, numQuestions);

        const steps = selectedWords.map(([word, data], index) => ({
            id: `grammar-step-${index + 1}`,
            type: 'fill-blank',
            content: {
                sentence: this._createSentenceWithBlank(word, data),
                correctAnswer: word,
                question: `Complete the sentence with the correct word:`,
                options: this._generateWordOptions(word, vocab.slice(0, 20))
            },
            hint: `The missing word is a ${data.type}. Meaning: ${data.user_language}`
        }));

        return {
            id: `grammar-exercise-${Date.now()}`,
            type: 'grammar',
            title: `Grammar Practice: ${realContent.name}`,
            description: `Practice using vocabulary from ${realContent.name} in context`,
            difficulty,
            steps,
            metadata: {
                source: 'real-content',
                chapterInfo: realContent.metadata
            }
        };
    }

    // Helper methods for real content generation
    _getQuestionCount(difficulty) {
        switch (difficulty) {
            case 'easy': return 3;
            case 'medium': return 5;
            case 'hard': return 8;
            default: return 5;
        }
    }

    _selectRandomItems(array, count) {
        const shuffled = [...array].sort(() => Math.random() - 0.5);
        return shuffled.slice(0, Math.min(count, array.length));
    }

    _generateTextOptions(correctWord, correctData, allVocab) {
        const options = [correctData.user_language];
        const otherWords = allVocab.filter(([w]) => w !== correctWord);
        const randomWrong = this._selectRandomItems(otherWords, 3);
        randomWrong.forEach(([, data]) => options.push(data.user_language));
        return options;
    }

    _generateWordOptions(correctWord, allWords) {
        const options = [correctWord];
        const otherWords = allWords.filter(([w]) => w !== correctWord);
        const randomWrong = this._selectRandomItems(otherWords, 3);
        randomWrong.forEach(([word]) => options.push(word));
        return options;
    }

    _shuffleOptions(options, correctIndex) {
        const shuffled = [...options];
        const correctAnswer = shuffled[correctIndex];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        const newCorrectIndex = shuffled.indexOf(correctAnswer);
        return { options: shuffled, correctAnswer: newCorrectIndex };
    }

    _createSentenceWithBlank(word, data) {
        const templates = {
            noun: [
                `The _____ is very important in daily life.`,
                `I need to buy a new _____ for my home.`,
                `The _____ was broken and needed repair.`
            ],
            verb: [
                `I like to _____ every morning.`,
                `We need to _____ before it's too late.`,
                `They will _____ tomorrow.`
            ],
            adjective: [
                `The weather is very _____ today.`,
                `This place looks _____ and comfortable.`,
                `The food tastes _____ and fresh.`
            ],
            adverb: [
                `She speaks English _____.`,
                `He works _____ every day.`,
                `They completed the task _____.`
            ]
        };

        const typeTemplates = templates[data.type] || templates.noun;
        return typeTemplates[Math.floor(Math.random() * typeTemplates.length)];
    }

    /**
     * Generate text exercise content
     * @param {Object} request - Request details
     * @returns {Object} - Text exercise
     * @private
     */
    _generateTextExercise(request) {
        const passages = {
            easy: {
                text: "The cat sits on the mat. It is a warm day. The cat likes to sleep in the sun.",
                questions: [
                    {
                        question: "Where does the cat sit?",
                        options: ["On the chair", "On the mat", "On the bed", "On the floor"],
                        correct: 1,
                        hint: "Look at the first sentence."
                    }
                ]
            },
            medium: {
                text: "Solar energy is becoming increasingly popular around the world. Many countries are investing in solar panels and wind turbines to reduce their dependence on fossil fuels. This shift towards renewable energy is helping to combat climate change and create jobs in the green energy sector.",
                questions: [
                    {
                        question: "What is helping to combat climate change?",
                        options: ["Fossil fuels", "Nuclear power", "Renewable energy", "Oil drilling"],
                        correct: 2,
                        hint: "Look for what countries are investing in."
                    },
                    {
                        question: "What benefits are mentioned for renewable energy?",
                        options: ["Only environmental", "Only economic", "Both environmental and economic", "Neither"],
                        correct: 2,
                        hint: "The passage mentions both climate change and job creation."
                    }
                ]
            },
            hard: {
                text: "The phenomenon of quantum entanglement, first described by Einstein as 'spooky action at a distance,' has evolved from a theoretical curiosity to a cornerstone of modern quantum physics. When two particles become entangled, measuring the state of one instantly affects the state of the other, regardless of the distance separating them. This seemingly impossible connection has profound implications for quantum computing, cryptography, and our understanding of the fundamental nature of reality.",
                questions: [
                    {
                        question: "How did Einstein describe quantum entanglement?",
                        options: ["Theoretical impossibility", "Spooky action at a distance", "Quantum computing", "Fundamental reality"],
                        correct: 1,
                        hint: "Look for Einstein's specific phrase in the text."
                    },
                    {
                        question: "What happens when entangled particles are measured?",
                        options: ["Nothing occurs", "One affects the other instantly", "They separate", "They disappear"],
                        correct: 1,
                        hint: "Focus on what happens when measuring one particle."
                    }
                ]
            }
        };

        const content = passages[request.difficulty] || passages.medium;

        return {
            title: `Reading Comprehension - ${request.difficulty}`,
            type: 'text',
            difficulty: request.difficulty,
            steps: content.questions.map((q, index) => ({
                instruction: index === 0 ? "Read the following passage and answer the questions." : "Continue answering questions about the passage.",
                text: content.text,
                question: q.question,
                options: q.options,
                correct: q.correct,
                hint: q.hint
            }))
        };
    }

    /**
     * Generate audio exercise content
     * @param {Object} request - Request details
     * @returns {Object} - Audio exercise
     * @private
     */
    _generateAudioExercise(request) {
        const audioExercises = {
            easy: {
                title: "Basic Listening",
                transcript: "Hello, my name is Sarah. I am twenty years old. I live in Paris.",
                questions: [
                    {
                        question: "What is the speaker's name?",
                        options: ["Maria", "Sarah", "Anna", "Lisa"],
                        correct: 1,
                        hint: "Listen to the beginning of the recording."
                    }
                ]
            },
            medium: {
                title: "Weather Forecast",
                transcript: "Good morning! Today's weather will be partly cloudy with temperatures reaching 22 degrees Celsius. There's a 30% chance of rain in the afternoon, so you might want to bring an umbrella. Tomorrow will be sunny with temperatures up to 25 degrees.",
                questions: [
                    {
                        question: "What will the temperature be today?",
                        options: ["20 degrees", "22 degrees", "25 degrees", "30 degrees"],
                        correct: 1,
                        hint: "Listen for today's temperature, not tomorrow's."
                    },
                    {
                        question: "What should you bring today?",
                        options: ["Sunglasses", "Jacket", "Umbrella", "Hat"],
                        correct: 2,
                        hint: "Think about what you need when there's a chance of rain."
                    }
                ]
            }
        };

        const content = audioExercises[request.difficulty] || audioExercises.medium;

        return {
            title: content.title,
            type: 'audio',
            difficulty: request.difficulty,
            steps: [
                {
                    instruction: "Listen to the audio carefully and answer the questions.",
                    audioUrl: "data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBjiR1/LNeSsFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhhBkHVoUEjPh==",
                    transcript: content.transcript,
                    questions: content.questions
                }
            ]
        };
    }

    /**
     * Generate image exercise content
     * @param {Object} request - Request details
     * @returns {Object} - Image exercise
     * @private
     */
    _generateImageExercise(request) {
        const images = {
            easy: "https://via.placeholder.com/400x300/87CEEB/ffffff?text=Sunny+Day",
            medium: "https://via.placeholder.com/400x300/228B22/ffffff?text=Green+Forest",
            hard: "https://via.placeholder.com/400x300/FF6347/ffffff?text=Complex+Scene"
        };

        return {
            title: `Image Analysis - ${request.difficulty}`,
            type: 'image',
            difficulty: request.difficulty,
            steps: [
                {
                    instruction: "Look at the image carefully and answer the question.",
                    imageUrl: images[request.difficulty] || images.medium,
                    question: "What do you see in this image?",
                    options: ["A sunny day", "A forest", "A complex scene", "Cannot determine"],
                    correct: 0,
                    hint: "Look at the text and colors in the placeholder image."
                }
            ]
        };
    }

    /**
     * Generate grammar exercise content
     * @param {Object} request - Request details
     * @returns {Object} - Grammar exercise
     * @private
     */
    _generateGrammarExercise(request) {
        const exercises = {
            easy: [
                {
                    instruction: "Fill in the blank with the correct verb form.",
                    sentence: "The dog _____ in the park.",
                    question: "Complete the sentence with the correct present tense form of 'run'.",
                    options: ["run", "runs", "running", "ran"],
                    correct: 1,
                    explanation: "Use 'runs' because 'dog' is singular and requires the third person singular form.",
                    hint: "Remember: he/she/it + verb + s"
                }
            ],
            medium: [
                {
                    instruction: "Choose the correct grammatical form.",
                    question: "Which sentence uses the present perfect correctly?",
                    options: [
                        "I have went to the store",
                        "I have gone to the store",
                        "I have go to the store",
                        "I have going to the store"
                    ],
                    correct: 1,
                    explanation: "The correct past participle of 'go' is 'gone', not 'went'.",
                    hint: "Present perfect uses 'have/has + past participle'"
                },
                {
                    instruction: "Fill in the blank with the correct form.",
                    sentence: "If I _____ rich, I would travel the world.",
                    question: "Complete the conditional sentence.",
                    options: ["am", "was", "were", "be"],
                    correct: 2,
                    explanation: "In hypothetical conditionals, use 'were' for all persons with 'if'.",
                    hint: "This is a hypothetical condition about the present."
                }
            ]
        };

        const content = exercises[request.difficulty] || exercises.medium;

        return {
            title: `Grammar Practice - ${request.difficulty}`,
            type: 'grammar',
            difficulty: request.difficulty,
            steps: content.map(exercise => ({
                ...exercise,
                hint: exercise.hint || "Think about the grammatical rules that apply here."
            }))
        };
    }

    /**
     * Generate default exercise content
     * @param {Object} request - Request details
     * @returns {Object} - Default exercise
     * @private
     */
    _generateDefaultExercise(request) {
        return {
            title: `General Exercise - ${request.difficulty || 'medium'}`,
            type: request.subtype || 'general',
            difficulty: request.difficulty || 'medium',
            steps: [
                {
                    instruction: "This is a sample exercise.",
                    question: "What type of exercise is this?",
                    options: ["Text", "Audio", "Image", "General"],
                    correct: 3,
                    hint: "Look at the title of the exercise."
                }
            ]
        };
    }

    // Event handlers

    /**
     * Handle content request events
     * @param {Object} event - Content request event
     * @private
     */
    async _handleContentRequest(event) {
        try {
            const content = await this.loadExercise(event.data);

            // Emit response
            this._eventBus.emit('content:response', {
                requestId: event.data.requestId,
                content
            }, this.name);

        } catch (error) {
            this._eventBus.emit('content:response', {
                requestId: event.data.requestId,
                error: error.message
            }, this.name);
        }
    }

    /**
     * Handle cache clear events
     * @param {Object} event - Cache clear event
     * @private
     */
    _handleClearCache(event) {
        this.clearCache(event.data?.pattern);
    }

    async _generateImageAnalysisWithAI(realContent, difficulty) {
        // Import IAEngine
        let IAEngine;
        try {
            const module = await import('../DRS/services/IAEngine.js');
            IAEngine = module.default;
        } catch (error) {
            throw new Error('IAEngine not available for image analysis');
        }

        const iaEngine = new IAEngine();
        const images = realContent.images.slice(0, difficulty === 'easy' ? 2 : 3);
        const steps = [];

        for (let i = 0; i < images.length; i++) {
            const image = images[i];
            const imageUrl = image.url || image.src || image.imageUrl;
            const description = image.description || image.alt || image.caption || '';
            const title = image.title || `Image ${i + 1}`;

            try {
                console.log(`🤖 Generating image analysis for: "${title}"`);

                const prompt = `Create an image analysis and explanation question for language learning:

**Image: ${title}**
Description: "${description}"
Image URL: ${imageUrl}

Create ONE question that tests:
- Visual analysis and description skills
- Ability to explain what is seen
- Understanding of visual context and details
- Language skills for describing images

Requirements:
- ${difficulty} difficulty level
- Focus on analysis and explanation
- Test descriptive language abilities
- 4 multiple choice options, correct answer FIRST

Return ONLY valid JSON:
{
    "question": "What is the best way to describe or explain this image?",
    "options": ["Correct description/analysis", "Wrong description 1", "Wrong description 2", "Wrong description 3"],
    "hint": "Look carefully at the details and context"
}`;

                const result = await iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are a visual analysis expert for language learning. Create questions that test descriptive and analytical skills. Return ONLY valid JSON.',
                    temperature: 0.4
                });

                const aiQuestion = this._parseAIQuestionResponse(result);
                if (aiQuestion) {
                    steps.push({
                        id: `image-analysis-ai-${i}`,
                        type: 'multiple-choice',
                        content: {
                            passage: `**🖼️ Image Analysis: ${title}**\n\n*Study this image carefully and analyze what you see.*\n\n**Description:** ${description}`,
                            question: aiQuestion.question,
                            options: aiQuestion.options,
                            correctAnswer: 0,
                            imageUrl: imageUrl,
                            imageAlt: description || `Analysis image ${i + 1}`
                        },
                        hint: aiQuestion.hint || "Look at the details and think about how to describe them"
                    });
                }
            } catch (aiError) {
                console.warn(`⚠️ AI failed for image ${i}:`, aiError.message);
                continue;
            }
        }

        if (steps.length === 0) {
            throw new Error('AI could not generate image analysis questions');
        }

        // Shuffle options
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `image-analysis-${Date.now()}`,
            type: 'image',
            title: `AI Image Analysis: ${realContent.name}`,
            description: `Analyze and explain images with AI guidance`,
            difficulty,
            steps,
            metadata: {
                source: 'ai-image-analysis',
                chapterInfo: realContent.metadata
            }
        };
    }

    async _generateVocabularyImageAnalysisWithAI(realContent, difficulty, visualWords) {
        // Import IAEngine
        let IAEngine;
        try {
            const module = await import('../DRS/services/IAEngine.js');
            IAEngine = module.default;
        } catch (error) {
            throw new Error('IAEngine not available for vocabulary image analysis');
        }

        const iaEngine = new IAEngine();
        const selectedWords = visualWords.slice(0, difficulty === 'easy' ? 2 : 3);
        const steps = [];

        for (let i = 0; i < selectedWords.length; i++) {
            const [word, data] = selectedWords[i];

            try {
                console.log(`🤖 Generating image analysis for word: "${word}"`);

                const prompt = `Create a visual analysis question for this vocabulary word in a learning context:

**Word:** "${word}"
**Meaning:** "${data.user_language}"
**Type:** ${data.type}

Create ONE question that tests:
- Visual understanding and explanation of the concept
- Ability to analyze and describe the word's visual representation
- Language skills for explaining what the word represents visually

Requirements:
- ${difficulty} difficulty level
- Focus on visual analysis and description
- Help students understand how to describe and explain this concept
- 4 multiple choice options, correct answer FIRST

Return ONLY valid JSON:
{
    "question": "How would you visually describe or analyze what '${word}' represents?",
    "options": ["Correct visual analysis", "Wrong description 1", "Wrong description 2", "Wrong description 3"],
    "hint": "Think about the visual characteristics and what you would see"
}`;

                const result = await iaEngine.validateEducationalContent(prompt, {
                    systemPrompt: 'You are a vocabulary visualization expert for language learning. Create questions that test visual understanding and descriptive skills. Return ONLY valid JSON.',
                    temperature: 0.4
                });

                const aiQuestion = this._parseAIQuestionResponse(result);
                if (aiQuestion) {
                    steps.push({
                        id: `vocab-image-ai-${i}`,
                        type: 'multiple-choice',
                        content: {
                            passage: `**🔍 Visual Analysis: "${word}"**\n\n*Think about how you would visually describe or analyze this concept.*\n\n**Word:** ${word}\n**Meaning:** ${data.user_language}\n**Type:** ${data.type}`,
                            question: aiQuestion.question,
                            options: aiQuestion.options,
                            correctAnswer: 0,
                            imageUrl: `https://via.placeholder.com/300x200?text=${encodeURIComponent(word)}`,
                            imageAlt: `Visual representation of ${word}`
                        },
                        hint: aiQuestion.hint || "Think about what you would see and how you would describe it"
                    });
                }
            } catch (aiError) {
                console.warn(`⚠️ AI failed for vocabulary image ${i}:`, aiError.message);
                continue;
            }
        }

        if (steps.length === 0) {
            throw new Error('AI could not generate vocabulary image analysis questions');
        }

        // Shuffle options
        steps.forEach(step => {
            const shuffled = this._shuffleOptions(step.content.options, step.content.correctAnswer);
            step.content.options = shuffled.options;
            step.content.correctAnswer = shuffled.correctAnswer;
        });

        return {
            id: `vocab-image-analysis-${Date.now()}`,
            type: 'image',
            title: `AI Visual Analysis: ${realContent.name}`,
            description: `Analyze and explain vocabulary concepts visually`,
            difficulty,
            steps,
            metadata: {
                source: 'ai-vocabulary-image-analysis',
                chapterInfo: realContent.metadata
            }
        };
    }
}

export default ContentLoader;