import type { FastifyRequest, FastifyReply } from 'fastify';
import * as reviewService from '../services/reviewService.js';
import { ModelType } from '../../common/llm/adapters/types.js';

// Mock用户ID（实际应从JWT token中获取）
const MOCK_USER_ID = 'user-mock-001';

/**
 * 上传稿件并开始审查
 * POST /api/review/upload
 */
export async function uploadManuscript(
  request: FastifyRequest<{
    Body: {
      modelType?: string;
    };
  }>,
  reply: FastifyReply
) {
  try {
    console.log('📤 开始上传稿件进行审查...');

    // 获取上传的文件
    const data = await request.file();

    if (!data) {
      console.error('❌ 没有接收到文件');
      return reply.status(400).send({
        success: false,
        message: 'No file uploaded',
      });
    }

    console.log(`📄 接收到文件: ${data.filename}, 类型: ${data.mimetype}`);

    const file = await data.toBuffer();
    const filename = data.filename;
    const fileType = data.mimetype;
    const fileSizeBytes = file.length;

    // 文件大小限制（5MB，稿件通常不会太大）
    const maxSize = 5 * 1024 * 1024;
    console.log(`📊 文件大小: ${(fileSizeBytes / 1024 / 1024).toFixed(2)}MB (限制: 5MB)`);

    if (fileSizeBytes > maxSize) {
      console.error(`❌ 文件太大: ${(fileSizeBytes / 1024 / 1024).toFixed(2)}MB`);
      return reply.status(400).send({
        success: false,
        message: 'File size exceeds 5MB limit',
      });
    }

    // 文件类型限制（仅支持Word文档）
    const allowedTypes = [
      'application/msword', // .doc
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
    ];

    console.log(`🔍 检查文件类型: ${fileType}`);
    if (!allowedTypes.includes(fileType)) {
      console.error(`❌ 不支持的文件类型: ${fileType}`);
      return reply.status(400).send({
        success: false,
        message: 'File type not supported. Only Word documents (.doc, .docx) are allowed',
      });
    }

    // 获取模型类型（默认deepseek-v3）
    const modelType = (data.fields.modelType?.value || 'deepseek-v3') as ModelType;

    // 验证模型类型
    const validModels: ModelType[] = ['deepseek-v3', 'qwen3-72b', 'qwen-long'];
    if (!validModels.includes(modelType)) {
      return reply.status(400).send({
        success: false,
        message: `Invalid model type. Allowed: ${validModels.join(', ')}`,
      });
    }

    console.log(`🤖 使用模型: ${modelType}`);

    // 调用服务层进行审查
    console.log('⚙️ 调用审查服务...');
    const task = await reviewService.reviewManuscript(file, filename, MOCK_USER_ID, modelType);

    console.log(`✅ 审查任务已创建: ${task.id}`);

    return reply.send({
      success: true,
      message: 'Manuscript uploaded successfully. Review task created.',
      data: {
        taskId: task.id,
        fileName: task.fileName,
        status: task.status,
        createdAt: task.createdAt,
      },
    });
  } catch (error) {
    console.error('❌ 上传稿件失败:', error);
    return reply.status(500).send({
      success: false,
      message: error instanceof Error ? error.message : 'Upload failed',
    });
  }
}

/**
 * 获取任务状态
 * GET /api/review/tasks/:taskId
 */
export async function getTaskStatus(
  request: FastifyRequest<{
    Params: {
      taskId: string;
    };
  }>,
  reply: FastifyReply
) {
  try {
    const { taskId } = request.params;
    console.log(`🔍 查询任务状态: ${taskId}`);

    const task = await reviewService.getReviewTask(MOCK_USER_ID, taskId);

    console.log(`✅ 任务状态: ${task.status}`);

    return reply.send({
      success: true,
      data: {
        id: task.id,
        fileName: task.fileName,
        fileSize: task.fileSize,
        status: task.status,
        wordCount: task.wordCount,
        overallScore: task.overallScore,
        modelUsed: task.modelUsed,
        createdAt: task.createdAt,
        startedAt: task.startedAt,
        completedAt: task.completedAt,
        durationSeconds: task.durationSeconds,
        errorMessage: task.errorMessage,
      },
    });
  } catch (error) {
    console.error('❌ 查询任务状态失败:', error);
    return reply.status(404).send({
      success: false,
      message: error instanceof Error ? error.message : 'Task not found',
    });
  }
}

/**
 * 获取审查报告
 * GET /api/review/tasks/:taskId/report
 */
export async function getTaskReport(
  request: FastifyRequest<{
    Params: {
      taskId: string;
    };
  }>,
  reply: FastifyReply
) {
  try {
    const { taskId } = request.params;
    console.log(`📊 获取审查报告: ${taskId}`);

    const report = await reviewService.getReviewReport(MOCK_USER_ID, taskId);

    console.log(`✅ 报告已生成`);

    return reply.send({
      success: true,
      data: report,
    });
  } catch (error) {
    console.error('❌ 获取报告失败:', error);

    // 如果报告尚未完成，返回202状态
    if (error instanceof Error && error.message.includes('not ready yet')) {
      return reply.status(202).send({
        success: false,
        message: error.message,
      });
    }

    return reply.status(404).send({
      success: false,
      message: error instanceof Error ? error.message : 'Report not found',
    });
  }
}

/**
 * 获取任务列表
 * GET /api/review/tasks
 */
export async function getTaskList(
  request: FastifyRequest<{
    Querystring: {
      page?: string;
      limit?: string;
    };
  }>,
  reply: FastifyReply
) {
  try {
    const page = parseInt(request.query.page || '1', 10);
    const limit = parseInt(request.query.limit || '20', 10);

    console.log(`📋 获取任务列表: page=${page}, limit=${limit}`);

    const result = await reviewService.getReviewTasks(MOCK_USER_ID, page, limit);

    console.log(`✅ 找到 ${result.tasks.length} 个任务`);

    return reply.send({
      success: true,
      data: result.tasks,
      pagination: result.pagination,
    });
  } catch (error) {
    console.error('❌ 获取任务列表失败:', error);
    return reply.status(500).send({
      success: false,
      message: error instanceof Error ? error.message : 'Failed to get task list',
    });
  }
}

/**
 * 删除任务
 * DELETE /api/review/tasks/:taskId
 */
export async function deleteTask(
  request: FastifyRequest<{
    Params: {
      taskId: string;
    };
  }>,
  reply: FastifyReply
) {
  try {
    const { taskId } = request.params;
    console.log(`🗑️ 删除任务: ${taskId}`);

    await reviewService.deleteReviewTask(MOCK_USER_ID, taskId);

    console.log(`✅ 任务已删除`);

    return reply.send({
      success: true,
      message: 'Task deleted successfully',
    });
  } catch (error) {
    console.error('❌ 删除任务失败:', error);
    return reply.status(404).send({
      success: false,
      message: error instanceof Error ? error.message : 'Failed to delete task',
    });
  }
}





























