/**
 * AIReportSystem - Système d'export et de rapport des explications de l'IA
 * Capture et formate les réponses détaillées de l'IAEngine pour les étudiants
 */

class AIReportSystem {
    constructor(config = {}) {
        this.config = {
            includeTimestamps: config.includeTimestamps !== false,
            formatStyle: config.formatStyle || 'detailed', // 'detailed', 'summary', 'json'
            language: config.language || 'fr',
            includeScores: config.includeScores !== false,
            ...config
        };

        // Stockage des sessions d'apprentissage
        this.sessionReports = new Map();
        this.currentSessionId = null;
    }

    /**
     * Démarre une nouvelle session de rapport
     * @param {Object} sessionInfo - Informations de la session
     * @returns {string} - ID de session
     */
    startSession(sessionInfo = {}) {
        const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

        const session = {
            id: sessionId,
            startTime: new Date(),
            endTime: null,
            exerciseCount: 0,
            totalScore: 0,
            averageScore: 0,
            sessionInfo: {
                bookId: sessionInfo.bookId || 'unknown',
                chapterId: sessionInfo.chapterId || 'unknown',
                difficulty: sessionInfo.difficulty || 'medium',
                exerciseTypes: sessionInfo.exerciseTypes || [],
                ...sessionInfo
            },
            exercises: [],
            aiInteractions: [],
            summary: {
                strengths: [],
                areasForImprovement: [],
                keyLearnings: [],
                recommendations: []
            }
        };

        this.sessionReports.set(sessionId, session);
        this.currentSessionId = sessionId;

        console.log(`📊 Started AI report session: ${sessionId}`);
        return sessionId;
    }

    /**
     * Ajoute une réponse IA au rapport
     * @param {Object} aiResponse - Réponse de l'IAEngine
     * @param {Object} exerciseContext - Contexte de l'exercice
     */
    addAIResponse(aiResponse, exerciseContext = {}) {
        if (!this.currentSessionId) {
            console.warn('⚠️ No active session for AI report');
            return;
        }

        const session = this.sessionReports.get(this.currentSessionId);
        if (!session) {
            console.error('❌ Session not found:', this.currentSessionId);
            return;
        }

        // Créer l'entrée de rapport
        const reportEntry = {
            timestamp: new Date(),
            exerciseType: exerciseContext.exerciseType || 'unknown',
            exerciseStep: exerciseContext.exerciseStep || 0,
            originalContent: exerciseContext.originalContent || '',
            userAnswer: exerciseContext.userAnswer || '',
            aiResponse: {
                score: aiResponse.score || 0,
                correct: aiResponse.correct || false,
                feedback: aiResponse.feedback || '',
                encouragement: aiResponse.encouragement || '',
                keyPoints: aiResponse.keyPoints || [],
                mainPointsUnderstood: aiResponse.mainPointsUnderstood || [],
                grammarErrors: aiResponse.grammarErrors || [],
                grammarStrengths: aiResponse.grammarStrengths || [],
                suggestion: aiResponse.suggestion || '',
                vocabularyUsed: aiResponse.vocabularyUsed || [],
                creativityScore: aiResponse.creativityScore || null
            },
            context: {
                difficulty: exerciseContext.difficulty || session.sessionInfo.difficulty,
                exerciseNumber: session.exerciseCount + 1,
                ...exerciseContext
            }
        };

        // Ajouter au rapport de session
        session.exercises.push(reportEntry);
        session.aiInteractions.push(reportEntry);
        session.exerciseCount++;

        if (aiResponse.score !== undefined) {
            session.totalScore += aiResponse.score;
            session.averageScore = session.totalScore / session.exerciseCount;
        }

        // Extraire les points d'apprentissage
        this._extractLearningPoints(reportEntry, session);

        console.log(`📝 Added AI response to report (Exercise ${session.exerciseCount})`);
    }

    /**
     * Extrait les points d'apprentissage de la réponse IA
     * @private
     */
    _extractLearningPoints(reportEntry, session) {
        const response = reportEntry.aiResponse;

        // Points forts
        if (response.grammarStrengths && response.grammarStrengths.length > 0) {
            response.grammarStrengths.forEach(strength => {
                if (!session.summary.strengths.includes(strength)) {
                    session.summary.strengths.push(strength);
                }
            });
        }

        // Domaines d'amélioration
        if (response.grammarErrors && response.grammarErrors.length > 0) {
            response.grammarErrors.forEach(error => {
                if (!session.summary.areasForImprovement.includes(error)) {
                    session.summary.areasForImprovement.push(error);
                }
            });
        }

        // Points clés compris
        if (response.keyPoints && response.keyPoints.length > 0) {
            response.keyPoints.forEach(point => {
                if (!session.summary.keyLearnings.includes(point)) {
                    session.summary.keyLearnings.push(point);
                }
            });
        }

        // Suggestions
        if (response.suggestion && !session.summary.recommendations.includes(response.suggestion)) {
            session.summary.recommendations.push(response.suggestion);
        }
    }

    /**
     * Termine la session actuelle
     */
    endSession() {
        if (!this.currentSessionId) {
            console.warn('⚠️ No active session to end');
            return;
        }

        const session = this.sessionReports.get(this.currentSessionId);
        if (session) {
            session.endTime = new Date();
            session.duration = session.endTime - session.startTime;
        }

        console.log(`📊 Ended AI report session: ${this.currentSessionId}`);
        this.currentSessionId = null;
    }

    /**
     * Génère un rapport de session formaté
     * @param {string} sessionId - ID de la session (optionnel, utilise la session courante si non spécifié)
     * @param {string} format - Format du rapport ('text', 'html', 'json')
     * @returns {string} - Rapport formaté
     */
    generateReport(sessionId = null, format = 'text') {
        const targetSessionId = sessionId || this.currentSessionId;
        if (!targetSessionId) {
            throw new Error('No session available for report generation');
        }

        const session = this.sessionReports.get(targetSessionId);
        if (!session) {
            throw new Error(`Session not found: ${targetSessionId}`);
        }

        switch (format.toLowerCase()) {
            case 'html':
                return this._generateHTMLReport(session);
            case 'json':
                return this._generateJSONReport(session);
            case 'text':
            default:
                return this._generateTextReport(session);
        }
    }

    /**
     * Génère un rapport texte formaté
     * @private
     */
    _generateTextReport(session) {
        const lines = [];

        // En-tête
        lines.push('='.repeat(60));
        lines.push('📚 RAPPORT D\'APPRENTISSAGE IA');
        lines.push('='.repeat(60));
        lines.push('');

        // Informations de session
        lines.push(`📖 Livre/Chapitre: ${session.sessionInfo.bookId}/${session.sessionInfo.chapterId}`);
        lines.push(`🎯 Difficulté: ${session.sessionInfo.difficulty}`);
        lines.push(`📅 Date: ${session.startTime.toLocaleDateString('fr-FR')}`);
        lines.push(`⏱️ Heure: ${session.startTime.toLocaleTimeString('fr-FR')}`);
        if (session.endTime) {
            const duration = Math.round((session.endTime - session.startTime) / 1000 / 60);
            lines.push(`⏰ Durée: ${duration} minutes`);
        }
        lines.push('');

        // Statistiques générales
        lines.push('📊 STATISTIQUES GÉNÉRALES');
        lines.push('-'.repeat(30));
        lines.push(`• Exercices complétés: ${session.exerciseCount}`);
        if (session.averageScore > 0) {
            lines.push(`• Score moyen: ${Math.round(session.averageScore)}%`);
        }
        lines.push('');

        // Détails des exercices
        if (session.exercises.length > 0) {
            lines.push('📝 DÉTAIL DES EXERCICES');
            lines.push('-'.repeat(30));

            session.exercises.forEach((exercise, index) => {
                const response = exercise.aiResponse;
                lines.push(`\n${index + 1}. ${exercise.exerciseType.toUpperCase()} (${exercise.timestamp.toLocaleTimeString('fr-FR')})`);

                if (exercise.originalContent) {
                    lines.push(`   💡 Contenu: ${exercise.originalContent.substring(0, 100)}${exercise.originalContent.length > 100 ? '...' : ''}`);
                }

                if (exercise.userAnswer) {
                    lines.push(`   ✏️ Réponse: ${exercise.userAnswer}`);
                }

                if (response.score !== undefined) {
                    lines.push(`   🎯 Score: ${response.score}% ${response.correct ? '✅' : '❌'}`);
                }

                if (response.feedback) {
                    lines.push(`   📢 Retour: ${response.feedback}`);
                }

                if (response.encouragement) {
                    lines.push(`   💪 Encouragement: ${response.encouragement}`);
                }

                if (response.keyPoints && response.keyPoints.length > 0) {
                    lines.push(`   🔑 Points clés: ${response.keyPoints.join(', ')}`);
                }

                if (response.suggestion) {
                    lines.push(`   💡 Suggestion: ${response.suggestion}`);
                }
            });
        }

        // Résumé d'apprentissage
        lines.push('\n📈 RÉSUMÉ D\'APPRENTISSAGE');
        lines.push('-'.repeat(30));

        if (session.summary.strengths.length > 0) {
            lines.push('\n✅ Points forts:');
            session.summary.strengths.forEach(strength => lines.push(`   • ${strength}`));
        }

        if (session.summary.areasForImprovement.length > 0) {
            lines.push('\n🔄 Domaines d\'amélioration:');
            session.summary.areasForImprovement.forEach(area => lines.push(`   • ${area}`));
        }

        if (session.summary.keyLearnings.length > 0) {
            lines.push('\n🧠 Apprentissages clés:');
            session.summary.keyLearnings.forEach(learning => lines.push(`   • ${learning}`));
        }

        if (session.summary.recommendations.length > 0) {
            lines.push('\n🎯 Recommandations:');
            session.summary.recommendations.forEach(rec => lines.push(`   • ${rec}`));
        }

        lines.push('\n' + '='.repeat(60));
        lines.push('🎓 Rapport généré par Class Generator 2.0');
        lines.push('='.repeat(60));

        return lines.join('\n');
    }

    /**
     * Génère un rapport HTML formaté
     * @private
     */
    _generateHTMLReport(session) {
        const html = `
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rapport d'Apprentissage IA - ${session.sessionInfo.bookId}</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; text-align: center; margin-bottom: 20px; }
        .stats { background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0; }
        .exercise { border-left: 4px solid #007bff; padding: 15px; margin: 15px 0; background: #ffffff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .score-good { color: #28a745; font-weight: bold; }
        .score-medium { color: #ffc107; font-weight: bold; }
        .score-poor { color: #dc3545; font-weight: bold; }
        .summary { background: #e9ecef; padding: 20px; border-radius: 8px; margin-top: 20px; }
        .tag { display: inline-block; background: #007bff; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.8em; margin: 2px; }
        .feedback { font-style: italic; color: #666; margin: 10px 0; padding: 10px; background: #f8f9fa; border-radius: 5px; }
        .encouragement { color: #28a745; font-weight: 500; margin: 10px 0; }
    </style>
</head>
<body>
    <div class="header">
        <h1>📚 Rapport d'Apprentissage IA</h1>
        <p>${session.sessionInfo.bookId} - ${session.sessionInfo.chapterId}</p>
        <p>${session.startTime.toLocaleDateString('fr-FR')} à ${session.startTime.toLocaleTimeString('fr-FR')}</p>
    </div>

    <div class="stats">
        <h3>📊 Statistiques</h3>
        <p><strong>Exercices complétés:</strong> ${session.exerciseCount}</p>
        ${session.averageScore > 0 ? `<p><strong>Score moyen:</strong> <span class="${this._getScoreClass(session.averageScore)}">${Math.round(session.averageScore)}%</span></p>` : ''}
        <p><strong>Difficulté:</strong> ${session.sessionInfo.difficulty}</p>
        ${session.duration ? `<p><strong>Durée:</strong> ${Math.round(session.duration / 1000 / 60)} minutes</p>` : ''}
    </div>

    <h3>📝 Détail des exercices</h3>
    ${session.exercises.map((exercise, index) => `
        <div class="exercise">
            <h4>${index + 1}. ${exercise.exerciseType.toUpperCase()} - ${exercise.timestamp.toLocaleTimeString('fr-FR')}</h4>

            ${exercise.originalContent ? `<p><strong>💡 Contenu:</strong> ${exercise.originalContent}</p>` : ''}
            ${exercise.userAnswer ? `<p><strong>✏️ Votre réponse:</strong> ${exercise.userAnswer}</p>` : ''}

            ${exercise.aiResponse.score !== undefined ? `
                <p><strong>🎯 Score:</strong>
                   <span class="${this._getScoreClass(exercise.aiResponse.score)}">${exercise.aiResponse.score}%</span>
                   ${exercise.aiResponse.correct ? '✅' : '❌'}
                </p>
            ` : ''}

            ${exercise.aiResponse.feedback ? `<div class="feedback">📢 <strong>Retour:</strong> ${exercise.aiResponse.feedback}</div>` : ''}
            ${exercise.aiResponse.encouragement ? `<div class="encouragement">💪 ${exercise.aiResponse.encouragement}</div>` : ''}

            ${exercise.aiResponse.keyPoints && exercise.aiResponse.keyPoints.length > 0 ? `
                <p><strong>🔑 Points clés:</strong><br>
                ${exercise.aiResponse.keyPoints.map(point => `<span class="tag">${point}</span>`).join('')}</p>
            ` : ''}

            ${exercise.aiResponse.suggestion ? `<p><strong>💡 Suggestion:</strong> ${exercise.aiResponse.suggestion}</p>` : ''}
        </div>
    `).join('')}

    <div class="summary">
        <h3>📈 Résumé d'apprentissage</h3>

        ${session.summary.strengths.length > 0 ? `
            <h4>✅ Points forts</h4>
            <ul>${session.summary.strengths.map(s => `<li>${s}</li>`).join('')}</ul>
        ` : ''}

        ${session.summary.areasForImprovement.length > 0 ? `
            <h4>🔄 Domaines d'amélioration</h4>
            <ul>${session.summary.areasForImprovement.map(a => `<li>${a}</li>`).join('')}</ul>
        ` : ''}

        ${session.summary.keyLearnings.length > 0 ? `
            <h4>🧠 Apprentissages clés</h4>
            <ul>${session.summary.keyLearnings.map(l => `<li>${l}</li>`).join('')}</ul>
        ` : ''}

        ${session.summary.recommendations.length > 0 ? `
            <h4>🎯 Recommandations</h4>
            <ul>${session.summary.recommendations.map(r => `<li>${r}</li>`).join('')}</ul>
        ` : ''}
    </div>

    <footer style="text-align: center; margin-top: 40px; color: #666; border-top: 1px solid #ddd; padding-top: 20px;">
        🎓 Rapport généré par Class Generator 2.0 - ${new Date().toLocaleDateString('fr-FR')}
    </footer>
</body>
</html>`;

        return html;
    }

    /**
     * Génère un rapport JSON
     * @private
     */
    _generateJSONReport(session) {
        return JSON.stringify(session, null, 2);
    }

    /**
     * Obtient la classe CSS pour un score
     * @private
     */
    _getScoreClass(score) {
        if (score >= 80) return 'score-good';
        if (score >= 60) return 'score-medium';
        return 'score-poor';
    }

    /**
     * Exporte un rapport vers un fichier
     * @param {string} sessionId - ID de la session
     * @param {string} format - Format du fichier ('text', 'html', 'json')
     * @param {string} filename - Nom du fichier (optionnel)
     * @returns {string} - URL de téléchargement
     */
    exportReport(sessionId = null, format = 'text', filename = null) {
        const session = this.sessionReports.get(sessionId || this.currentSessionId);
        if (!session) {
            throw new Error('Session not found for export');
        }

        const content = this.generateReport(sessionId, format);

        // Créer le nom de fichier
        const defaultFilename = `rapport_ia_${session.sessionInfo.bookId}_${session.sessionInfo.chapterId}_${new Date().toISOString().split('T')[0]}.${format}`;
        const finalFilename = filename || defaultFilename;

        // Créer un blob et une URL de téléchargement
        const mimeTypes = {
            'text': 'text/plain;charset=utf-8',
            'html': 'text/html;charset=utf-8',
            'json': 'application/json;charset=utf-8'
        };

        const blob = new Blob([content], { type: mimeTypes[format] || 'text/plain' });
        const url = URL.createObjectURL(blob);

        // Déclencher le téléchargement
        const a = document.createElement('a');
        a.href = url;
        a.download = finalFilename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

        // Nettoyer l'URL
        setTimeout(() => URL.revokeObjectURL(url), 100);

        console.log(`📥 Exported AI report: ${finalFilename}`);
        return url;
    }

    /**
     * Obtient toutes les sessions
     * @returns {Array} - Liste des sessions
     */
    getAllSessions() {
        return Array.from(this.sessionReports.values());
    }

    /**
     * Supprime une session
     * @param {string} sessionId - ID de la session à supprimer
     */
    deleteSession(sessionId) {
        if (this.sessionReports.delete(sessionId)) {
            console.log(`🗑️ Deleted AI report session: ${sessionId}`);

            // Si c'est la session courante, la réinitialiser
            if (this.currentSessionId === sessionId) {
                this.currentSessionId = null;
            }
        }
    }

    /**
     * Nettoie les anciennes sessions (plus de X jours)
     * @param {number} daysOld - Nombre de jours (défaut: 30)
     */
    cleanupOldSessions(daysOld = 30) {
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - daysOld);

        let deletedCount = 0;
        for (const [sessionId, session] of this.sessionReports.entries()) {
            if (session.startTime < cutoffDate) {
                this.sessionReports.delete(sessionId);
                deletedCount++;
            }
        }

        console.log(`🧹 Cleaned up ${deletedCount} old AI report sessions`);
    }

    /**
     * Obtient les statistiques globales de toutes les sessions
     * @returns {Object} - Statistiques globales
     */
    getGlobalStats() {
        const sessions = this.getAllSessions();

        if (sessions.length === 0) {
            return {
                totalSessions: 0,
                totalExercises: 0,
                averageScore: 0,
                mostCommonExerciseType: null,
                totalTimeSpent: 0
            };
        }

        const totalExercises = sessions.reduce((sum, session) => sum + session.exerciseCount, 0);
        const totalScore = sessions.reduce((sum, session) => sum + session.totalScore, 0);
        const averageScore = totalExercises > 0 ? totalScore / totalExercises : 0;

        // Types d'exercices les plus courants
        const exerciseTypes = {};
        sessions.forEach(session => {
            session.exercises.forEach(exercise => {
                exerciseTypes[exercise.exerciseType] = (exerciseTypes[exercise.exerciseType] || 0) + 1;
            });
        });

        const mostCommonExerciseType = Object.keys(exerciseTypes).reduce((a, b) =>
            exerciseTypes[a] > exerciseTypes[b] ? a : b, null);

        // Temps total passé
        const totalTimeSpent = sessions
            .filter(session => session.duration)
            .reduce((sum, session) => sum + session.duration, 0);

        return {
            totalSessions: sessions.length,
            totalExercises,
            averageScore: Math.round(averageScore),
            mostCommonExerciseType,
            totalTimeSpent: Math.round(totalTimeSpent / 1000 / 60), // en minutes
            exerciseTypeDistribution: exerciseTypes
        };
    }
}

export default AIReportSystem;