import { Router } from 'express';
import { authenticate } from '../middlewares/auth';
import {
  getDashboardStats,
  getStudentStats,
  getRecentActivity,
  getCompleteDashboardData,
  getCompleteTeacherDashboardData,
} from '../controllers/statisticsController';

const router = Router();

/**
 * @route   GET /api/statistics/dashboard
 * @desc    Get dashboard statistics for the current user
 * @access  Private
 */
router.get('/dashboard', authenticate, getDashboardStats);

/**
 * @route   GET /api/statistics/student/:studentId
 * @desc    Get statistics for a specific student
 * @access  Private (Teacher/Admin or the student themselves)
 */
router.get('/student/:studentId', authenticate, getStudentStats);

/**
 * @route   POST /api/statistics/students
 * @desc    Get statistics for multiple students (batch)
 * @access  Private (Teacher/Admin)
 */
router.post('/students', authenticate, async (req, res, next) => {
  try {
    const { studentIds } = req.body || {};
    if (!Array.isArray(studentIds) || studentIds.length === 0) {
      return res.status(400).json({ success: false, message: 'studentIds array required' });
    }
    // Import lazily to use existing function
    const { prisma } = await import('../index');
    const results: any[] = [];
    for (const studentId of studentIds) {
      const [totalConversations, assignedBots, recentConversations] = await Promise.all([
        prisma.conversation.count({ where: { studentId } }),
        prisma.studentBotAccess.count({ where: { studentId } }),
        prisma.conversation.findMany({ where: { studentId }, select: { id: true, startedAt: true }, orderBy: { startedAt: 'desc' }, take: 1 })
      ]);
      
      // Calculate total duration from all conversations
      const allConversations = await prisma.conversation.aggregate({
        where: {
          studentId,
          durationSeconds: { not: null }
        },
        _sum: { durationSeconds: true }
      });
      const totalDurationSeconds = allConversations._sum?.durationSeconds || 0;
      
      results.push({
        studentId,
        totalConversations,
        totalDurationSeconds,
        assignedBots,
        lastActivityAt: recentConversations[0]?.startedAt || null
      });
    }
    res.json({ success: true, data: { stats: results } });
  } catch (e) {
    next(e);
  }
});

/**
 * @route   GET /api/statistics/student/:studentId/activity
 * @desc    Get activity history for a specific student (conversations with feedback and transcript)
 * @access  Private (Teacher/Admin)
 */
router.get('/student/:studentId/activity', authenticate, async (req, res, next) => {
  try {
    const { studentId } = req.params;
    const page = Number.parseInt(req.query.page as string) || 1;
    const limit = Number.parseInt(req.query.limit as string) || 10;
    const skip = (page - 1) * limit;

    // Import lazily
    const { prisma } = await import('../index');
    
    // Get conversations with feedback and full details
    const [conversations, totalCount] = await Promise.all([
      prisma.conversation.findMany({
        where: { studentId },
        select: {
          id: true,
          startedAt: true,
          endedAt: true,
          durationSeconds: true,
          summary: true,
          aiAnalysis: true,
          audioTranscript: true,
          transcript: true,
          // Campos OpenAI
          openaiSummary: true,
          openaiEvaluation: true,
          openaiFeedback: true,
          openaiTranscript: true,
          feedbackStatus: true,
          bot: {
            select: {
              id: true,
              name: true,
              topic: true,
              level: true
            }
          },
          feedback: {
            include: {
              teacher: {
                select: {
                  id: true,
                  name: true
                }
              }
            }
          }
        },
        orderBy: { startedAt: 'desc' },
        skip,
        take: limit
      }),
      prisma.conversation.count({ where: { studentId } })
    ]);

    // Format activities
    const activities = conversations.map(conv => {
      console.log('🔍 Conversation data:', {
        id: conv.id,
        hasOpenaiSummary: !!conv.openaiSummary,
        hasOpenaiEvaluation: !!conv.openaiEvaluation,
        hasOpenaiFeedback: !!conv.openaiFeedback,
        hasOpenaiTranscript: !!conv.openaiTranscript,
        feedbackStatus: conv.feedbackStatus
      });
      
      return {
        id: conv.id,
        type: 'conversation',
        title: `Conversation with ${conv.bot.name}`,
        description: `${conv.bot.topic} - Level ${conv.bot.level}`,
        timestamp: conv.startedAt,
        duration: conv.durationSeconds || 0,
        summary: conv.summary || null,
        feedback: conv.feedback || [],
        transcript: conv.audioTranscript || conv.transcript || null,
        aiAnalysis: conv.aiAnalysis || null,
        // Campos OpenAI
        openaiSummary: conv.openaiSummary || null,
        openaiEvaluation: conv.openaiEvaluation || null,
        openaiFeedback: conv.openaiFeedback || null,
        openaiTranscript: conv.openaiTranscript || null,
        feedbackStatus: conv.feedbackStatus || null,
        bot: conv.bot
      };
    });

    const totalPages = Math.ceil(totalCount / limit);

    res.json({
      success: true,
      data: {
        activities,
        pagination: {
          page,
          limit,
          totalCount,
          totalPages,
          hasNext: page < totalPages,
          hasPrev: page > 1
        }
      }
    });
  } catch (e) {
    next(e);
  }
});

/**
 * @route   GET /api/statistics/activity
 * @desc    Get recent activity for the current user
 * @access  Private
 */
router.get('/activity', authenticate, getRecentActivity);

/**
 * @route   GET /api/statistics/dashboard-complete
 * @desc    Get complete dashboard data in a single request
 * @access  Private
 */
router.get('/dashboard-complete', authenticate, getCompleteDashboardData);

/**
 * @route   GET /api/statistics/teacher-dashboard
 * @desc    Get complete teacher dashboard data (students, bots, assignments, stats)
 * @access  Private (Teacher/Admin)
 */
router.get('/teacher-dashboard', authenticate, getCompleteTeacherDashboardData);

export default router; 