/**
 * 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 || [
                'reading-comprehension-QCM', 'listening-comprehension-QCM',
                'visual-description-QCM', 'grammar-practice-QCM', 'vocabulary-flashcards',
                'reading-comprehension-AI', 'listening-comprehension-AI',
                'visual-description-AI', 'grammar-practice-AI'
            ],
            difficulties: config.difficulties || ['easy', 'medium', 'hard'],
            ...config
        };

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

        // Shared IAEngine instance for AI operations
        this._iaEngine = null;
        this._iaEnginePromise = null;

        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');
    }

    /**
     * Get shared IAEngine instance (creates and initializes if needed)
     * @private
     */
    async _getIAEngine() {
        if (this._iaEngine) {
            return this._iaEngine;
        }

        // Use promise to ensure single initialization even with concurrent calls
        if (!this._iaEnginePromise) {
            this._iaEnginePromise = this._initializeIAEngine();
        }

        return await this._iaEnginePromise;
    }

    /**
     * Initialize IAEngine instance
     * @private
     */
    async _initializeIAEngine() {
        try {
            const module = await import('../DRS/services/IAEngine.js');
            const IAEngine = module.default;
            this._iaEngine = new IAEngine();

            // FORCE immediate API key initialization
            console.log('🤖 Shared IAEngine instance created, initializing API keys...');
            await this._iaEngine._initializeApiKeys();
            console.log('🤖 Shared IAEngine fully initialized with API keys');

            return this._iaEngine;
        } catch (error) {
            throw new Error(`IAEngine not available for AI content generation: ${error.message}`);
        }
    }

    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);

                // DON'T emit content:loaded for exercise content - that's for chapter content only
                // (exercises are ephemeral and shouldn't trigger game compatibility recalculation)

                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 await this._generateExerciseFromRealContent(realContent, request);

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

    /**
     * Check if QCM content is available, fallback to AI version if not
     */
    _checkQCMFallback(realContent, subtype) {
        // If not a QCM exercise, return as-is
        if (!subtype.endsWith('-QCM')) {
            return subtype;
        }

        // Check content availability for QCM exercises
        const hasVocabulary = realContent.vocabulary && Object.keys(realContent.vocabulary).length > 0;
        const hasDialogs = realContent.dialogs && Object.keys(realContent.dialogs).length > 0;
        const hasGrammar = realContent.grammar && realContent.grammar.length > 0;
        const hasImages = realContent.images && realContent.images.length > 0;

        switch (subtype) {
            case 'reading-comprehension-QCM':
                // Need dialogs or text content for reading comprehension QCM
                if (!hasDialogs && !realContent.texts) {
                    return 'reading-comprehension-AI';
                }
                break;

            case 'listening-comprehension-QCM':
                // Audio exercises need actual audio files - no fallback possible
                if (!realContent.audios) {
                    throw new Error('No audio content available for listening comprehension exercise');
                }
                break;

            case 'visual-description-QCM':
                // Image exercises need actual images - no fallback possible
                if (!hasImages) {
                    throw new Error('No image content available for visual description exercise');
                }
                break;

            case 'grammar-practice-QCM':
                // Need grammar rules or vocabulary for grammar QCM
                if (!hasGrammar && !hasVocabulary) {
                    return 'grammar-practice-AI';
                }
                break;
        }

        // QCM content is available
        return subtype;
    }

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

        // Check if QCM content is available, fallback to AI if not
        const actualSubtype = this._checkQCMFallback(realContent, subtype);
        if (actualSubtype !== subtype) {
            console.log(`📋 QCM content not sufficient for ${subtype}, falling back to ${actualSubtype}`);
        }

        switch (actualSubtype) {
            case 'text':
            case 'reading-comprehension-QCM':
            case 'reading-comprehension-AI':
                // Text/Reading comprehension exercises
                return await this._generateTextFromRealContent(realContent, difficulty);
            case 'reading':
                // Reading = comprehension with real passages
                return await this._generateReadingFromRealContent(realContent, difficulty);
            case 'phrase':
                // Phrase comprehension exercises
                return this._generatePhraseFromRealContent(realContent, difficulty);
            case 'audio':
            case 'listening-comprehension-QCM':
            case 'listening-comprehension-AI':
                return await this._generateAudioFromRealContent(realContent, difficulty);
            case 'image':
            case 'visual-description-QCM':
            case 'visual-description-AI':
                return await this._generateImageFromRealContent(realContent, difficulty);
            case 'grammar':
            case 'grammar-practice-QCM':
            case 'grammar-practice-AI':
                return this._generateGrammarFromRealContent(realContent, difficulty);
            case 'vocabulary-flashcards':
                // Flashcards use real vocabulary content only
                return this._extractVocabularyForFlashcards(realContent);
            default:
                throw new Error(`Unknown exercise subtype: ${subtype}`);
        }
    }

    /**
     * Generate AI-based exercises when no real content is available
     */
    async _generateMockContent(request) {
        const { subtype, chapterId, bookId, difficulty = 'medium' } = request;

        console.log(`🤖 No real content available for ${subtype} exercise - generating AI-based content`);
        console.log(`📚 Chapter/Book: ${chapterId || bookId}`);
        console.log(`🎯 Using pure AI generation for learning content`);

        try {
            // Use shared IAEngine instance
            const iaEngine = await this._getIAEngine();

            // Generate content based on exercise type
            switch (subtype) {
                case 'text':
                case 'reading':
                case 'reading-comprehension-QCM':
                case 'reading-comprehension-AI':
                    return await this._generateAITextExercise(iaEngine, request);
                case 'audio':
                case 'listening-comprehension-QCM':
                case 'listening-comprehension-AI':
                    return await this._generateAIAudioExercise(iaEngine, request);
                case 'image':
                case 'visual-description-QCM':
                case 'visual-description-AI':
                    return await this._generateAIImageExercise(iaEngine, request);
                case 'grammar':
                case 'grammar-practice-QCM':
                case 'grammar-practice-AI':
                    return await this._generateAIGrammarExercise(iaEngine, request);
                case 'vocabulary-flashcards':
                    throw new Error('Vocabulary flashcards should use real content, not AI generation');
                default:
                    return await this._generateAIGeneralExercise(iaEngine, request);
            }

        } catch (error) {
            console.error(`❌ Failed to generate AI content for ${subtype}:`, error.message);
            console.error(`❌ AI is required for this system to function`);

            // No fallback - AI is mandatory for this system
            throw new Error(`AI generation failed for ${subtype} exercise. IAEngine is required for this system to function. Original error: ${error.message}`);
        }
    }

    // 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
            }
        };
    }

    async _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 = await this._getIAEngine();

        // 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 = await this._getIAEngine();
        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 = await this._getIAEngine();
        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];

            // Support both old format (lines array) and new format (content array)
            let dialogText;
            if (dialog.lines) {
                // Old format: {speaker, text, user_language}
                dialogText = dialog.lines.map(line =>
                    `${line.speaker}: ${line.text} (${line.user_language})`
                ).join('\n');
            } else if (dialog.content) {
                // New format: array of strings "Speaker: Text"
                dialogText = dialog.content.join('\n');
            } else {
                console.warn('⚠️ Dialog has neither lines nor content array, skipping:', dialog.title);
                continue;
            }

            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) {
                    // Format passage based on dialog structure (old or new format)
                    let passageText;
                    if (dialog.lines) {
                        // Old format: {speaker, text}
                        passageText = dialog.lines.map(line => `**${line.speaker}:** ${line.text}`).join('\n');
                    } else if (dialog.content) {
                        // New format: array of strings already formatted
                        passageText = dialog.content.join('\n');
                    } else {
                        passageText = dialogText; // Fallback to extracted text
                    }

                    steps.push({
                        id: `dialog-text-ai-${i}`,
                        type: 'multiple-choice',
                        content: {
                            passage: `**${dialog.title}**\n\n${passageText}`,
                            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 = await this._getIAEngine();
        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 = await this._getIAEngine();
        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
            }
        };
    }

    _generatePhraseFromRealContent(realContent, difficulty) {
        console.log('💬 Generating phrase exercise from real content');

        if (!realContent.phrases || Object.keys(realContent.phrases).length === 0) {
            throw new Error('No phrases found in content');
        }

        const phrasesEntries = Object.entries(realContent.phrases);
        console.log(`✅ Found ${phrasesEntries.length} phrases available`);

        // Select one random phrase
        const selectedPhrases = this._selectRandomItems(phrasesEntries, 1);
        const [phraseText, phraseData] = selectedPhrases[0];

        // Wrap in steps array like text exercises to enable proper validation flow
        const steps = [{
            id: `phrase-step-1`,
            type: 'phrase',
            content: {
                phrase: {
                    id: phraseText,
                    english: phraseText,
                    text: phraseText,
                    user_language: phraseData.user_language,
                    translation: phraseData.user_language,
                    context: phraseData.context,
                    pronunciation: phraseData.pronunciation
                }
            }
        }];

        return {
            id: `phrase-exercise-${Date.now()}`,
            type: 'phrase',
            title: `Phrase Comprehension: ${realContent.name}`,
            description: `Understand and analyze academic phrases from ${realContent.name}`,
            difficulty,
            steps,  // Now has steps array like text exercises
            metadata: {
                source: 'real-phrases',
                chapterInfo: realContent.metadata,
                totalPhrasesAvailable: phrasesEntries.length
            }
        };
    }

    _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)];
    }

    // Pure AI content generation methods (no real content available)

    async _generateAITextExercise(iaEngine, request) {
        const { difficulty = 'medium', chapterId, bookId } = request;
        const topic = chapterId || bookId || 'general English';

        console.log(`🤖 Generating AI text comprehension for topic: ${topic}`);

        const prompt = `Create an intelligent text comprehension exercise for ${difficulty} level English learners.

Topic area: ${topic}
Requirements:
- Create an educational text passage (100-200 words) about ${topic}
- Make it appropriate for ${difficulty} level
- Generate 2-3 comprehension questions about the text
- For each question, create 1 CORRECT answer + 5 PLAUSIBLE wrong answers (distractors)
- Wrong answers should be realistic mistakes students might make:
  * Partial truths or incomplete information
  * Common misconceptions about the topic
  * Details confused with main ideas
  * Logical but incorrect conclusions
  * Similar concepts that don't apply
- Put correct answer FIRST, then 5 intelligent distractors
- Include helpful hints that guide without giving away the answer
- Focus on testing real comprehension, not just vocabulary

Return ONLY valid JSON:
{
    "title": "Intelligent QCM: ${topic}",
    "passage": "Educational text about the topic...",
    "questions": [
        {
            "question": "What is the main idea of this passage?",
            "options": [
                "Correct comprehensive answer",
                "Plausible but too specific detail",
                "Common misconception about topic",
                "Logical but wrong conclusion",
                "Related but different concept",
                "Partially true but incomplete"
            ],
            "hint": "Focus on the overall message, not specific details"
        }
    ]
}`;

        try {
            const result = await iaEngine.validateEducationalContent(prompt, {
                systemPrompt: 'You are a text comprehension expert. Create engaging, educational content. Return ONLY valid JSON.',
                temperature: 0.6
            });

            const aiContent = this._parseAIExerciseResponse(result);
            if (!aiContent) {
                throw new Error('Invalid AI response format');
            }

            const steps = aiContent.questions.map((q, index) => {
                const shuffled = this._shuffleOptions(q.options, 0);
                return {
                    id: `ai-text-${index}`,
                    type: 'multiple-choice',
                    content: {
                        passage: aiContent.passage,
                        question: q.question,
                        options: shuffled.options,
                        correctAnswer: shuffled.correctAnswer
                    },
                    hint: q.hint || "Read carefully and think about the meaning"
                };
            });

            return {
                id: `ai-text-${Date.now()}`,
                type: 'text',
                title: aiContent.title || `AI Intelligent QCM: ${topic}`,
                description: `AI-generated text comprehension exercise about ${topic}`,
                difficulty,
                steps,
                metadata: {
                    source: 'ai-generated-pure',
                    topic,
                    provider: 'multiple-ai-providers'
                }
            };

        } catch (error) {
            console.warn('AI text generation failed:', error.message);
            throw error;
        }
    }

    async _generateAIAudioExercise(iaEngine, request) {
        const { difficulty = 'medium', chapterId, bookId } = request;
        const topic = chapterId || bookId || 'general conversation';

        console.log(`🤖 Generating AI audio comprehension for topic: ${topic}`);

        const prompt = `Create an intelligent audio comprehension exercise for ${difficulty} level English learners.

Topic: ${topic}
Requirements:
- Create a realistic dialogue or monologue transcript (50-100 words)
- Make it sound natural and conversational for ${difficulty} level
- Generate 2 listening comprehension questions
- For each question, create 1 CORRECT answer + 5 PLAUSIBLE wrong answers
- Wrong answers should test common listening mistakes:
  * Mishearing similar-sounding words
  * Confusing speakers in dialogues
  * Missing context clues
  * Focusing on wrong details
  * Misunderstanding tone or intent
- Put correct answer FIRST, then 5 intelligent distractors
- Focus on what learners would actually hear and misunderstand

Return ONLY valid JSON:
{
    "title": "Intelligent Audio QCM: ${topic}",
    "transcript": "Realistic dialogue or speech...",
    "questions": [
        {
            "question": "What did the speaker say about...?",
            "options": [
                "Correct interpretation of what was said",
                "Similar-sounding but wrong information",
                "Wrong speaker attribution",
                "Misunderstood context",
                "Wrong detail focus",
                "Opposite of what was meant"
            ],
            "hint": "Listen carefully to the exact words and context"
        }
    ]
}`;

        try {
            const result = await iaEngine.validateEducationalContent(prompt, {
                systemPrompt: 'You are a listening comprehension expert. Create realistic audio content. Return ONLY valid JSON.',
                temperature: 0.6
            });

            const aiContent = this._parseAIExerciseResponse(result);
            if (!aiContent) {
                throw new Error('Invalid AI response format');
            }

            const steps = aiContent.questions.map((q, index) => {
                const shuffled = this._shuffleOptions(q.options, 0);
                return {
                    id: `ai-audio-${index}`,
                    type: 'multiple-choice',
                    content: {
                        passage: `🎧 **Listen carefully:**\n\n"${aiContent.transcript}"`,
                        question: q.question,
                        options: shuffled.options,
                        correctAnswer: shuffled.correctAnswer,
                        audioText: aiContent.transcript
                    },
                    hint: q.hint || "Listen for the key information"
                };
            });

            return {
                id: `ai-audio-${Date.now()}`,
                type: 'audio',
                title: aiContent.title || `AI Listening: ${topic}`,
                description: `AI-generated listening exercise about ${topic}`,
                difficulty,
                steps,
                metadata: {
                    source: 'ai-generated-pure',
                    topic,
                    provider: 'multiple-ai-providers'
                }
            };

        } catch (error) {
            console.warn('AI audio generation failed:', error.message);
            throw error;
        }
    }

    async _generateAIImageExercise(iaEngine, request) {
        const { difficulty = 'medium', chapterId, bookId } = request;
        const topic = chapterId || bookId || 'everyday objects';

        console.log(`🤖 Generating AI image analysis for topic: ${topic}`);

        const prompt = `Create an intelligent visual description exercise for ${difficulty} level English learners.

Topic: ${topic}
Requirements:
- Describe a realistic scene or object related to ${topic}
- Create detailed visual description (50-80 words) with specific visual elements
- Generate 2 questions about what learners would see
- For each question, create 1 CORRECT answer + 5 PLAUSIBLE wrong answers
- Wrong answers should test common visual interpretation mistakes:
  * Confusing similar objects or colors
  * Missing important visual details
  * Misinterpreting spatial relationships
  * Confusing foreground/background elements
  * Misunderstanding descriptive adjectives
- Put correct answer FIRST, then 5 intelligent visual distractors
- Focus on precise visual vocabulary and observation skills

Return ONLY valid JSON:
{
    "title": "Intelligent Visual QCM: ${topic}",
    "description": "Detailed description of what you would see...",
    "questions": [
        {
            "question": "What is the main object in this scene?",
            "options": [
                "Correct identification of main object",
                "Similar-looking but wrong object",
                "Background object confused as main",
                "Wrong color or size description",
                "Related but different item",
                "Completely different category"
            ],
            "hint": "Focus on the most prominent visual element described"
        }
    ]
}`;

        try {
            const result = await iaEngine.validateEducationalContent(prompt, {
                systemPrompt: 'You are a visual description expert. Create vivid, educational descriptions. Return ONLY valid JSON.',
                temperature: 0.6
            });

            const aiContent = this._parseAIExerciseResponse(result);
            if (!aiContent) {
                throw new Error('Invalid AI response format');
            }

            const steps = aiContent.questions.map((q, index) => {
                const shuffled = this._shuffleOptions(q.options, 0);
                return {
                    id: `ai-image-${index}`,
                    type: 'multiple-choice',
                    content: {
                        passage: `🖼️ **Imagine this scene:**\n\n${aiContent.description}`,
                        question: q.question,
                        options: shuffled.options,
                        correctAnswer: shuffled.correctAnswer,
                        imageAlt: aiContent.description
                    },
                    hint: q.hint || "Think about what you would actually see"
                };
            });

            return {
                id: `ai-image-${Date.now()}`,
                type: 'image',
                title: aiContent.title || `AI Visual: ${topic}`,
                description: `AI-generated visual description exercise about ${topic}`,
                difficulty,
                steps,
                metadata: {
                    source: 'ai-generated-pure',
                    topic,
                    provider: 'multiple-ai-providers'
                }
            };

        } catch (error) {
            console.warn('AI image generation failed:', error.message);
            throw error;
        }
    }

    async _generateAIGrammarExercise(iaEngine, request) {
        const { difficulty = 'medium', chapterId, bookId } = request;
        const topic = chapterId || bookId || 'practical grammar';

        console.log(`🤖 Generating AI grammar exercise for topic: ${topic}`);

        const prompt = `Create an intelligent grammar exercise for ${difficulty} level English learners.

Focus area: ${topic} related grammar
Requirements:
- Create 3 practical grammar questions for ${difficulty} level
- Use real-world contexts and situations
- For each question, create 1 CORRECT answer + 5 PLAUSIBLE wrong answers
- Wrong answers should represent common grammar mistakes:
  * Wrong verb tenses
  * Subject-verb disagreement
  * Incorrect word forms (adjective/adverb confusion)
  * Common pronunciation-based errors
  * Logical but grammatically wrong constructions
- Put correct answer FIRST, then 5 intelligent grammar distractors
- Include clear explanations for the correct answer
- Focus on mistakes students actually make

Return ONLY valid JSON:
{
    "title": "Intelligent Grammar QCM: ${topic}",
    "questions": [
        {
            "question": "Complete the sentence: I ___ to work every day.",
            "options": [
                "go",
                "goes",
                "going",
                "went",
                "am go",
                "goed"
            ],
            "explanation": "Use 'go' with 'I' in present tense - first person singular doesn't add 's'",
            "hint": "Think about present tense with 'I' - what ending does the verb need?"
        }
    ]
}`;

        try {
            const result = await iaEngine.validateEducationalContent(prompt, {
                systemPrompt: 'You are a grammar expert. Create practical, useful exercises. Return ONLY valid JSON.',
                temperature: 0.5
            });

            const aiContent = this._parseAIExerciseResponse(result);
            if (!aiContent) {
                throw new Error('Invalid AI response format');
            }

            const steps = aiContent.questions.map((q, index) => {
                const shuffled = this._shuffleOptions(q.options, 0);
                return {
                    id: `ai-grammar-${index}`,
                    type: 'multiple-choice',
                    content: {
                        question: q.question,
                        options: shuffled.options,
                        correctAnswer: shuffled.correctAnswer
                    },
                    hint: q.hint || q.explanation || "Think about the grammar rule that applies"
                };
            });

            return {
                id: `ai-grammar-${Date.now()}`,
                type: 'grammar',
                title: aiContent.title || `AI Grammar: ${topic}`,
                description: `AI-generated grammar exercise for ${topic}`,
                difficulty,
                steps,
                metadata: {
                    source: 'ai-generated-pure',
                    topic,
                    provider: 'multiple-ai-providers'
                }
            };

        } catch (error) {
            console.warn('AI grammar generation failed:', error.message);
            throw error;
        }
    }

    async _generateAIGeneralExercise(iaEngine, request) {
        const { difficulty = 'medium', chapterId, bookId, subtype } = request;
        const topic = chapterId || bookId || 'general English';

        console.log(`🤖 Generating AI general exercise for topic: ${topic}, type: ${subtype}`);

        const prompt = `Create an intelligent general English exercise for ${difficulty} level learners.

Topic: ${topic}
Exercise type: ${subtype || 'general'}
Requirements:
- Create educational content appropriate for ${difficulty} level
- Generate 2-3 practical questions about real-world English usage
- For each question, create 1 CORRECT answer + 5 PLAUSIBLE wrong answers
- Wrong answers should test common English learning mistakes:
  * Vocabulary confusion (similar meanings)
  * Cultural misunderstandings
  * False friends or cognates
  * Formal vs informal register confusion
  * Common usage errors by non-native speakers
- Put correct answer FIRST, then 5 intelligent distractors
- Focus on practical, useful English skills for daily life

Return ONLY valid JSON:
{
    "title": "Intelligent English QCM: ${topic}",
    "content": "Educational content or context...",
    "questions": [
        {
            "question": "In this situation, what would be the most appropriate response?",
            "options": [
                "Correct and culturally appropriate response",
                "Too formal for the situation",
                "Too casual/informal for context",
                "Grammatically wrong but common mistake",
                "Literal translation that sounds odd",
                "Right idea but wrong cultural context"
            ],
            "hint": "Consider both grammar and cultural appropriateness"
        }
    ]
}`;

        try {
            const result = await iaEngine.validateEducationalContent(prompt, {
                systemPrompt: 'You are an English learning expert. Create practical, engaging exercises. Return ONLY valid JSON.',
                temperature: 0.6
            });

            const aiContent = this._parseAIExerciseResponse(result);
            if (!aiContent) {
                throw new Error('Invalid AI response format');
            }

            const steps = aiContent.questions.map((q, index) => {
                const shuffled = this._shuffleOptions(q.options, 0);
                return {
                    id: `ai-general-${index}`,
                    type: 'multiple-choice',
                    content: {
                        passage: aiContent.content || aiContent.passage,
                        question: q.question,
                        options: shuffled.options,
                        correctAnswer: shuffled.correctAnswer
                    },
                    hint: q.hint || "Think carefully about the context"
                };
            });

            return {
                id: `ai-general-${Date.now()}`,
                type: subtype || 'general',
                title: aiContent.title || `AI Practice: ${topic}`,
                description: `AI-generated exercise for ${topic}`,
                difficulty,
                steps,
                metadata: {
                    source: 'ai-generated-pure',
                    topic,
                    provider: 'multiple-ai-providers'
                }
            };

        } catch (error) {
            console.warn('AI general generation failed:', error.message);
            throw error;
        }
    }

    _parseAIExerciseResponse(result) {
        try {
            let content = null;

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

            if (content && (content.questions || content.passage || content.description)) {
                return content;
            }

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


    // 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);
        }
    }

    /**
     * Get content for chapter ID (for FlashcardLearning compatibility)
     */
    async getContent(chapterId) {
        console.log(`📚 Getting content for chapter: ${chapterId}`);

        try {
            const contentPath = `/content/chapters/${chapterId}.json`;
            const response = await fetch(contentPath);

            if (!response.ok) {
                console.warn(`❌ Failed to load content from ${contentPath}`);
                return null;
            }

            const content = await response.json();
            console.log(`✅ Content loaded for ${chapterId}:`, {
                hasVocabulary: !!content.vocabulary,
                vocabCount: content.vocabulary ? Object.keys(content.vocabulary).length : 0
            });

            // Emit content:loaded event for GameLoader
            this._eventBus.emit('content:loaded', {
                content,
                chapterId
            }, this.name);

            return content;

        } catch (error) {
            console.error(`❌ Error loading content for ${chapterId}:`, error);
            return null;
        }
    }

    /**
     * Extract real vocabulary for flashcards from chapter content
     */
    _extractVocabularyForFlashcards(realContent) {
        console.log('📚 Extracting real vocabulary for flashcards...');

        // Check if vocabulary exists
        if (!realContent.vocabulary || Object.keys(realContent.vocabulary).length === 0) {
            throw new Error('No vocabulary found in chapter content for flashcards');
        }

        console.log(`✅ Found ${Object.keys(realContent.vocabulary).length} vocabulary words`);

        return {
            title: `Vocabulary Flashcards - ${realContent.title || 'Chapter'}`,
            description: 'Learn vocabulary with spaced repetition flashcards',
            vocabulary: realContent.vocabulary,
            type: 'flashcards'
        };
    }

    /**
     * Generate AI vocabulary exercise for flashcards
     */
    async _generateAIVocabularyExercise(iaEngine, request) {
        console.log('📚 Generating AI vocabulary exercise for flashcards...');

        try {
            const prompt = `Generate a vocabulary learning exercise with flashcards.

Create vocabulary content suitable for language learning with these requirements:
- Practical, everyday words
- Clear definitions and usage examples
- Appropriate for ${request.difficulty || 'medium'} level
- Include pronunciation guides
- Focus on useful vocabulary

Return a JSON object with this format:
{
    "title": "Vocabulary Learning",
    "description": "Essential vocabulary with flashcards",
    "vocabulary": {
        "word1": {
            "user_language": "translation",
            "type": "noun/verb/adjective",
            "pronunciation": "/pronunciation/",
            "example": "Example sentence"
        }
    }
}`;

            const result = await iaEngine.validateEducationalContent(prompt, {
                systemPrompt: 'Generate practical vocabulary content for language learning flashcards.',
                temperature: 0.7,
                provider: 'openai'
            });

            if (result && result.content) {
                try {
                    const content = JSON.parse(result.content);
                    console.log('✅ Generated AI vocabulary exercise with', Object.keys(content.vocabulary || {}).length, 'words');
                    return content;
                } catch (parseError) {
                    console.warn('Failed to parse AI vocabulary response');
                }
            }

            // No fallback - real content only
            throw new Error('No vocabulary content available for flashcards');

        } catch (error) {
            console.error('❌ AI vocabulary generation failed:', error);
            throw error;
        }
    }

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

export default ContentLoader;
