/**
 * Coordinator Tools
 * 协调器可用的工具定义 — 包括 Agent 调用工具和直接工具
 */

import { ToolDefinition } from '../types/agent.types';

// ============================================================
// Agent Invocation Tools (调用专家 Agent 的工具)
// ============================================================

export const AGENT_INVOCATION_TOOLS: ToolDefinition[] = [
  {
    name: 'invoke_policy_expert',
    description:
      '调用政策专家 Agent 查询和解读香港移民政策。当用户询问具体政策、申请条件、流程步骤时使用。' +
      '务必通过此工具查证政策信息，不要凭记忆回答政策问题。',
    input_schema: {
      type: 'object',
      properties: {
        query: {
          type: 'string',
          description: '政策查询内容，例如："TTPS B类的申请条件和流程"',
        },
        category: {
          type: 'string',
          enum: ['QMAS', 'GEP', 'IANG', 'TTPS', 'CIES', 'TECHTAS'],
          description: '移民类别代码（可选，缩小查询范围）',
        },
        includeProcessSteps: {
          type: 'boolean',
          description: '是否需要包含详细申请流程步骤',
        },
        includeRequirements: {
          type: 'boolean',
          description: '是否需要列出所有申请条件',
        },
      },
      required: ['query'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'invoke_assessment_expert',
    description:
      '调用评估专家 Agent 对用户进行移民资格评估。' +
      '需要至少收集到年龄、国籍、学历、工作经验等基本信息后才可调用。' +
      '评估结果会包含每个类别的评分和推荐理由。',
    input_schema: {
      type: 'object',
      properties: {
        userInfo: {
          type: 'object',
          description:
            '用户信息键值对，如 {"age": "35", "nationality": "中国大陆", "education": "硕士/计算机", "workExperience": "10年/软件工程"}',
        },
        targetCategories: {
          type: 'array',
          items: { type: 'string' },
          description: '重点评估的类别列表（可选，不传则评估所有6个类别）',
        },
        conversationContext: {
          type: 'string',
          description: '最近几轮对话的简要摘要，帮助评估专家理解背景',
        },
      },
      required: ['userInfo'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'invoke_strategist',
    description:
      '调用策略顾问 Agent 分析对话状态并提供策略建议。' +
      '仅供协调器内部参考，用户不可见。' +
      '建议每 3-5 轮调用一次，或在关键决策点调用。',
    input_schema: {
      type: 'object',
      properties: {
        conversationSummary: {
          type: 'string',
          description: '当前对话摘要',
        },
        currentTurnCount: {
          type: 'number',
          description: '当前对话轮次数',
        },
        collectedInfo: {
          type: 'object',
          description: '已收集的用户信息',
        },
        userSentiment: {
          type: 'string',
          description: '用户当前情绪（如：积极、犹豫、焦虑、中性）',
        },
        hasAssessment: {
          type: 'boolean',
          description: '是否已完成资格评估',
        },
        hasConverted: {
          type: 'boolean',
          description: '是否已转化（付费/预约）',
        },
      },
      required: ['conversationSummary', 'currentTurnCount', 'collectedInfo'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'invoke_objection_handler',
    description:
      '调用异议处理专家 Agent 处理用户的疑虑和反对意见。' +
      '当用户表达犹豫、担忧、价格异议或与竞品比较时使用。',
    input_schema: {
      type: 'object',
      properties: {
        objection: {
          type: 'string',
          description: '用户的疑虑或反对意见原文',
        },
        userContext: {
          type: 'string',
          description: '用户背景信息摘要（已知的）',
        },
        previousObjections: {
          type: 'array',
          items: { type: 'string' },
          description: '之前已处理过的疑虑列表',
        },
      },
      required: ['objection', 'userContext'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'invoke_case_analyst',
    description:
      '调用案例分析师 Agent 查找和分析类似的成功案例。' +
      '用于建立用户信心，展示公司实力。',
    input_schema: {
      type: 'object',
      properties: {
        userProfile: {
          type: 'object',
          description: '用户基本信息',
        },
        targetCategory: {
          type: 'string',
          description: '目标移民类别',
        },
        focusArea: {
          type: 'string',
          description: '关注重点（如：审批速度、特殊情况处理等）',
        },
      },
      required: ['userProfile', 'targetCategory'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'invoke_memory_manager',
    description:
      '调用记忆管理 Agent 管理用户信息。' +
      '在对话开始时加载用户上下文(load_context)，' +
      '在收集到新信息时保存(save_info)，' +
      '定期从对话中提取信息(extract_from_conversation)。',
    input_schema: {
      type: 'object',
      properties: {
        action: {
          type: 'string',
          enum: ['load_context', 'save_info', 'extract_from_conversation', 'summarize_profile'],
          description: '操作类型',
        },
        userId: {
          type: 'string',
          description: '用户 ID',
        },
        dataToSave: {
          type: 'object',
          description: '要保存的信息键值对（save_info 时使用）',
        },
        recentMessages: {
          type: 'string',
          description: '最近的对话内容（extract_from_conversation 时使用）',
        },
        contextQuery: {
          type: 'string',
          description: '上下文检索查询（load_context 时使用）',
        },
      },
      required: ['action', 'userId'],
    },
    isConcurrencySafe: false, // 有写操作
  },
];

// ============================================================
// Direct Tools (协调器直接调用的工具，不经过专家 Agent)
// ============================================================

export const DIRECT_TOOLS: ToolDefinition[] = [
  {
    name: 'search_knowledge',
    description:
      '直接搜索知识库获取移民相关信息。' +
      '用于快速查询事实信息，不需要完整的政策专家分析时使用。',
    input_schema: {
      type: 'object',
      properties: {
        query: { type: 'string', description: '搜索查询' },
        category: {
          type: 'string',
          enum: ['QMAS', 'GEP', 'IANG', 'TTPS', 'CIES', 'TECHTAS'],
        },
      },
      required: ['query'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'get_user_context',
    description: '快速检索用户的历史记忆信息',
    input_schema: {
      type: 'object',
      properties: {
        query: { type: 'string', description: '检索查询' },
      },
      required: ['query'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'check_off_topic',
    description: '检查用户消息是否偏离移民咨询主题',
    input_schema: {
      type: 'object',
      properties: {
        query: { type: 'string', description: '用户消息内容' },
      },
      required: ['query'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'get_current_datetime',
    description: '获取当前日期和时间（用于时效性政策信息判断）',
    input_schema: {
      type: 'object',
      properties: {},
    },
    isConcurrencySafe: true,
  },
  {
    name: 'web_search',
    description: '搜索互联网获取最新移民资讯、新闻或政策更新',
    input_schema: {
      type: 'object',
      properties: {
        query: { type: 'string', description: '搜索查询' },
      },
      required: ['query'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'get_exchange_rate',
    description: '获取当前汇率（讨论投资移民金额时使用）',
    input_schema: {
      type: 'object',
      properties: {
        from: { type: 'string', description: '源货币代码，如 CNY' },
        to: { type: 'string', description: '目标货币代码，如 HKD' },
      },
      required: ['from', 'to'],
    },
    isConcurrencySafe: true,
  },
  {
    name: 'fetch_immigration_news',
    description: '获取最新的香港移民新闻和政策动态',
    input_schema: {
      type: 'object',
      properties: {
        category: {
          type: 'string',
          description: '新闻类别（可选）',
        },
        limit: {
          type: 'number',
          description: '返回条数，默认 5',
        },
      },
    },
    isConcurrencySafe: true,
  },
  {
    name: 'save_user_memory',
    description:
      '直接保存用户信息到长期记忆。' +
      '用于保存关键信息，无需启动完整的记忆管理 Agent。' +
      'userId 不需要传，系统自动获取。',
    input_schema: {
      type: 'object',
      properties: {
        memoryType: {
          type: 'string',
          enum: ['FACT', 'PREFERENCE', 'INTENT'],
          description: '记忆类型：FACT-用户事实，PREFERENCE-偏好，INTENT-意图',
        },
        content: { type: 'string', description: '要记住的内容' },
        category: {
          type: 'string',
          enum: ['QMAS', 'GEP', 'IANG', 'TTPS', 'CIES', 'TECHTAS'],
          description: '相关移民类别（可选）',
        },
      },
      required: ['memoryType', 'content'],
    },
    isConcurrencySafe: false,
  },
  {
    name: 'collect_assessment_info',
    description:
      '结构化收集评估所需信息。' +
      '当对话中获得了用户的评估相关信息时，用此工具保存。',
    input_schema: {
      type: 'object',
      properties: {
        userId: { type: 'string', description: '用户 ID' },
        field: {
          type: 'string',
          enum: [
            'age', 'nationality', 'education_level', 'education_field',
            'work_experience_years', 'work_experience_field', 'current_salary',
            'language_ability', 'family_status', 'has_hk_connection',
            'investment_capability', 'target_timeline',
          ],
          description: '信息字段名',
        },
        value: { type: 'string', description: '字段值' },
      },
      required: ['userId', 'field', 'value'],
    },
    isConcurrencySafe: false,
  },
  {
    name: 'generate_payment',
    description:
      '生成支付二维码。仅在用户明确表示要付费或预约服务时使用。' +
      '需要确认用户选择的服务类别和支付方式后调用。',
    input_schema: {
      type: 'object',
      properties: {
        serviceType: {
          type: 'string',
          enum: ['ASSESSMENT', 'CONSULTATION', 'DOCUMENT_REVIEW'],
          description: '服务类型',
        },
        category: {
          type: 'string',
          enum: ['QMAS', 'GEP', 'IANG', 'TTPS', 'CIES', 'TECHTAS'],
          description: '移民类别',
        },
        paymentMethod: {
          type: 'string',
          enum: ['ALIPAY', 'WECHAT', 'CREDIT_CARD'],
          description: '支付方式（支付宝、微信、信用卡）',
        },
      },
      required: ['serviceType', 'category', 'paymentMethod'],
    },
    isConcurrencySafe: false,
  },
  {
    name: 'check_payment_status',
    description:
      '查询订单支付状态。当用户询问是否支付成功、订单进度时使用。',
    input_schema: {
      type: 'object',
      properties: {
        orderId: { type: 'string', description: '订单 ID' },
      },
      required: ['orderId'],
    },
    isConcurrencySafe: true, // 只读
  },
  {
    name: 'query_order_history',
    description:
      '查询用户的历史订单列表。当用户想查看购买记录时使用。',
    input_schema: {
      type: 'object',
      properties: {},
    },
    isConcurrencySafe: true, // 只读
  },
  {
    name: 'cancel_order',
    description:
      '取消未支付的订单。仅限未支付状态可取消。用户明确要求取消时使用。',
    input_schema: {
      type: 'object',
      properties: {
        orderId: { type: 'string', description: '要取消的订单 ID' },
      },
      required: ['orderId'],
    },
    isConcurrencySafe: false, // 写操作
  },
];

// ============================================================
// All Coordinator Tools Combined
// ============================================================

/** 协调器全部可用工具 */
export const ALL_COORDINATOR_TOOLS: ToolDefinition[] = [
  ...AGENT_INVOCATION_TOOLS,
  ...DIRECT_TOOLS,
];

/**
 * Get Claude API-compatible tool definitions
 * (strips custom fields like isConcurrencySafe)
 */
export function getToolsForClaudeAPI(
  additionalTools?: Array<{
    name: string;
    description: string;
    input_schema: Record<string, unknown>;
  }>,
): Array<{
  name: string;
  description: string;
  input_schema: Record<string, unknown>;
}> {
  const internal = ALL_COORDINATOR_TOOLS.map(t => ({
    name: t.name,
    description: t.description,
    input_schema: t.input_schema,
  }));
  if (additionalTools && additionalTools.length > 0) {
    return [...internal, ...additionalTools];
  }
  return internal;
}

/** Agent 调用工具名称集合 */
export const AGENT_TOOL_NAMES = new Set(
  AGENT_INVOCATION_TOOLS.map(t => t.name),
);

/** 判断是否是 Agent 调用工具 */
export function isAgentInvocationTool(toolName: string): boolean {
  return AGENT_TOOL_NAMES.has(toolName);
}
