/**
 * ContentDependencyAnalyzer - Intelligent content dependency analysis
 * Analyzes upcoming content to determine vocabulary prerequisites
 */

class ContentDependencyAnalyzer {
    constructor(prerequisiteEngine) {
        this.prerequisiteEngine = prerequisiteEngine;

        // Common words that don't need vocabulary learning
        this.commonWords = new Set([
            // Articles and determiners
            'a', 'an', 'the', 'this', 'that', 'these', 'those', 'some', 'any', 'each', 'every',

            // Pronouns
            'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her', 'us', 'them',
            'my', 'your', 'his', 'her', 'its', 'our', 'their', 'mine', 'yours', 'hers', 'ours', 'theirs',

            // Prepositions
            'in', 'on', 'at', 'by', 'for', 'with', 'to', 'from', 'of', 'about', 'under', 'over',
            'through', 'during', 'before', 'after', 'above', 'below', 'up', 'down', 'out', 'off',

            // Common verbs
            'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did',
            'will', 'would', 'could', 'should', 'can', 'may', 'might', 'must', 'go', 'get', 'make', 'take',

            // Conjunctions
            'and', 'or', 'but', 'because', 'if', 'when', 'where', 'how', 'why', 'what', 'who', 'which',

            // Common adverbs
            'not', 'no', 'yes', 'very', 'so', 'too', 'also', 'only', 'just', 'still', 'even', 'now', 'then',

            // Numbers
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
            'first', 'second', 'third', 'last', 'next',

            // Common adjectives
            'good', 'bad', 'big', 'small', 'new', 'old', 'long', 'short', 'high', 'low', 'right', 'left'
        ]);
    }

    /**
     * Analyze content dependencies for vocabulary requirements
     * @param {Object} nextContent - The upcoming content to analyze
     * @param {Object} vocabularyModule - The vocabulary module with available words
     * @returns {Object} - Analysis results
     */
    analyzeContentDependencies(nextContent, vocabularyModule) {
        console.log('🔍 Analyzing content dependencies:', nextContent);

        if (!nextContent || !vocabularyModule) {
            return {
                hasUnmetDependencies: false,
                missingWords: [],
                totalWordsInContent: 0,
                analysisError: 'Missing content or vocabulary module'
            };
        }

        try {
            // Extract words from content
            const wordsInContent = this.extractWordsFromContent(nextContent);
            console.log('📝 Words extracted from content:', wordsInContent);

            // Get vocabulary words from module
            const vocabularyWords = this.getVocabularyWords(vocabularyModule);
            console.log('📚 Available vocabulary words:', vocabularyWords.length);

            // Find missing words
            const missingWords = this.findMissingWords(wordsInContent, vocabularyWords);
            console.log('❌ Missing words requiring vocabulary practice:', missingWords);

            return {
                hasUnmetDependencies: missingWords.length > 0,
                missingWords: missingWords,
                totalWordsInContent: wordsInContent.length,
                vocabularyWordsInContent: wordsInContent.filter(word => vocabularyWords.includes(word)).length,
                analysisSuccess: true
            };

        } catch (error) {
            console.error('Failed to analyze content dependencies:', error);
            return {
                hasUnmetDependencies: false,
                missingWords: [],
                totalWordsInContent: 0,
                analysisError: error.message
            };
        }
    }

    /**
     * Extract words from different types of content
     * @param {Object} content - Content object with type and data
     * @returns {Array} - Array of normalized words
     */
    extractWordsFromContent(content) {
        let text = '';

        switch (content.type) {
            case 'phrase':
                text = content.text || content.phrase || '';
                break;

            case 'text':
                if (content.sentences && Array.isArray(content.sentences)) {
                    text = content.sentences.join(' ');
                } else if (content.text) {
                    text = content.text;
                } else if (content.content) {
                    text = content.content;
                }
                break;

            case 'dialog':
                if (content.lines && Array.isArray(content.lines)) {
                    text = content.lines.join(' ');
                } else if (content.dialogs && Array.isArray(content.dialogs)) {
                    text = content.dialogs.map(d => d.text || d.line || '').join(' ');
                }
                break;

            case 'audio':
                text = content.transcript || content.text || '';
                break;

            default:
                // Try to extract text from common properties
                text = content.text || content.content || content.phrase || content.sentence || '';
        }

        return this.extractWordsFromText(text);
    }

    /**
     * Extract and normalize words from raw text
     * @param {string} text - Raw text content
     * @returns {Array} - Array of normalized words
     */
    extractWordsFromText(text) {
        if (!text || typeof text !== 'string') {
            return [];
        }

        return text
            .toLowerCase()
            .replace(/[^\w\s'-]/g, ' ') // Keep apostrophes and hyphens
            .split(/\s+/)
            .filter(word => word.length > 2) // Skip very short words
            .filter(word => !this.commonWords.has(word)) // Skip common words
            .filter(word => /^[a-z'-]+$/.test(word)) // Only words with letters, apostrophes, hyphens
            .map(word => word.replace(/^[''-]+|[''-]+$/g, '')) // Remove leading/trailing punctuation
            .filter(word => word.length > 1) // Filter again after cleanup
            .filter((word, index, array) => array.indexOf(word) === index); // Remove duplicates
    }

    /**
     * Get vocabulary words from the vocabulary module
     * @param {Object} vocabularyModule - The vocabulary module
     * @returns {Array} - Array of vocabulary words
     */
    getVocabularyWords(vocabularyModule) {
        try {
            // Try different methods to get vocabulary words
            if (vocabularyModule.getVocabularyWords && typeof vocabularyModule.getVocabularyWords === 'function') {
                return vocabularyModule.getVocabularyWords();
            }

            if (vocabularyModule.vocabularyWords && Array.isArray(vocabularyModule.vocabularyWords)) {
                return vocabularyModule.vocabularyWords;
            }

            if (vocabularyModule.words && Array.isArray(vocabularyModule.words)) {
                return vocabularyModule.words.map(w => typeof w === 'string' ? w : w.word).filter(Boolean);
            }

            // Try to get from prerequisite engine
            if (this.prerequisiteEngine && this.prerequisiteEngine.chapterVocabulary) {
                return Array.from(this.prerequisiteEngine.chapterVocabulary);
            }

            console.warn('Could not extract vocabulary words from module');
            return [];

        } catch (error) {
            console.error('Error getting vocabulary words:', error);
            return [];
        }
    }

    /**
     * Find words that are in vocabulary list but not discovered by user
     * @param {Array} contentWords - Words found in content
     * @param {Array} vocabularyWords - Available vocabulary words
     * @returns {Array} - Words that need to be learned
     */
    findMissingWords(contentWords, vocabularyWords) {
        if (!Array.isArray(contentWords) || !Array.isArray(vocabularyWords)) {
            return [];
        }

        return contentWords.filter(word => {
            // Check if word is in vocabulary list
            const isInVocabulary = vocabularyWords.some(vocabWord =>
                vocabWord.toLowerCase() === word.toLowerCase()
            );

            if (!isInVocabulary) {
                return false; // Not a vocabulary word, no need to learn
            }

            // Check if word is already discovered
            const isDiscovered = this.prerequisiteEngine &&
                                 this.prerequisiteEngine.isDiscovered &&
                                 this.prerequisiteEngine.isDiscovered(word);

            return !isDiscovered; // Need to learn if not discovered
        });
    }

    /**
     * Get analysis summary for logging/debugging
     * @param {Object} analysis - Analysis result
     * @returns {string} - Formatted summary
     */
    getAnalysisSummary(analysis) {
        if (analysis.analysisError) {
            return `❌ Analysis failed: ${analysis.analysisError}`;
        }

        if (!analysis.hasUnmetDependencies) {
            return `✅ No vocabulary prerequisites needed (${analysis.totalWordsInContent} words analyzed)`;
        }

        return `📚 Vocabulary needed: ${analysis.missingWords.length} words (${analysis.missingWords.slice(0, 3).join(', ')}${analysis.missingWords.length > 3 ? '...' : ''})`;
    }
}

export default ContentDependencyAnalyzer;