/**
 * 默认移民咨询策略
 *
 * 这是系统的核心咨询流程，定义了Agent如何主动引导用户完成移民咨询。
 * 老板可以通过后台修改或创建新策略来覆盖此默认行为。
 */

// ============================================================================
// 类型定义
// ============================================================================

/**
 * 咨询阶段ID
 */
export enum StageId {
  GREETING = 'greeting',           // 开场破冰
  NEEDS_DISCOVERY = 'needs_discovery', // 需求了解
  INFO_COLLECTION = 'info_collection', // 背景收集
  ASSESSMENT = 'assessment',       // 资格评估
  RECOMMENDATION = 'recommendation', // 方案推荐
  OBJECTION_HANDLING = 'objection_handling', // 异议处理
  CONVERSION = 'conversion',       // 转化促成
  HANDOFF = 'handoff',             // 完成对接
}

/**
 * 指令类型
 */
export enum DirectiveType {
  MUST_DO = 'MUST_DO',       // 必须做
  SHOULD_DO = 'SHOULD_DO',   // 建议做
  MUST_NOT = 'MUST_NOT',     // 禁止做
  PREFER = 'PREFER',         // 优先考虑
}

/**
 * 转化路径类型
 */
export enum ConversionPath {
  PAID_ASSESSMENT = 'paid_assessment',   // 付费评估
  HUMAN_EXPERT = 'human_expert',         // 对接人类专家
  CONTINUE_FREE = 'continue_free',       // 继续免费咨询
}

/**
 * 行为指令
 */
export interface Directive {
  type: DirectiveType;
  content: string;
  priority: number;
}

/**
 * 需要收集的用户信息
 */
export interface RequiredInfo {
  key: string;
  label: string;
  description: string;
  askingStrategy: string;       // 建议的提问方式
  validation?: string;          // 验证规则
  isRequired: boolean;
  priority: number;             // 收集优先级，数字越小越优先
}

/**
 * 阶段转移条件
 */
export interface TransitionCondition {
  type: 'INFO_COLLECTED' | 'USER_INTENT' | 'TURNS_EXCEEDED' | 'KEYWORD' | 'ASSESSMENT_DONE' | 'CUSTOM';
  // INFO_COLLECTED: 指定信息已收集
  infoKeys?: string[];
  minCount?: number;            // 至少收集几项
  // USER_INTENT: 用户表达了某种意图
  intents?: string[];
  // TURNS_EXCEEDED: 超过指定轮次
  maxTurns?: number;
  // KEYWORD: 包含关键词
  keywords?: string[];
  // CUSTOM: 自定义条件描述（LLM判断）
  customCondition?: string;
}

/**
 * 阶段转移
 */
export interface StageTransition {
  targetStageId: StageId;
  conditions: TransitionCondition[];
  priority: number;             // 优先级，数字越大越优先
  description: string;          // 转移说明
}

/**
 * 阶段建议使用的工具
 */
export interface StageTool {
  toolName: string;
  description: string;
  triggerCondition: string;  // 什么情况下应该调用
  priority: 'required' | 'recommended' | 'optional';
}

/**
 * 咨询阶段
 */
export interface ConsultingStage {
  id: StageId;
  name: string;
  description: string;
  order: number;

  // 阶段目标
  goal: string;

  // 成功标准
  successCriteria: string[];

  // 行为指令
  directives: Directive[];

  // 需要收集的信息
  requiredInfo: RequiredInfo[];

  // 建议使用的工具（确保信息准确）
  suggestedTools: StageTool[];

  // 阶段转移规则
  transitions: StageTransition[];

  // 最大轮次（超过后强制转移）
  maxTurns: number;

  // 建议的回复长度
  suggestedResponseLength: number;
}

/**
 * 完整咨询策略
 */
export interface ConsultingStrategy {
  id: string;
  name: string;
  description: string;
  version: string;
  isDefault: boolean;

  // 阶段定义
  stages: ConsultingStage[];

  // 全局指令（适用于所有阶段）
  globalDirectives: Directive[];

  // 专家联系方式配置
  expertContact: {
    wechat?: string;
    phone?: string;
    email?: string;
    workingHours?: string;
  };

  // 付费服务配置
  paidServices: {
    assessmentPrice: number;
    currency: string;
    description: string;
  };
}

// ============================================================================
// 默认策略定义
// ============================================================================

/**
 * 需要收集的核心用户信息
 */
export const CORE_USER_INFO: RequiredInfo[] = [
  {
    key: 'age',
    label: '年龄',
    description: '用户的年龄',
    askingStrategy: '方便问一下您今年多大了吗？',
    validation: '18-65之间的数字',
    isRequired: true,
    priority: 1,
  },
  {
    key: 'education',
    label: '最高学历',
    description: '用户的最高学历',
    askingStrategy: '您的最高学历是什么呢？（如本科、硕士、博士等）',
    isRequired: true,
    priority: 2,
  },
  {
    key: 'university',
    label: '毕业院校',
    description: '用户毕业的学校',
    askingStrategy: '请问您是哪所学校毕业的？',
    isRequired: false,
    priority: 3,
  },
  {
    key: 'major',
    label: '专业',
    description: '用户的专业',
    askingStrategy: '您学的是什么专业？',
    isRequired: false,
    priority: 4,
  },
  {
    key: 'workYears',
    label: '工作年限',
    description: '用户的工作年限',
    askingStrategy: '您工作几年了？',
    isRequired: true,
    priority: 5,
  },
  {
    key: 'industry',
    label: '所在行业',
    description: '用户所在的行业',
    askingStrategy: '您目前在什么行业工作？',
    isRequired: true,
    priority: 6,
  },
  {
    key: 'jobTitle',
    label: '职位',
    description: '用户的职位',
    askingStrategy: '您目前的职位是什么？',
    isRequired: false,
    priority: 7,
  },
  {
    key: 'annualIncome',
    label: '年收入',
    description: '用户的年收入（人民币）',
    askingStrategy: '方便透露一下您的年收入大概在什么范围吗？（大概范围就行，比如30-50万、50-100万等）',
    isRequired: true,
    priority: 8,
  },
  {
    key: 'immigrationPurpose',
    label: '移民目的',
    description: '用户想移民的主要原因',
    askingStrategy: '您考虑移民香港主要是出于什么考虑呢？（比如子女教育、事业发展、税务规划等）',
    isRequired: true,
    priority: 9,
  },
  {
    key: 'timeline',
    label: '时间规划',
    description: '用户的移民时间规划',
    askingStrategy: '您计划什么时候开始办理？有没有比较紧迫的时间要求？',
    isRequired: false,
    priority: 10,
  },
  {
    key: 'hasHKConnection',
    label: '香港联系',
    description: '用户是否有香港的工作机会或雇主',
    askingStrategy: '您目前有没有香港的工作机会或者认识的香港雇主？',
    isRequired: false,
    priority: 11,
  },
];

/**
 * 默认咨询策略
 */
export const DEFAULT_CONSULTING_STRATEGY: ConsultingStrategy = {
  id: 'default-hk-immigration',
  name: '香港移民咨询默认策略',
  description: '标准的香港移民咨询流程，适用于大多数咨询场景',
  version: '1.0.0',
  isDefault: true,

  // ========================================
  // 全局指令
  // ========================================
  globalDirectives: [
    {
      type: DirectiveType.MUST_DO,
      content: '每次回复结尾都要有一个推进对话的问题或明确的下一步引导',
      priority: 100,
    },
    {
      type: DirectiveType.MUST_DO,
      content: '保持专业但亲切的语气，像一个经验丰富的朋友在给建议',
      priority: 95,
    },
    {
      type: DirectiveType.MUST_NOT,
      content: '绝对不能说"保证成功"、"100%通过"、"包过"之类的承诺',
      priority: 100,
    },
    {
      type: DirectiveType.MUST_NOT,
      content: '不要一次问超过2个问题，会让用户感到压力',
      priority: 90,
    },
    {
      type: DirectiveType.MUST_NOT,
      content: '不要回避价格、费用、难度等敏感问题，要诚实回答',
      priority: 90,
    },
    {
      type: DirectiveType.SHOULD_DO,
      content: '适时总结和确认已了解的信息，让用户感到被认真对待',
      priority: 70,
    },
    {
      type: DirectiveType.SHOULD_DO,
      content: '如果用户问了与移民无关的问题，礼貌引导回移民话题',
      priority: 60,
    },
    {
      type: DirectiveType.PREFER,
      content: '回复要简洁有力，避免长篇大论，重点突出',
      priority: 50,
    },
  ],

  // ========================================
  // 专家联系方式
  // ========================================
  expertContact: {
    wechat: 'HK_Immigration_Expert',
    phone: '+852-1234-5678',
    email: 'expert@iconsulting.com',
    workingHours: '周一至周五 9:00-18:00（香港时间）',
  },

  // ========================================
  // 付费服务配置
  // ========================================
  paidServices: {
    assessmentPrice: 99,
    currency: 'CNY',
    description: '专业移民顾问1对1评估，包含详细的方案分析和申请建议',
  },

  // ========================================
  // 阶段定义
  // ========================================
  stages: [
    // ----------------------------------------
    // 阶段1: 开场破冰
    // ----------------------------------------
    {
      id: StageId.GREETING,
      name: '开场破冰',
      description: '热情欢迎用户，建立初步信任，根据用户历史做个性化问候',
      order: 1,
      goal: '让用户感到被欢迎和被重视，愿意继续对话',
      successCriteria: [
        '用户回复了至少一条消息',
        '用户没有表现出不耐烦或想离开',
        '如果是老用户，提及之前的咨询让用户感到被记住',
      ],
      suggestedResponseLength: 150,
      maxTurns: 3,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '【首要】在对话开始时立即调用get_user_context工具，获取用户历史信息',
          priority: 100,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '如果是老用户：提及上次咨询的内容，如"您好！上次您咨询的是高才通，后来考虑得怎么样了？"',
          priority: 98,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '如果是新用户：热情但不过度，用"您好"开头，简单介绍自己是香港移民咨询顾问',
          priority: 95,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '可以问一下用户是怎么了解到我们的（但不强求回答）',
          priority: 50,
        },
        {
          type: DirectiveType.MUST_NOT,
          content: '不要在开场就问太多个人信息，会让人有压力',
          priority: 90,
        },
      ],

      requiredInfo: [],

      suggestedTools: [
        {
          toolName: 'get_user_context',
          description: '获取用户历史信息和记忆，判断是否为老用户，提取历史咨询记录',
          triggerCondition: '【必须】对话开始的第一轮就要调用，获取用户所有历史资料',
          priority: 'required',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.NEEDS_DISCOVERY,
          conditions: [
            { type: 'USER_INTENT', intents: ['ask_about_immigration', 'want_to_immigrate', 'curious_about_hk'] },
          ],
          priority: 10,
          description: '用户表达了对移民的兴趣',
        },
        {
          targetStageId: StageId.INFO_COLLECTION,
          conditions: [
            { type: 'CUSTOM', customCondition: '老用户已有足够背景信息（年龄、学历、工作年限、收入）' },
          ],
          priority: 15,
          description: '老用户信息充足，跳过需求了解直接进入信息确认',
        },
        {
          targetStageId: StageId.NEEDS_DISCOVERY,
          conditions: [
            { type: 'TURNS_EXCEEDED', maxTurns: 2 },
          ],
          priority: 5,
          description: '开场超过2轮，主动进入需求了解',
        },
      ],
    },

    // ----------------------------------------
    // 阶段2: 需求了解
    // ----------------------------------------
    {
      id: StageId.NEEDS_DISCOVERY,
      name: '需求了解',
      description: '了解用户为什么想移民香港，有什么期望和顾虑',
      order: 2,
      goal: '理解用户的移民动机和核心需求',
      successCriteria: [
        '了解用户想移民的主要原因',
        '了解用户对香港移民的基本认知水平',
      ],
      suggestedResponseLength: 200,
      maxTurns: 5,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '询问用户考虑移民香港的主要原因（子女教育/事业发展/税务规划/生活品质等）',
          priority: 100,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '了解用户对香港移民政策了解多少，针对性地介绍',
          priority: 80,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '如果用户提到具体的移民类型（如高才通），先调用search_knowledge获取准确信息再回应',
          priority: 70,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '回答政策问题时，必须先调用search_knowledge从知识库获取准确信息，不要凭记忆回答',
          priority: 95,
        },
      ],

      requiredInfo: [
        CORE_USER_INFO.find(i => i.key === 'immigrationPurpose')!,
      ],

      suggestedTools: [
        {
          toolName: 'search_knowledge',
          description: '搜索知识库获取移民政策的准确信息',
          triggerCondition: '当用户询问具体政策、要求、流程时，必须调用以确保信息准确',
          priority: 'required',
        },
        {
          toolName: 'web_search',
          description: '搜索官方网站获取最新政策变化',
          triggerCondition: '当用户问到"最新"、"现在"、"2024年"等时效性问题时调用',
          priority: 'recommended',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.INFO_COLLECTION,
          conditions: [
            { type: 'INFO_COLLECTED', infoKeys: ['immigrationPurpose'] },
          ],
          priority: 10,
          description: '已了解用户移民目的，进入信息收集',
        },
        {
          targetStageId: StageId.INFO_COLLECTION,
          conditions: [
            { type: 'USER_INTENT', intents: ['want_assessment', 'check_eligibility'] },
          ],
          priority: 15,
          description: '用户主动想做评估',
        },
        {
          targetStageId: StageId.INFO_COLLECTION,
          conditions: [
            { type: 'TURNS_EXCEEDED', maxTurns: 4 },
          ],
          priority: 5,
          description: '需求了解超过4轮，进入信息收集',
        },
      ],
    },

    // ----------------------------------------
    // 阶段3: 背景信息收集
    // ----------------------------------------
    {
      id: StageId.INFO_COLLECTION,
      name: '背景信息收集',
      description: '收集用户的年龄、学历、工作、收入等评估所需信息',
      order: 3,
      goal: '收集足够的信息来判断用户适合哪种移民方案',
      successCriteria: [
        '收集到年龄、学历、工作年限、年收入这4项核心信息',
        '用户没有因为问题太多而流失',
      ],
      suggestedResponseLength: 180,
      maxTurns: 10,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '每次只问1-2个问题，不要让用户感到被审问',
          priority: 100,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '解释为什么要问这些信息："为了帮您找到最合适的方案，我需要了解一下..."',
          priority: 95,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '收集到一些信息后，可以给出初步的积极反馈："您的条件看起来不错"',
          priority: 70,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '如果用户不愿意透露某些信息，不要强求，跳过继续',
          priority: 80,
        },
        {
          type: DirectiveType.PREFER,
          content: '优先收集：年龄 → 学历/院校 → 工作年限 → 年收入',
          priority: 60,
        },
      ],

      requiredInfo: CORE_USER_INFO.filter(i =>
        ['age', 'education', 'workYears', 'annualIncome'].includes(i.key)
      ),

      suggestedTools: [
        {
          toolName: 'save_user_memory',
          description: '保存用户提供的背景信息到长期记忆',
          triggerCondition: '每当用户透露了个人信息（年龄、学历、收入等）时，立即保存',
          priority: 'required',
        },
        {
          toolName: 'check_off_topic',
          description: '检查用户问题是否与移民无关',
          triggerCondition: '当用户问题明显偏离移民话题时调用',
          priority: 'recommended',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.ASSESSMENT,
          conditions: [
            {
              type: 'INFO_COLLECTED',
              infoKeys: ['age', 'education', 'workYears', 'annualIncome'],
              minCount: 4,
            },
          ],
          priority: 10,
          description: '核心信息收集完成，进入评估',
        },
        {
          targetStageId: StageId.ASSESSMENT,
          conditions: [
            {
              type: 'INFO_COLLECTED',
              infoKeys: ['age', 'education', 'workYears', 'annualIncome'],
              minCount: 3,
            },
            { type: 'TURNS_EXCEEDED', maxTurns: 8 },
          ],
          priority: 8,
          description: '收集了大部分信息且轮次较多，进入评估',
        },
        {
          targetStageId: StageId.ASSESSMENT,
          conditions: [
            { type: 'USER_INTENT', intents: ['want_result_now', 'impatient'] },
          ],
          priority: 15,
          description: '用户急于知道结果',
        },
      ],
    },

    // ----------------------------------------
    // 阶段4: 资格评估
    // ----------------------------------------
    {
      id: StageId.ASSESSMENT,
      name: '资格评估',
      description: '根据收集的信息，评估用户适合哪些移民方案',
      order: 4,
      goal: '给出初步的评估结论，判断用户适合的移民类型',
      successCriteria: [
        '明确告诉用户他最适合的1-2个方案',
        '简要说明为什么适合',
      ],
      suggestedResponseLength: 300,
      maxTurns: 3,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '基于已收集的信息，明确推荐最适合的移民方案（高才通/优才/专才等）',
          priority: 100,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '【重要】给出评估结论前，必须调用search_knowledge获取各方案的最新要求，确保推荐准确',
          priority: 98,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '解释为什么推荐这个方案，与用户的条件对应起来',
          priority: 95,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '如果用户条件很好，要表达积极信号；如果条件一般，要诚实但给出希望',
          priority: 80,
        },
        {
          type: DirectiveType.MUST_NOT,
          content: '不要给出成功率的具体数字承诺',
          priority: 100,
        },
      ],

      requiredInfo: [],

      suggestedTools: [
        {
          toolName: 'search_knowledge',
          description: '搜索各移民方案的具体要求和标准',
          triggerCondition: '【必须】在给出评估结论前，搜索推荐方案的官方要求',
          priority: 'required',
        },
        {
          toolName: 'web_search',
          description: '搜索最新政策，确保评估基于最新信息',
          triggerCondition: '当知识库信息可能过时时，搜索入境处官网获取最新政策',
          priority: 'recommended',
        },
        {
          toolName: 'collect_assessment_info',
          description: '汇总收集的用户信息用于评估',
          triggerCondition: '开始评估前，整理所有已收集的用户信息',
          priority: 'recommended',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.RECOMMENDATION,
          conditions: [
            { type: 'TURNS_EXCEEDED', maxTurns: 2 },
          ],
          priority: 10,
          description: '评估完成，进入详细方案推荐',
        },
        {
          targetStageId: StageId.RECOMMENDATION,
          conditions: [
            { type: 'USER_INTENT', intents: ['want_details', 'interested', 'tell_me_more'] },
          ],
          priority: 15,
          description: '用户想了解更多细节',
        },
        {
          targetStageId: StageId.OBJECTION_HANDLING,
          conditions: [
            { type: 'USER_INTENT', intents: ['has_doubt', 'not_sure', 'worried'] },
          ],
          priority: 12,
          description: '用户有顾虑，进入异议处理',
        },
      ],
    },

    // ----------------------------------------
    // 阶段5: 方案推荐
    // ----------------------------------------
    {
      id: StageId.RECOMMENDATION,
      name: '方案推荐',
      description: '详细介绍推荐的移民方案，包括流程、材料、时间、费用等',
      order: 5,
      goal: '让用户充分了解推荐方案的具体内容',
      successCriteria: [
        '用户了解了申请流程的大致步骤',
        '用户了解了大概的时间和费用',
      ],
      suggestedResponseLength: 400,
      maxTurns: 6,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '【重要】介绍流程前，必须调用search_knowledge获取该方案的详细流程、材料清单、费用等信息',
          priority: 100,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '介绍推荐方案的基本流程（准备材料→递交申请→审批→获批）',
          priority: 98,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '说明大致的时间周期和费用范围',
          priority: 90,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '强调该方案对用户的优势（审批快/成功率高/要求匹配等）',
          priority: 80,
        },
        {
          type: DirectiveType.MUST_NOT,
          content: '不要一次把所有信息都倒出来，根据用户问题逐步展开',
          priority: 85,
        },
      ],

      requiredInfo: [],

      suggestedTools: [
        {
          toolName: 'search_knowledge',
          description: '搜索方案的详细流程、材料清单、费用信息',
          triggerCondition: '【必须】介绍任何具体信息前，先从知识库获取准确数据',
          priority: 'required',
        },
        {
          toolName: 'web_search',
          description: '搜索入境处官网获取最新政策和流程',
          triggerCondition: '当用户询问最新政策、审批时间、费用变化时调用',
          priority: 'recommended',
        },
        {
          toolName: 'fetch_immigration_news',
          description: '获取移民相关新闻',
          triggerCondition: '当用户问到政策变化或新闻时调用',
          priority: 'optional',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.CONVERSION,
          conditions: [
            { type: 'USER_INTENT', intents: ['want_to_proceed', 'how_to_start', 'next_step'] },
          ],
          priority: 15,
          description: '用户想进一步行动',
        },
        {
          targetStageId: StageId.OBJECTION_HANDLING,
          conditions: [
            { type: 'USER_INTENT', intents: ['has_concern', 'too_expensive', 'too_difficult', 'not_confident'] },
          ],
          priority: 12,
          description: '用户有顾虑',
        },
        {
          targetStageId: StageId.CONVERSION,
          conditions: [
            { type: 'TURNS_EXCEEDED', maxTurns: 5 },
          ],
          priority: 8,
          description: '介绍充分，引导转化',
        },
      ],
    },

    // ----------------------------------------
    // 阶段6: 异议处理
    // ----------------------------------------
    {
      id: StageId.OBJECTION_HANDLING,
      name: '异议处理',
      description: '解答用户的疑虑、担忧和反对意见',
      order: 6,
      goal: '消除用户的顾虑，建立信心',
      successCriteria: [
        '用户的主要顾虑得到了回应',
        '用户态度有所缓和或积极',
      ],
      suggestedResponseLength: 250,
      maxTurns: 5,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '认真倾听用户的顾虑，先表示理解再回应',
          priority: 100,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '用事实和逻辑回应，不要空洞安慰',
          priority: 95,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '可以举一些类似情况的成功案例（不承诺具体结果）',
          priority: 70,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '如果用户的顾虑确实有道理，诚实承认并提供替代方案',
          priority: 80,
        },
        {
          type: DirectiveType.MUST_NOT,
          content: '不要贬低用户的担忧，说"这没什么"之类的话',
          priority: 90,
        },
      ],

      requiredInfo: [],

      suggestedTools: [
        {
          toolName: 'search_knowledge',
          description: '搜索相关的案例和常见问题解答',
          triggerCondition: '当用户提出具体顾虑时，搜索相关的解答和案例',
          priority: 'recommended',
        },
        {
          toolName: 'get_exchange_rate',
          description: '获取实时汇率',
          triggerCondition: '当用户担心费用问题时，可以计算人民币/港币的实际金额',
          priority: 'optional',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.CONVERSION,
          conditions: [
            { type: 'USER_INTENT', intents: ['satisfied', 'convinced', 'want_to_proceed'] },
          ],
          priority: 15,
          description: '顾虑消除，进入转化',
        },
        {
          targetStageId: StageId.RECOMMENDATION,
          conditions: [
            { type: 'USER_INTENT', intents: ['want_other_options', 'try_another'] },
          ],
          priority: 12,
          description: '用户想了解其他方案',
        },
        {
          targetStageId: StageId.CONVERSION,
          conditions: [
            { type: 'TURNS_EXCEEDED', maxTurns: 4 },
          ],
          priority: 8,
          description: '异议处理充分，尝试转化',
        },
        {
          targetStageId: StageId.HANDOFF,
          conditions: [
            { type: 'USER_INTENT', intents: ['give_up', 'not_interested', 'maybe_later'] },
          ],
          priority: 10,
          description: '用户暂时不想继续，友好收尾',
        },
      ],
    },

    // ----------------------------------------
    // 阶段7: 转化促成
    // ----------------------------------------
    {
      id: StageId.CONVERSION,
      name: '转化促成',
      description: '引导用户选择下一步：付费评估、对接专家或其他',
      order: 7,
      goal: '促成用户采取行动（付费评估或对接专家）',
      successCriteria: [
        '用户明确表示要付费评估，或要专家联系方式',
        '或用户明确表示暂时不需要，但保持了良好关系',
      ],
      suggestedResponseLength: 250,
      maxTurns: 5,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '给用户明确的下一步选择：1)付费专业评估 2)对接资深顾问 3)继续免费咨询',
          priority: 100,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '说明付费评估的价值：专业团队一对一分析，比AI更深入准确',
          priority: 95,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '强调时间价值：移民政策经常变化，早行动早受益',
          priority: 70,
        },
        {
          type: DirectiveType.MUST_NOT,
          content: '不要过度推销让用户反感，一次最多引导两次',
          priority: 90,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '如果用户犹豫，可以提供限时优惠或免费咨询名额',
          priority: 60,
        },
      ],

      requiredInfo: [],

      suggestedTools: [
        {
          toolName: 'generate_payment',
          description: '生成付费评估的支付二维码',
          triggerCondition: '当用户明确表示要付费评估时，立即调用生成支付码',
          priority: 'required',
        },
        {
          toolName: 'save_user_memory',
          description: '保存用户的转化意向和偏好',
          triggerCondition: '当用户表达明确意向时，记录下来以便后续跟进',
          priority: 'recommended',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.HANDOFF,
          conditions: [
            { type: 'USER_INTENT', intents: ['want_to_pay', 'buy_assessment'] },
          ],
          priority: 20,
          description: '用户决定付费评估',
        },
        {
          targetStageId: StageId.HANDOFF,
          conditions: [
            { type: 'USER_INTENT', intents: ['want_expert', 'talk_to_human', 'contact_info'] },
          ],
          priority: 18,
          description: '用户想对接人类专家',
        },
        {
          targetStageId: StageId.NEEDS_DISCOVERY,
          conditions: [
            { type: 'USER_INTENT', intents: ['more_questions', 'want_to_know_more'] },
          ],
          priority: 12,
          description: '用户还有更多问题',
        },
        {
          targetStageId: StageId.HANDOFF,
          conditions: [
            { type: 'TURNS_EXCEEDED', maxTurns: 4 },
          ],
          priority: 8,
          description: '转化尝试充分，进入收尾',
        },
      ],
    },

    // ----------------------------------------
    // 阶段8: 完成对接
    // ----------------------------------------
    {
      id: StageId.HANDOFF,
      name: '完成对接',
      description: '根据用户选择，完成付费、提供专家联系方式或友好收尾',
      order: 8,
      goal: '完成本次咨询的闭环',
      successCriteria: [
        '如果付费：成功生成支付链接',
        '如果对接专家：提供了联系方式',
        '如果暂不需要：友好告别并留下再次咨询的可能',
      ],
      suggestedResponseLength: 200,
      maxTurns: 5,

      directives: [
        {
          type: DirectiveType.MUST_DO,
          content: '根据用户选择执行：生成支付码/提供专家联系方式/友好告别',
          priority: 100,
        },
        {
          type: DirectiveType.MUST_DO,
          content: '感谢用户的咨询，表示随时欢迎再来',
          priority: 90,
        },
        {
          type: DirectiveType.SHOULD_DO,
          content: '如果用户暂时不需要服务，告知我们的公众号/官网，保持联系',
          priority: 70,
        },
      ],

      requiredInfo: [],

      suggestedTools: [
        {
          toolName: 'generate_payment',
          description: '生成支付二维码',
          triggerCondition: '当用户确认要付费时调用',
          priority: 'required',
        },
        {
          toolName: 'save_user_memory',
          description: '保存本次咨询的关键信息和用户决定',
          triggerCondition: '对话结束前，保存用户的决定和后续跟进信息',
          priority: 'required',
        },
      ],

      transitions: [
        {
          targetStageId: StageId.NEEDS_DISCOVERY,
          conditions: [
            { type: 'USER_INTENT', intents: ['new_question', 'another_topic'] },
          ],
          priority: 10,
          description: '用户有新问题，重新开始',
        },
      ],
    },
  ],
};

// ============================================================================
// 辅助函数
// ============================================================================

/**
 * 获取阶段配置
 */
export function getStageById(stageId: StageId): ConsultingStage | undefined {
  return DEFAULT_CONSULTING_STRATEGY.stages.find(s => s.id === stageId);
}

/**
 * 获取下一个默认阶段
 */
export function getNextStage(currentStageId: StageId): ConsultingStage | undefined {
  const currentStage = getStageById(currentStageId);
  if (!currentStage) return undefined;

  return DEFAULT_CONSULTING_STRATEGY.stages.find(s => s.order === currentStage.order + 1);
}

/**
 * 获取阶段需要收集的信息（未收集的）
 */
export function getUncollectedInfo(
  stageId: StageId,
  collectedInfo: Record<string, unknown>
): RequiredInfo[] {
  const stage = getStageById(stageId);
  if (!stage) return [];

  return stage.requiredInfo
    .filter(info => !collectedInfo[info.key])
    .sort((a, b) => a.priority - b.priority);
}

/**
 * 判断用户意图（简单关键词匹配）
 */
export function detectUserIntents(message: string): string[] {
  const intents: string[] = [];
  const text = message.toLowerCase();

  // 想移民/咨询相关
  if (/移民|香港|想去|考虑|咨询|了解/.test(text)) {
    intents.push('ask_about_immigration', 'want_to_immigrate');
  }

  // 想评估
  if (/评估|测试|看看|够不够|资格|条件/.test(text)) {
    intents.push('want_assessment', 'check_eligibility');
  }

  // 想了解更多
  if (/详细|具体|更多|展开|说说|介绍/.test(text)) {
    intents.push('want_details', 'tell_me_more', 'interested');
  }

  // 有顾虑
  if (/担心|顾虑|不确定|难|复杂|麻烦|贵|费用高/.test(text)) {
    intents.push('has_concern', 'has_doubt', 'worried');
  }

  // 满意/想继续
  if (/好的|可以|明白|清楚|懂了|想继续|下一步|怎么办/.test(text)) {
    intents.push('satisfied', 'want_to_proceed', 'next_step');
  }

  // 想付费
  if (/付费|付款|购买|买|支付|下单/.test(text)) {
    intents.push('want_to_pay', 'buy_assessment');
  }

  // 想对接专家
  if (/专家|顾问|人工|真人|联系方式|微信|电话/.test(text)) {
    intents.push('want_expert', 'talk_to_human', 'contact_info');
  }

  // 暂时不需要
  if (/再说|以后|考虑一下|不急|暂时不|再看看/.test(text)) {
    intents.push('maybe_later', 'not_interested');
  }

  // 不耐烦
  if (/直接|快点|别啰嗦|说重点/.test(text)) {
    intents.push('impatient', 'want_result_now');
  }

  return intents;
}
