import { FastifyRequest, FastifyReply } from 'fastify';
import { agentService } from '../services/agentService.js';

interface AgentParams {
  id: string;
}

interface RenderPromptBody {
  projectBackground?: string;
  userInput: string;
  knowledgeBaseContext?: string;
}

class AgentController {
  // 获取所有智能体列表
  async getAllAgents(request: FastifyRequest, reply: FastifyReply) {
    try {
      const agents = agentService.getAllAgents();

      return reply.code(200).send({
        success: true,
        data: agents,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '获取智能体列表失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 获取启用的智能体列表
  async getEnabledAgents(request: FastifyRequest, reply: FastifyReply) {
    try {
      const agents = agentService.getEnabledAgents();

      return reply.code(200).send({
        success: true,
        data: agents,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '获取智能体列表失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 获取单个智能体详情
  async getAgentById(
    request: FastifyRequest<{ Params: AgentParams }>,
    reply: FastifyReply
  ) {
    try {
      const { id } = request.params;
      const agent = agentService.getAgentById(id);

      if (!agent) {
        return reply.code(404).send({
          success: false,
          message: '智能体不存在',
        });
      }

      return reply.code(200).send({
        success: true,
        data: agent,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '获取智能体详情失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 获取智能体的系统Prompt
  async getSystemPrompt(
    request: FastifyRequest<{ Params: AgentParams }>,
    reply: FastifyReply
  ) {
    try {
      const { id } = request.params;

      if (!agentService.agentExists(id)) {
        return reply.code(404).send({
          success: false,
          message: '智能体不存在',
        });
      }

      const systemPrompt = agentService.getSystemPrompt(id);

      return reply.code(200).send({
        success: true,
        data: {
          agentId: id,
          systemPrompt,
        },
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '获取系统Prompt失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 渲染用户Prompt（用于预览或调试）
  async renderPrompt(
    request: FastifyRequest<{ Params: AgentParams }>,
    reply: FastifyReply
  ) {
    try {
      const { id } = request.params;
      const body = request.body as RenderPromptBody;

      if (!agentService.agentExists(id)) {
        return reply.code(404).send({
          success: false,
          message: '智能体不存在',
        });
      }

      if (!body.userInput) {
        return reply.code(400).send({
          success: false,
          message: 'userInput为必填项',
        });
      }

      const renderedPrompt = agentService.renderUserPrompt(id, {
        projectBackground: body.projectBackground,
        userInput: body.userInput,
        knowledgeBaseContext: body.knowledgeBaseContext,
      });

      return reply.code(200).send({
        success: true,
        data: {
          agentId: id,
          renderedPrompt,
        },
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '渲染Prompt失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 根据分类获取智能体
  async getAgentsByCategory(
    request: FastifyRequest<{ Querystring: { category: string } }>,
    reply: FastifyReply
  ) {
    try {
      const { category } = request.query;

      if (!category) {
        return reply.code(400).send({
          success: false,
          message: 'category参数为必填项',
        });
      }

      const agents = agentService.getAgentsByCategory(category);

      return reply.code(200).send({
        success: true,
        data: agents,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '获取智能体列表失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 重新加载配置（管理员功能）
  async reloadConfig(request: FastifyRequest, reply: FastifyReply) {
    try {
      agentService.reloadConfig();

      return reply.code(200).send({
        success: true,
        message: '智能体配置已重新加载',
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '重新加载配置失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }
}

export const agentController = new AgentController();




