/**
 * ASL 筛选服务
 * 使用真实LLM进行双模型筛选
 */

import { prisma } from '../../../config/database.js';
import { logger } from '../../../common/logging/index.js';
import { llmScreeningService } from './llmScreeningService.js';

/**
 * 启动筛选任务（简化版）
 * 
 * 注意：这是MVP版本，使用模拟AI判断
 * 生产环境应该：
 * 1. 使用消息队列异步处理
 * 2. 调用真实的DeepSeek和Qwen API
 * 3. 实现错误重试机制
 */
export async function startScreeningTask(projectId: string, userId: string) {
  try {
    logger.info('Starting screening task', { projectId, userId });

    // 1. 检查项目是否存在
    const project = await prisma.aslScreeningProject.findFirst({
      where: { id: projectId, userId },
    });

    if (!project) {
      throw new Error('Project not found');
    }

    // 2. 获取该项目的所有文献
    const literatures = await prisma.aslLiterature.findMany({
      where: { projectId },
    });

    if (literatures.length === 0) {
      throw new Error('No literatures found in project');
    }

    logger.info('Found literatures for screening', { 
      projectId, 
      count: literatures.length 
    });

    // 3. 创建筛选任务
    const task = await prisma.aslScreeningTask.create({
      data: {
        projectId,
        taskType: 'title_abstract',
        status: 'running',
        totalItems: literatures.length,
        processedItems: 0,
        successItems: 0,
        failedItems: 0,
        conflictItems: 0,
        startedAt: new Date(),
      },
    });

    logger.info('Screening task created', { taskId: task.id });

    // 4. 异步处理文献（简化版：直接在这里处理）
    // 生产环境应该发送到消息队列
    processLiteraturesInBackground(task.id, projectId, literatures);

    return task;
  } catch (error) {
    logger.error('Failed to start screening task', { error, projectId });
    throw error;
  }
}

/**
 * 后台处理文献（真实LLM调用）
 */
async function processLiteraturesInBackground(
  taskId: string,
  projectId: string,
  literatures: any[]
) {
  try {
    // 1. 获取项目的PICOS标准
    const project = await prisma.aslScreeningProject.findUnique({
      where: { id: projectId },
    });

    if (!project) {
      throw new Error('Project not found');
    }

    // 🔧 修复：字段名映射（数据库格式 → LLM服务格式）
    const rawPicoCriteria = project.picoCriteria as any;
    const picoCriteria = {
      P: rawPicoCriteria?.P || rawPicoCriteria?.population || '',
      I: rawPicoCriteria?.I || rawPicoCriteria?.intervention || '',
      C: rawPicoCriteria?.C || rawPicoCriteria?.comparison || '',
      O: rawPicoCriteria?.O || rawPicoCriteria?.outcome || '',
      S: rawPicoCriteria?.S || rawPicoCriteria?.studyDesign || '',
    };
    
    const inclusionCriteria = project.inclusionCriteria || '';
    const exclusionCriteria = project.exclusionCriteria || '';
    const screeningConfig = project.screeningConfig as any;
    
    // 🔧 修复：模型名映射（前端格式 → API格式）
    const MODEL_NAME_MAP: Record<string, string> = {
      'DeepSeek-V3': 'deepseek-chat',
      'Qwen-Max': 'qwen-max',
      'GPT-4o': 'gpt-4o',
      'Claude-4.5': 'claude-sonnet-4.5',
      'deepseek-chat': 'deepseek-chat',  // 兼容直接使用API名
      'qwen-max': 'qwen-max',
      'gpt-4o': 'gpt-4o',
      'claude-sonnet-4.5': 'claude-sonnet-4.5',
    };
    
    const rawModels = screeningConfig?.models || ['deepseek-chat', 'qwen-max'];
    const models = rawModels.map((m: string) => MODEL_NAME_MAP[m] || m);

    logger.info('Starting real LLM screening', {
      taskId,
      projectId,
      totalLiteratures: literatures.length,
      models,
    });

    // 🔍 调试：输出关键信息到控制台
    console.log('\n🚀 开始真实LLM筛选:');
    console.log('  任务ID:', taskId);
    console.log('  项目ID:', projectId);
    console.log('  文献数:', literatures.length);
    console.log('  模型（映射后）:', models);
    console.log('  PICOS-P:', picoCriteria.P?.substring(0, 50) || '(空)');
    console.log('  PICOS-I:', picoCriteria.I?.substring(0, 50) || '(空)');
    console.log('  PICOS-C:', picoCriteria.C?.substring(0, 50) || '(空)');
    console.log('  纳入标准:', inclusionCriteria?.substring(0, 50) || '(空)');
    console.log('  排除标准:', exclusionCriteria?.substring(0, 50) || '(空)');
    console.log('');

    let processedCount = 0;
    let successCount = 0;
    let conflictCount = 0;

    // 2. 逐篇处理文献（串行处理，避免API限流）
    for (const literature of literatures) {
      try {
        // 🔧 验证：必须有标题和摘要
        if (!literature.title || !literature.abstract) {
          logger.warn('Skipping literature without title or abstract', {
            literatureId: literature.id,
            hasTitle: !!literature.title,
            hasAbstract: !!literature.abstract,
          });
          console.log(`⚠️  跳过文献 ${processedCount + 1}: 缺少标题或摘要`);
          processedCount++;
          continue;
        }

        logger.info('Processing literature', {
          literatureId: literature.id,
          title: literature.title?.substring(0, 50) + '...',
        });

        // 3. 调用真实的双模型筛选
        const screeningResult = await llmScreeningService.dualModelScreening(
          literature.id,
          literature.title,
          literature.abstract,
          picoCriteria as any,  // 已做映射，类型安全
          inclusionCriteria,
          exclusionCriteria,
          [models[0], models[1]],
          screeningConfig?.style || 'standard',
          literature.authors,
          literature.journal,
          literature.publicationYear
        );

        // 4. 映射结果到数据库格式
        const dbResult = {
          projectId,
          literatureId: literature.id,

          // DeepSeek结果
          dsModelName: screeningResult.deepseekModel,
          dsPJudgment: screeningResult.deepseek.judgment.P,
          dsIJudgment: screeningResult.deepseek.judgment.I,
          dsCJudgment: screeningResult.deepseek.judgment.C,
          dsSJudgment: screeningResult.deepseek.judgment.S,
          dsConclusion: screeningResult.deepseek.conclusion,
          dsConfidence: screeningResult.deepseek.confidence,
          dsPEvidence: screeningResult.deepseek.evidence.P,
          dsIEvidence: screeningResult.deepseek.evidence.I,
          dsCEvidence: screeningResult.deepseek.evidence.C,
          dsSEvidence: screeningResult.deepseek.evidence.S,
          dsReason: screeningResult.deepseek.reason,

          // Qwen结果
          qwenModelName: screeningResult.qwenModel,
          qwenPJudgment: screeningResult.qwen.judgment.P,
          qwenIJudgment: screeningResult.qwen.judgment.I,
          qwenCJudgment: screeningResult.qwen.judgment.C,
          qwenSJudgment: screeningResult.qwen.judgment.S,
          qwenConclusion: screeningResult.qwen.conclusion,
          qwenConfidence: screeningResult.qwen.confidence,
          qwenPEvidence: screeningResult.qwen.evidence.P,
          qwenIEvidence: screeningResult.qwen.evidence.I,
          qwenCEvidence: screeningResult.qwen.evidence.C,
          qwenSEvidence: screeningResult.qwen.evidence.S,
          qwenReason: screeningResult.qwen.reason,

          // 冲突状态
          conflictStatus: screeningResult.hasConflict ? 'conflict' : 'none',
          ...(screeningResult.conflictFields ? { conflictFields: screeningResult.conflictFields } : {}),

          // 最终决策
          finalDecision: screeningResult.finalDecision === 'pending' ? null : screeningResult.finalDecision,

          // AI处理状态
          aiProcessingStatus: 'completed',
          aiProcessedAt: new Date(),

          // 可追溯信息
          promptVersion: 'v1.0.0-mvp',
          rawOutput: JSON.parse(JSON.stringify({
            deepseek: screeningResult.deepseek,
            qwen: screeningResult.qwen,
          })),
        };

        // 5. 保存结果到数据库
        await prisma.aslScreeningResult.create({
          data: dbResult,
        });

        successCount++;
        if (screeningResult.hasConflict) {
          conflictCount++;
        }

        logger.info('Literature processed successfully', {
          literatureId: literature.id,
          dsConclusion: screeningResult.deepseek.conclusion,
          qwenConclusion: screeningResult.qwen.conclusion,
          hasConflict: screeningResult.hasConflict,
        });

        // 🔍 调试：成功处理
        console.log(`✅ 文献 ${processedCount+1}/${literatures.length} 处理成功`);
        console.log('  DS:', screeningResult.deepseek.conclusion, '/', 'Qwen:', screeningResult.qwen.conclusion);
        console.log('  冲突:', screeningResult.hasConflict ? '是' : '否');
      } catch (error) {
        logger.error('Failed to process literature', {
          literatureId: literature.id,
          error: error instanceof Error ? error.message : 'Unknown error',
          stack: error instanceof Error ? error.stack : undefined,
        });
        
        // 🔍 调试：输出到控制台
        console.error('\n❌ 文献处理失败:');
        console.error('  文献ID:', literature.id);
        console.error('  标题:', literature.title?.substring(0, 60));
        console.error('  错误:', error);
        console.error('');
        
        // 继续处理下一篇文献
      }

      processedCount++;

      // 6. 更新任务进度（每1条更新一次，保证前端能及时看到进度）
      await prisma.aslScreeningTask.update({
        where: { id: taskId },
        data: {
          processedItems: processedCount,
          successItems: successCount,
          conflictItems: conflictCount,
          failedItems: processedCount - successCount,
        },
      });

      if (processedCount % 5 === 0 || processedCount === literatures.length) {
        logger.info('Task progress updated', {
          taskId,
          progress: `${processedCount}/${literatures.length}`,
          success: successCount,
          conflicts: conflictCount,
        });
      }
    }

    // 7. 标记任务完成
    await prisma.aslScreeningTask.update({
      where: { id: taskId },
      data: {
        status: 'completed',
        processedItems: literatures.length,
        successItems: successCount,
        conflictItems: conflictCount,
        failedItems: literatures.length - successCount,
        completedAt: new Date(),
      },
    });

    logger.info('Screening task completed', {
      taskId,
      total: literatures.length,
      success: successCount,
      conflicts: conflictCount,
      failed: literatures.length - successCount,
    });
  } catch (error) {
    logger.error('Background processing failed', { taskId, error });

    // 标记任务失败
    await prisma.aslScreeningTask.update({
      where: { id: taskId },
      data: {
        status: 'failed',
        errorMessage: error instanceof Error ? error.message : 'Unknown error',
      },
    });
  }
}

// 已移除 mockAIScreening 函数，现在使用真实的 LLM 调用
// 如果需要测试模式，请在环境变量中设置 USE_MOCK_AI=true

