/**
 * Tool for Morgan agent to create custom AI agent packages
 */

import { tool } from 'ai'
import { z } from 'zod'
import { v4 as uuidv4 } from 'uuid'
import type { AgentPackagePayload } from '@/lib/types'

const createAgentPackageSchema = z.object({
  displayName: z
    .string()
    .describe('Clear, memorable name for the agent (e.g., "Code Reviewer", "API Designer")'),
  summary: z
    .string()
    .describe(
      'Concise 1-2 sentence description of what the agent does and when to use it'
    ),
  systemPrompt: z
    .string()
    .describe(
      'Comprehensive system prompt that defines the agent\'s expertise, behavior, and response patterns. Should be detailed and actionable.'
    ),
  tags: z
    .array(z.string())
    .describe(
      'Relevant tags categorizing the agent (e.g., ["code-review", "documentation", "analysis"])'
    ),
  recommendedIcon: z
    .string()
    .optional()
    .describe('Emoji or icon identifier for visual representation'),
  whenToUse: z
    .string()
    .optional()
    .describe(
      'Guidance on when users should select this agent vs other agents'
    ),
})

type CreateAgentPackageInput = z.infer<typeof createAgentPackageSchema>

/**
 * Morgan's create_agent_package tool
 * Enables Morgan to create custom agents with specified configurations
 *
 * NOTE: Using `as any` to work around Vercel AI SDK tool() typing limitations.
 * The tool works correctly at runtime; the typing issue is in the SDK's overload resolution.
 */
export const createAgentPackageTool = tool({
  description:
    'Create a new custom AI agent with a specialized system prompt and capabilities',
  parameters: createAgentPackageSchema,
  execute: async (input: CreateAgentPackageInput) => {
    const { displayName, summary, systemPrompt, tags, recommendedIcon, whenToUse } = input
    // Generate unique agent ID
    const agentId = `custom-${uuidv4()}`

    // Create agent package payload
    const payload: AgentPackagePayload = {
      agentId,
      displayName,
      summary,
      systemPrompt,
      tags: tags || [],
      hints: {
        recommendedIcon,
        whenToUse,
      },
    }

    return {
      success: true,
      message: `Created agent package "${displayName}" with ID: ${agentId}`,
      payload,
    }
  },
} as any)
