import { FastifyRequest, FastifyReply } from 'fastify';
import { conversationService } from '../services/conversationService.js';
import { ModelType } from '../adapters/types.js';

export class ConversationController {
  /**
   * 创建新对话
   */
  async createConversation(
    request: FastifyRequest<{
      Body: {
        projectId: string;
        agentId: string;
        title?: string;
      };
    }>,
    reply: FastifyReply
  ) {
    try {
      // TODO: 从JWT token获取userId
      const userId = 'user-mock-001'; // 临时使用模拟用户

      const { projectId, agentId, title } = request.body;

      const conversation = await conversationService.createConversation({
        userId,
        projectId,
        agentId,
        title,
      });

      reply.code(201).send({
        success: true,
        data: conversation,
      });
    } catch (error: any) {
      reply.code(400).send({
        success: false,
        message: error.message || '创建对话失败',
      });
    }
  }

  /**
   * 获取对话列表
   */
  async getConversations(
    request: FastifyRequest<{
      Querystring: {
        projectId?: string;
      };
    }>,
    reply: FastifyReply
  ) {
    try {
      // TODO: 从JWT token获取userId
      const userId = 'user-mock-001';

      const projectId = request.query.projectId;

      const conversations = await conversationService.getConversations(
        userId,
        projectId
      );

      reply.send({
        success: true,
        data: conversations,
      });
    } catch (error: any) {
      reply.code(500).send({
        success: false,
        message: error.message || '获取对话列表失败',
      });
    }
  }

  /**
   * 获取对话详情
   */
  async getConversationById(
    request: FastifyRequest<{
      Params: {
        id: string;
      };
    }>,
    reply: FastifyReply
  ) {
    try {
      // TODO: 从JWT token获取userId
      const userId = 'user-mock-001';

      const conversationId = request.params.id;

      const conversation = await conversationService.getConversationById(
        conversationId,
        userId
      );

      reply.send({
        success: true,
        data: conversation,
      });
    } catch (error: any) {
      reply.code(404).send({
        success: false,
        message: error.message || '对话不存在',
      });
    }
  }

  /**
   * 发送消息（非流式）
   */
  async sendMessage(
    request: FastifyRequest<{
      Body: {
        conversationId: string;
        content: string;
        modelType: ModelType;
        knowledgeBaseIds?: string[];
      };
    }>,
    reply: FastifyReply
  ) {
    try {
      // TODO: 从JWT token获取userId
      const userId = 'user-mock-001';

      const { conversationId, content, modelType, knowledgeBaseIds } =
        request.body;

      // 验证modelType
      if (modelType !== 'deepseek-v3' && modelType !== 'qwen3-72b' && modelType !== 'qwen-long' && modelType !== 'gemini-pro') {
        reply.code(400).send({
          success: false,
          message: `不支持的模型类型: ${modelType}`,
        });
        return;
      }

      const result = await conversationService.sendMessage(
        {
          conversationId,
          content,
          modelType,
          knowledgeBaseIds,
        },
        userId
      );

      reply.send({
        success: true,
        data: result,
      });
    } catch (error: any) {
      reply.code(400).send({
        success: false,
        message: error.message || '发送消息失败',
      });
    }
  }

  /**
   * 发送消息（流式输出，SSE）
   */
  async sendMessageStream(
    request: FastifyRequest<{
      Body: {
        conversationId: string;
        content: string;
        modelType: ModelType;
        knowledgeBaseIds?: string[];
      };
    }>,
    reply: FastifyReply
  ) {
    try {
      // TODO: 从JWT token获取userId
      const userId = 'user-mock-001';

      const { conversationId, content, modelType, knowledgeBaseIds } =
        request.body;

      // 验证modelType
      if (modelType !== 'deepseek-v3' && modelType !== 'qwen3-72b' && modelType !== 'qwen-long' && modelType !== 'gemini-pro') {
        reply.code(400).send({
          success: false,
          message: `不支持的模型类型: ${modelType}`,
        });
        return;
      }

      // 设置SSE响应头
      reply.raw.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        'Access-Control-Allow-Origin': '*',
      });

      // 流式输出
      for await (const chunk of conversationService.sendMessageStream(
        {
          conversationId,
          content,
          modelType,
          knowledgeBaseIds,
        },
        userId
      )) {
        // 发送SSE数据
        reply.raw.write(`data: ${JSON.stringify(chunk)}\n\n`);
      }

      // 发送结束标记
      reply.raw.write('data: [DONE]\n\n');
      reply.raw.end();
    } catch (error: any) {
      console.error('Stream error:', error);
      reply.raw.write(
        `data: ${JSON.stringify({
          error: error.message || '发送消息失败',
        })}\n\n`
      );
      reply.raw.end();
    }
  }

  /**
   * 删除对话
   */
  async deleteConversation(
    request: FastifyRequest<{
      Params: {
        id: string;
      };
    }>,
    reply: FastifyReply
  ) {
    try {
      // TODO: 从JWT token获取userId
      const userId = 'user-mock-001';

      const conversationId = request.params.id;

      await conversationService.deleteConversation(conversationId, userId);

      reply.send({
        success: true,
        message: '对话已删除',
      });
    } catch (error: any) {
      reply.code(400).send({
        success: false,
        message: error.message || '删除对话失败',
      });
    }
  }
}

export const conversationController = new ConversationController();

