import type { ToolWithMetadata } from '../types.js';
import type { AgentConfig } from '../../types/index.js';
import type { ImageData } from '../../agent/types.js';
import { agentRegistry, AgentExecutor } from '../../agent/index.js';
import { toolRegistry } from '../registry.js';
import { SessionManager } from '../../session/index.js';
import { getAgentManager } from '../../agent/manager.js';
import { loadVisionConfig } from '../../utils/config.js';

/**
 * 模型预设映射
 */
const MODEL_PRESETS: Record<string, string> = {
  sonnet: 'claude-sonnet-4-20250514',
  opus: 'claude-opus-4-0-20250514',
  haiku: 'claude-3-5-haiku-20241022',
};

// Task 工具上下文（运行时注入）
let taskContext: {
  baseConfig: AgentConfig;
  sessionManager: SessionManager;
} | null = null;

/**
 * 初始化 Task 工具上下文
 */
export function initTaskContext(
  baseConfig: AgentConfig,
  sessionManager: SessionManager
): void {
  taskContext = { baseConfig, sessionManager };
}

/**
 * 获取 Task 工具上下文
 */
export function getTaskContext(): typeof taskContext {
  return taskContext;
}

/**
 * 获取 Task 工具动态描述
 */
function getTaskDescription(): string {
  const subagents = agentRegistry.listSubagents();
  if (subagents.length === 0) {
    return '执行子任务（当前没有可用的子 Agent）';
  }

  const agentList = subagents
    .map((a) => `- ${a.name}: ${a.description}`)
    .join('\n');

  return `启动子 Agent 执行复杂任务，支持后台运行和模型选择。

可用的 Agent:
${agentList}

使用示例:
- 同步执行: task({ subagent_type: "explore", prompt: "找到所有 API 路由" })
- 后台运行: task({ subagent_type: "code-reviewer", prompt: "审查代码", run_in_background: true })
- 指定模型: task({ subagent_type: "general", prompt: "复杂分析", model: "opus" })`;
}

/**
 * Task 工具
 * 用于创建子任务，委派给指定的 Agent 处理
 * 支持后台运行和模型选择
 */
export const taskTool: ToolWithMetadata = {
  name: 'task',
  description: getTaskDescription(),
  parameters: {
    description: {
      type: 'string',
      description: '任务简短描述（3-5 个词，用于标识任务）',
      required: true,
    },
    prompt: {
      type: 'string',
      description: '详细的任务说明，包括目标、范围和期望输出',
      required: true,
    },
    subagent_type: {
      type: 'string',
      description: '子 Agent 类型，可选: general, explore, code-reviewer',
      required: true,
    },
    model: {
      type: 'string',
      description: '模型选择: sonnet, opus, haiku（默认继承主 Agent 配置）',
      required: false,
    },
    run_in_background: {
      type: 'boolean',
      description: '是否后台运行。后台运行时立即返回 agentId，使用 agent_output 工具获取结果',
      required: false,
    },
    images: {
      type: 'array',
      description: '图片数据数组（用于 vision 相关任务），每个图片包含 data(base64)、mimeType、filename(可选)',
      required: false,
    },
  },
  metadata: {
    name: 'task',
    category: 'agent',
    description: '执行子任务，委派给专门的 Agent',
    keywords: ['task', 'agent', 'subagent', '子任务', '委派', '探索', '审查', '后台'],
    deferLoading: false, // 核心工具，始终加载
  },
  async execute(params) {
    const {
      description,
      prompt,
      subagent_type,
      model,
      run_in_background,
      images,
    } = params as {
      description: string;
      prompt: string;
      subagent_type: string;
      model?: string;
      run_in_background?: boolean;
      images?: ImageData[];
    };

    // 检查上下文是否已初始化
    if (!taskContext) {
      return {
        success: false,
        output: '',
        error: 'Task 工具未初始化，请确保正确设置上下文',
      };
    }

    const { baseConfig, sessionManager } = taskContext;

    // 1. 获取 Agent 配置
    const agent = agentRegistry.get(subagent_type);
    if (!agent) {
      const availableAgents = agentRegistry.listSubagents().map((a) => a.name);
      return {
        success: false,
        output: '',
        error: `未找到 Agent: ${subagent_type}。可用的 Agent: ${availableAgents.join(', ')}`,
      };
    }

    // 检查是否为 primary 模式
    if (agent.mode === 'primary') {
      return {
        success: false,
        output: '',
        error: `Agent "${subagent_type}" 是 primary 模式，不能作为子任务调用`,
      };
    }

    // 2. 处理模型选择
    let effectiveConfig = baseConfig;

    // Vision Agent 特殊处理：使用 VisionConfig 配置
    if (subagent_type === 'vision') {
      const visionConfig = loadVisionConfig();
      if (!visionConfig) {
        return {
          success: false,
          output: '',
          error: 'Vision Agent 需要配置 Vision 服务。请在配置文件中设置 visionProvider、visionApiKey 等参数。',
        };
      }
      // 使用 Vision 配置覆盖 baseConfig
      effectiveConfig = {
        ...baseConfig,
        provider: visionConfig.provider,
        apiKey: visionConfig.apiKey,
        model: visionConfig.model,
        baseUrl: visionConfig.baseUrl,
      };
    } else if (model) {
      const modelName = MODEL_PRESETS[model];
      if (!modelName) {
        return {
          success: false,
          output: '',
          error: `无效的模型选择: ${model}。可选: sonnet, opus, haiku`,
        };
      }
      effectiveConfig = {
        ...baseConfig,
        model: modelName,
      };
    }

    // 3. 后台运行模式
    if (run_in_background) {
      const agentManager = getAgentManager();
      const parentSessionId = sessionManager.getSessionId() || 'standalone';

      const agentId = await agentManager.runInBackground(
        agent,
        description,
        prompt,
        effectiveConfig,
        toolRegistry,
        {
          parentSessionId,
          workdir: process.cwd(),
          images,
        }
      );

      return {
        success: true,
        output: `Agent ${agentId} 已在后台启动 (@${agent.name})。\n使用 agent_output 工具查询结果: agent_output({ agent_id: "${agentId}" })`,
        metadata: {
          agentId,
          agent: agent.name,
          mode: 'background',
        },
      };
    }

    // 4. 同步执行模式
    const parentSessionId = sessionManager.getSessionId() || 'standalone';
    const childSession = sessionManager.createChildSession(
      parentSessionId,
      agent.name,
      `${description} (@${agent.name})`
    );

    // 创建执行器
    const executor = new AgentExecutor(agent, effectiveConfig, toolRegistry);

    // 执行任务
    const result = await executor.execute(prompt, {
      parentSessionId,
      workdir: process.cwd(),
      images,
      onStream: undefined, // 子任务不使用流式输出
    });

    // 保存子会话
    childSession.messages = [
      { role: 'user', content: prompt },
      { role: 'assistant', content: result.text },
    ];
    await sessionManager.saveChildSession(childSession);

    if (result.success) {
      return {
        success: true,
        output: result.text,
        metadata: {
          agent: agent.name,
          sessionId: childSession.id,
          steps: result.steps,
          mode: 'sync',
        },
      };
    } else {
      return {
        success: false,
        output: '',
        error: result.error || '子任务执行失败',
        metadata: {
          agent: agent.name,
          sessionId: childSession.id,
          steps: result.steps,
          mode: 'sync',
        },
      };
    }
  },
};

/**
 * 更新 Task 工具描述（Agent 注册表初始化后调用）
 */
export function updateTaskDescription(): void {
  (taskTool as { description: string }).description = getTaskDescription();
}
