import { NextRequest, NextResponse } from 'next/server';
import { ProjectService, EvaluationService } from '@/lib/services/database';

export async function GET(request: NextRequest) {
  try {
    console.log('📊 開始獲取統計數據...');

    // 獲取所有專案
    const projects = await ProjectService.getAll();
    console.log(`📋 找到 ${projects.length} 個專案`);

    // 計算統計數據
    const totalProjects = projects.length;
    const completedProjects = projects.filter(p => p.status === 'completed').length;
    const processingProjects = projects.filter(p => p.status === 'analyzing' || p.status === 'pending').length;

    // 計算平均分數
    let totalScore = 0;
    let scoredProjects = 0;

    for (const project of projects) {
      if (project.status === 'completed') {
        const evaluation = await EvaluationService.findByProjectId(project.id);
        console.log(`專案 ${project.id} (${project.title}): 狀態=${project.status}, 評審=${evaluation ? '有' : '無'}, 分數=${evaluation?.overall_score || '無'}`);
        if (evaluation && evaluation.overall_score) {
          // 確保 overall_score 是數字類型
          const score = Number(evaluation.overall_score);
          if (!isNaN(score)) {
            totalScore += score;
            scoredProjects++;
          } else {
            console.warn(`專案 ${project.id} 的分數不是有效數字: ${evaluation.overall_score}`);
          }
        }
      }
    }

    const averageScore = scoredProjects > 0 ? Math.round(totalScore / scoredProjects) : 0;
    console.log(`平均分數計算: 總分=${totalScore}, 有分數的專案數=${scoredProjects}, 平均分數=${averageScore}`);
    
    // 額外的調試信息
    if (scoredProjects === 0) {
      console.log('⚠️ 沒有找到任何有分數的專案');
    } else {
      console.log(`✅ 成功計算平均分數: ${averageScore}`);
    }

    const stats = {
      totalProjects,
      completedProjects,
      processingProjects,
      averageScore
    };

    console.log('✅ 統計數據:', stats);

    return NextResponse.json({
      success: true,
      data: stats
    });

  } catch (error) {
    console.error('❌ 獲取統計數據失敗:', error);
    return NextResponse.json(
      { success: false, error: '獲取統計數據失敗' },
      { status: 500 }
    );
  }
}
