import { z } from 'zod';
import { defineTool, type ToolResult } from './types.js';

/**
 * Sub-agent types
 */
export const SubAgentTypeSchema = z.enum(['explore', 'plan', 'bash']);
export type SubAgentType = z.infer<typeof SubAgentTypeSchema>;

/**
 * Model tier to actual model mapping
 */
export const ModelTierSchema = z.enum(['fast', 'standard', 'powerful']);
export type ModelTier = z.infer<typeof ModelTierSchema>;

const MODEL_TIERS: Record<ModelTier, string> = {
  fast: 'claude-3-5-haiku-20241022',
  standard: 'claude-sonnet-4-20250514',
  powerful: 'claude-opus-4-20250514',
};

interface TaskResult {
  response: string;
  filesExplored?: string[];
  findings?: string[];
  toolCalls?: number;
}

interface BackgroundTaskResult {
  taskId: string;
  status: 'running';
}

/**
 * Task tool for spawning specialized sub-agents
 */
export const taskTool = defineTool({
  name: 'task',
  description: `Spawn a specialized sub-agent for focused tasks.

Sub-agent types:
- explore: Fast read-only codebase exploration. Use for understanding code structure, finding patterns, answering questions about the codebase.
- plan: Design implementation plans. Can read code and write plan documents to .emdash/ directory.
- bash: Shell command execution specialist. Use for running builds, tests, git operations.

Model tiers:
- fast: Quick responses, lower cost (Haiku)
- standard: Balanced performance (Sonnet)
- powerful: Complex reasoning (Opus)`,
  category: 'task',
  schema: z.object({
    type: SubAgentTypeSchema.describe('Type of sub-agent to spawn'),
    prompt: z.string().describe('Detailed task description for the sub-agent'),
    model: ModelTierSchema.optional().describe('Model tier to use (default: standard)'),
    background: z.boolean().optional().describe('Run in background and return immediately'),
  }),

  async execute(
    input,
    context
  ): Promise<ToolResult<TaskResult | BackgroundTaskResult>> {
    const modelName = MODEL_TIERS[input.model ?? 'standard'];

    context.logger.info(
      { type: input.type, model: modelName, background: input.background },
      'Spawning sub-agent'
    );

    // Dynamic import to avoid circular dependency
    const { SubAgentRunner } = await import('../subagent.js');

    const runner = new SubAgentRunner({
      type: input.type,
      repoRoot: context.repoRoot,
      model: input.model ?? 'standard',
      logger: context.logger,
    });

    if (input.background) {
      const taskId = await runner.startBackground(input.prompt);
      return {
        success: true,
        data: { taskId, status: 'running' as const },
        suggestions: ['Use task_status tool to check progress'],
      };
    }

    const result = await runner.run(input.prompt);

    if (!result.success) {
      return {
        success: false,
        error: result.error ?? 'Sub-agent execution failed',
      };
    }

    return {
      success: true,
      data: {
        response: result.response,
        filesExplored: result.filesExplored,
        findings: result.findings,
        toolCalls: result.toolCalls,
      },
    };
  },
});
