/**
 * ContentProgressAnalyzer - Analyzes chapter content and creates progress items
 * Calculates total possible points and tracks completion
 */

import VocabularyDiscoveryItem from '../progress-items/VocabularyDiscoveryItem.js';
import VocabularyMasteryItem from '../progress-items/VocabularyMasteryItem.js';
import {
    PhraseItem,
    DialogItem,
    TextItem,
    AudioItem,
    ImageItem,
    GrammarItem
} from '../progress-items/ContentProgressItems.js';

class ContentProgressAnalyzer {
    constructor() {
        this.itemRegistry = new Map(); // Cache of analyzed items by chapter
    }

    /**
     * Analyze a chapter and create all progress items
     * @param {Object} chapterContent - Chapter content data
     * @param {string} chapterId - Chapter ID for caching
     * @returns {Object} - Analysis result with items and total weight
     */
    analyzeChapter(chapterContent, chapterId = 'unknown') {
        // Check cache
        if (this.itemRegistry.has(chapterId)) {
            return this.itemRegistry.get(chapterId);
        }

        const items = [];

        // 1. VOCABULARY: 2 points per word (discovery + mastery)
        if (chapterContent.vocabulary) {
            const vocabWords = Object.keys(chapterContent.vocabulary);
            console.log(`📊 Analyzing ${vocabWords.length} vocabulary words...`);

            vocabWords.forEach(word => {
                // Discovery item (1 point)
                const discoveryItem = new VocabularyDiscoveryItem(word, chapterContent.vocabulary[word]);
                discoveryItem.validate();
                items.push(discoveryItem);

                // Mastery item (1 point)
                const masteryItem = new VocabularyMasteryItem(word, chapterContent.vocabulary[word]);
                masteryItem.validate();
                items.push(masteryItem);
            });
        }

        // 2. PHRASES: 1 point per phrase
        if (chapterContent.phrases) {
            const phraseIds = Object.keys(chapterContent.phrases);
            console.log(`📊 Analyzing ${phraseIds.length} phrases...`);

            phraseIds.forEach(phraseId => {
                const phraseItem = new PhraseItem(phraseId, chapterContent.phrases[phraseId]);
                phraseItem.validate();
                items.push(phraseItem);
            });
        }

        // 3. DIALOGS: 3 points per dialog
        if (chapterContent.dialogs) {
            const dialogData = Array.isArray(chapterContent.dialogs)
                ? chapterContent.dialogs
                : Object.values(chapterContent.dialogs);

            console.log(`📊 Analyzing ${dialogData.length} dialogs...`);

            dialogData.forEach((dialog, idx) => {
                const dialogId = dialog.id || idx;
                const dialogItem = new DialogItem(dialogId, dialog);
                dialogItem.validate();
                items.push(dialogItem);
            });
        }

        // 4. LESSONS/TEXTS: 5 points per text
        if (chapterContent.lessons) {
            const lessonIds = Object.keys(chapterContent.lessons);
            console.log(`📊 Analyzing ${lessonIds.length} lessons/texts...`);

            lessonIds.forEach(lessonId => {
                const textItem = new TextItem(lessonId, chapterContent.lessons[lessonId]);
                textItem.validate();
                items.push(textItem);
            });
        }

        // 5. AUDIOS: 4 points per audio
        if (chapterContent.audios) {
            const audioIds = Object.keys(chapterContent.audios);
            console.log(`📊 Analyzing ${audioIds.length} audios...`);

            audioIds.forEach(audioId => {
                const audioItem = new AudioItem(audioId, chapterContent.audios[audioId]);
                audioItem.validate();
                items.push(audioItem);
            });
        }

        // 6. IMAGES: 2 points per image
        if (chapterContent.images) {
            const images = Array.isArray(chapterContent.images)
                ? chapterContent.images
                : Object.values(chapterContent.images);

            console.log(`📊 Analyzing ${images.length} images...`);

            images.forEach((img, idx) => {
                const imageItem = new ImageItem(idx, img);
                imageItem.validate();
                items.push(imageItem);
            });
        }

        // 7. GRAMMAR: 2 points per rule
        if (chapterContent.grammar) {
            const grammarRules = Array.isArray(chapterContent.grammar)
                ? chapterContent.grammar
                : Object.values(chapterContent.grammar);

            console.log(`📊 Analyzing ${grammarRules.length} grammar rules...`);

            grammarRules.forEach((rule, idx) => {
                const grammarItem = new GrammarItem(idx, rule);
                grammarItem.validate();
                items.push(grammarItem);
            });
        }

        // Calculate total weight
        const totalWeight = items.reduce((sum, item) => sum + item.getWeight(), 0);

        const analysis = {
            chapterId,
            items,
            totalWeight,
            breakdown: this._getBreakdown(items)
        };

        // Cache result
        this.itemRegistry.set(chapterId, analysis);

        console.log(`✅ Chapter analysis complete: ${totalWeight} total points`);
        console.log('📊 Breakdown:', analysis.breakdown);

        return analysis;
    }

    /**
     * Get breakdown by item type
     * @private
     */
    _getBreakdown(items) {
        const breakdown = {};

        items.forEach(item => {
            if (!breakdown[item.type]) {
                breakdown[item.type] = { count: 0, weight: 0 };
            }
            breakdown[item.type].count++;
            breakdown[item.type].weight += item.getWeight();
        });

        return breakdown;
    }

    /**
     * Calculate progress percentage
     * @param {string} chapterId - Chapter ID
     * @param {Array} completedItems - Array of completed item IDs
     * @returns {Object} - Progress data
     */
    calculateProgress(chapterId, completedItems) {
        const analysis = this.itemRegistry.get(chapterId);

        if (!analysis) {
            throw new Error(`No analysis found for chapter: ${chapterId}`);
        }

        let completedWeight = 0;
        const completedBreakdown = {};

        completedItems.forEach(itemId => {
            const item = analysis.items.find(i => i.id === itemId);
            if (item) {
                completedWeight += item.getWeight();

                if (!completedBreakdown[item.type]) {
                    completedBreakdown[item.type] = { count: 0, weight: 0 };
                }
                completedBreakdown[item.type].count++;
                completedBreakdown[item.type].weight += item.getWeight();
            }
        });

        const percentage = analysis.totalWeight > 0
            ? Math.round((completedWeight / analysis.totalWeight) * 100)
            : 0;

        return {
            percentage,
            completedWeight,
            totalWeight: analysis.totalWeight,
            breakdown: analysis.breakdown,
            completedBreakdown
        };
    }

    /**
     * Clear cache
     */
    clearCache() {
        this.itemRegistry.clear();
    }
}

export default ContentProgressAnalyzer;
