/**
 * DevKit Tools API
 * 
 * CRUD operations for tool management
 */

import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

interface CreateToolBody {
  name: string;
  kind: string;
  config?: any;
  enabled?: boolean;
}

interface UpdateToolBody {
  name?: string;
  kind?: string;
  config?: any;
  enabled?: boolean;
}

/**
 * Register tool management routes
 */
export function registerToolRoutes(fastify: FastifyInstance) {
  /**
   * GET /devkit/api/tools
   * List all tools
   */
  fastify.get('/devkit/api/tools', async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const tools = await prisma.devKitTool.findMany({
        include: {
          agents: {
            include: {
              agent: true
            }
          }
        },
        orderBy: {
          createdAt: 'desc'
        }
      });

      // Transform to include agents count
      const toolsWithCount = tools.map(tool => ({
        ...tool,
        agentsCount: tool.agents.length,
        agents: tool.agents.map(at => at.agent)
      }));

      return {
        tools: toolsWithCount,
        total: tools.length
      };
    } catch (error: any) {
      return reply.status(500).send({
        error: 'failed_to_list_tools',
        message: error.message
      });
    }
  });

  /**
   * POST /devkit/api/tools
   * Create a new tool
   */
  fastify.post('/devkit/api/tools', async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const body = request.body as CreateToolBody;

      // Validate required fields
      if (!body.name || !body.kind) {
        return reply.status(400).send({
          error: 'validation_error',
          message: 'Missing required fields: name, kind'
        });
      }

      // Create tool
      const tool = await prisma.devKitTool.create({
        data: {
          name: body.name,
          kind: body.kind,
          config: body.config || {},
          enabled: body.enabled !== undefined ? body.enabled : true
        },
        include: {
          agents: {
            include: {
              agent: true
            }
          }
        }
      });

      return {
        tool: {
          ...tool,
          agentsCount: tool.agents.length,
          agents: tool.agents.map(at => at.agent)
        }
      };
    } catch (error: any) {
      return reply.status(500).send({
        error: 'failed_to_create_tool',
        message: error.message
      });
    }
  });

  /**
   * GET /devkit/api/tools/:id
   * Get tool details
   */
  fastify.get('/devkit/api/tools/:id', async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const { id } = request.params as { id: string };

      const tool = await prisma.devKitTool.findUnique({
        where: { id },
        include: {
          agents: {
            include: {
              agent: true
            }
          }
        }
      });

      if (!tool) {
        return reply.status(404).send({
          error: 'tool_not_found',
          message: `Tool with id '${id}' not found`
        });
      }

      return {
        tool: {
          ...tool,
          agentsCount: tool.agents.length,
          agents: tool.agents.map(at => ({
            ...at.agent,
            configOverride: at.configOverride
          }))
        }
      };
    } catch (error: any) {
      return reply.status(500).send({
        error: 'failed_to_get_tool',
        message: error.message
      });
    }
  });

  /**
   * PUT /devkit/api/tools/:id
   * Update tool
   */
  fastify.put('/devkit/api/tools/:id', async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const { id } = request.params as { id: string };
      const body = request.body as UpdateToolBody;

      // Check if tool exists
      const existing = await prisma.devKitTool.findUnique({
        where: { id }
      });

      if (!existing) {
        return reply.status(404).send({
          error: 'tool_not_found',
          message: `Tool with id '${id}' not found`
        });
      }

      // Update tool
      const tool = await prisma.devKitTool.update({
        where: { id },
        data: {
          ...(body.name && { name: body.name }),
          ...(body.kind && { kind: body.kind }),
          ...(body.config && { config: body.config }),
          ...(body.enabled !== undefined && { enabled: body.enabled })
        },
        include: {
          agents: {
            include: {
              agent: true
            }
          }
        }
      });

      return {
        tool: {
          ...tool,
          agentsCount: tool.agents.length,
          agents: tool.agents.map(at => at.agent)
        }
      };
    } catch (error: any) {
      return reply.status(500).send({
        error: 'failed_to_update_tool',
        message: error.message
      });
    }
  });

  /**
   * DELETE /devkit/api/tools/:id
   * Delete tool
   */
  fastify.delete('/devkit/api/tools/:id', async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const { id } = request.params as { id: string };

      // Check if tool exists
      const existing = await prisma.devKitTool.findUnique({
        where: { id }
      });

      if (!existing) {
        return reply.status(404).send({
          error: 'tool_not_found',
          message: `Tool with id '${id}' not found`
        });
      }

      // Delete tool (cascade will delete agent_tools)
      await prisma.devKitTool.delete({
        where: { id }
      });

      return {
        success: true,
        message: 'Tool deleted successfully'
      };
    } catch (error: any) {
      return reply.status(500).send({
        error: 'failed_to_delete_tool',
        message: error.message
      });
    }
  });
}

