/**
 * card-builder.js — 飞书卡片消息构建
 *
 * 所有卡片均通过 JSON 直接构建（interactive 类型），无需飞书卡片模板 ID。
 */

import { PRODUCT_FEISHU_CARD_TITLE } from '../../../shared/brand.js';

const MODE_LABELS = {
  default:           '默认模式',
  acceptEdits:       '接受编辑',
  plan:              '计划模式',
  bypassPermissions: 'YOLO 模式',
};

const MODEL_OPTIONS = [
  { key: 'sonnet', label: 'Sonnet', desc: '均衡性能，适合大多数任务' },
  { key: 'opus',   label: 'Opus',   desc: '最强能力，复杂任务首选' },
  { key: 'haiku',  label: 'Haiku',  desc: '极速轻量，简单任务专用' },
];
const MODEL_LABELS = Object.fromEntries(MODEL_OPTIONS.map(m => [m.key, m.label]));

/**
 * 隐藏用户项目目录前缀，只保留相对项目路径。
 * 例：/data/user-projects/597ef057-.../test → test
 */
function stripProjectPrefix(fullPath) {
  if (!fullPath) return fullPath;
  return fullPath.replace(/^.*\/user-projects\/[0-9a-f-]{36}\//, '') || fullPath;
}

// ─── 各场景卡片构建函数 ────────────────────────────────────────────────────────

/**
 * 工具审批卡片（直接 JSON）
 */
function buildToolApprovalCardDirect(toolName, toolInput, requestId) {
  const inputSummary = truncate(
    typeof toolInput === 'object' ? JSON.stringify(toolInput, null, 2) : String(toolInput || ''),
    400
  );
  const card = {
    schema: '2.0',
    config: { update_multi: true },
    body: {
      direction: 'vertical',
      elements: [
        {
          tag: 'column_set',
          flex_mode: 'stretch',
          horizontal_spacing: '12px',
          horizontal_align: 'left',
          columns: [
            {
              tag: 'column',
              width: 'weighted',
              weight: 1,
              vertical_spacing: '8px',
              horizontal_align: 'left',
              vertical_align: 'top',
              elements: [
                { tag: 'markdown', content: `**工具名称**\n${toolName || ''}` },
                { tag: 'markdown', content: `**请求ID**\n${requestId || ''}` },
              ],
            },
            {
              tag: 'column',
              width: 'weighted',
              weight: 1,
              vertical_spacing: '8px',
              horizontal_align: 'left',
              vertical_align: 'top',
              elements: [
                { tag: 'markdown', content: '**审批状态**\n待处理' },
              ],
            },
          ],
          margin: '0px 0px 0px 0px',
        },
        {
          tag: 'markdown',
          content: `**工具输入摘要**\n\`\`\`json\n${inputSummary}\n\`\`\``,
          margin: '0px 0px 0px 0px',
        },
        {
          tag: 'form',
          name: 'approval_form',
          direction: 'vertical',
          horizontal_align: 'left',
          vertical_align: 'top',
          padding: '0px 0px 0px 0px',
          margin: '0px 0px 0px 0px',
          elements: [
            {
              tag: 'column_set',
              flex_mode: 'stretch',
              horizontal_spacing: '8px',
              horizontal_align: 'left',
              margin: '0px 0px 0px 0px',
              columns: [
                {
                  tag: 'column',
                  width: 'auto',
                  vertical_spacing: '8px',
                  horizontal_align: 'left',
                  vertical_align: 'top',
                  elements: [{
                    tag: 'button',
                    name: 'approve_btn',
                    form_action_type: 'submit',
                    type: 'primary_filled',
                    width: 'default',
                    margin: '4px 0px 4px 0px',
                    text: { tag: 'plain_text', content: '同意' },
                    behaviors: [{ type: 'callback', value: { action: 'tool_approve', decision: 'allow' } }],
                  }],
                },
                {
                  tag: 'column',
                  width: 'auto',
                  vertical_spacing: '8px',
                  horizontal_align: 'left',
                  vertical_align: 'top',
                  elements: [{
                    tag: 'button',
                    name: 'reject_btn',
                    form_action_type: 'submit',
                    type: 'danger',
                    width: 'default',
                    margin: '4px 0px 4px 0px',
                    text: { tag: 'plain_text', content: '拒绝' },
                    behaviors: [{ type: 'callback', value: { action: 'tool_approve', decision: 'deny' } }],
                  }],
                },
                {
                  tag: 'column',
                  width: 'weighted',
                  weight: 1,
                  vertical_spacing: '8px',
                  horizontal_align: 'left',
                  vertical_align: 'center',
                  elements: [{
                    tag: 'button',
                    name: 'remember_btn',
                    form_action_type: 'submit',
                    type: 'primary',
                    width: 'default',
                    margin: '4px 0px 4px 0px',
                    text: { tag: 'plain_text', content: '记住并允许' },
                    behaviors: [{ type: 'callback', value: { action: 'tool_approve', decision: 'allow_remember' } }],
                  }],
                },
              ],
            },
          ],
        },
      ],
    },
    header: {
      title: { tag: 'plain_text', content: '工具审批请求' },
      subtitle: { tag: 'plain_text', content: '' },
      text_tag_list: [{ tag: 'text_tag', text: { tag: 'plain_text', content: '待审批' }, color: 'blue' }],
      template: 'blue',
      icon: { tag: 'standard_icon', token: 'robot_outlined' },
      padding: '12px 8px 12px 8px',
    },
  };
  return JSON.stringify(card);
}

/**
 * 工具审批结果卡片（直接 JSON）
 * 审批决定后更新原卡片用
 */
function buildToolApprovalResultCardDirect(decision) {
  const label =
    decision === 'allow'   ? '✅ 已允许' :
    decision === 'deny'    ? '❌ 已拒绝' :
    decision === 'timeout' ? '⏰ 已超时' : '已处理';
  const template =
    decision === 'allow' || decision === 'allow_remember' ? 'green' :
    decision === 'deny'  ? 'red' : 'grey';
  const card = {
    schema: '2.0',
    config: { update_multi: true },
    body: {
      direction: 'vertical',
      elements: [
        { tag: 'markdown', content: `**审批结果**\n${label}` },
      ],
    },
    header: {
      title: { tag: 'plain_text', content: '工具审批请求' },
      subtitle: { tag: 'plain_text', content: '' },
      template,
      icon: { tag: 'standard_icon', token: 'robot_outlined' },
      padding: '12px 8px 12px 8px',
    },
  };
  return JSON.stringify(card);
}

/**
 * 模式选择卡片（直接 JSON）
 * 每个模式渲染为一行：左侧显示名称与说明，右侧显示切换按钮
 * 当前模式按钮高亮且禁用，其余按钮可点击触发 set_mode callback
 */
function buildModeSelectCardDirect(currentMode) {
  const current = currentMode || 'default';
  const MODES = [
    { key: 'default',           label: '默认模式',   desc: '每次操作需手动确认' },
    { key: 'acceptEdits',       label: '接受编辑',   desc: '自动接受文件编辑，其余需确认' },
    { key: 'plan',              label: '计划模式',   desc: '只规划，不执行任何操作' },
    { key: 'bypassPermissions', label: 'YOLO 模式', desc: '跳过所有确认，自动执行' },
  ];

  const rows = [];
  MODES.forEach((m, i) => {
    const isCurrent = m.key === current;
    rows.push({
      tag: 'column_set',
      flex_mode: 'stretch',
      horizontal_spacing: '12px',
      horizontal_align: 'left',
      margin: '4px 0px 4px 0px',
      columns: [
        {
          tag: 'column',
          width: 'weighted',
          weight: 1,
          vertical_spacing: '4px',
          horizontal_align: 'left',
          vertical_align: 'center',
          elements: [{
            tag: 'markdown',
            content: `${isCurrent ? '✅ ' : ''}**${m.label}**\n${m.desc}`,
          }],
        },
        {
          tag: 'column',
          width: 'auto',
          vertical_spacing: '4px',
          horizontal_align: 'right',
          vertical_align: 'center',
          elements: [{
            tag: 'button',
            type: isCurrent ? 'primary_filled' : 'default',
            width: 'default',
            margin: '0px 0px 0px 0px',
            text: { tag: 'plain_text', content: isCurrent ? '当前' : '切换' },
            disabled: isCurrent,
            behaviors: [{ type: 'callback', value: { action: 'set_mode', mode: m.key } }],
          }],
        },
      ],
    });
    if (i < MODES.length - 1) rows.push({ tag: 'hr' });
  });

  const card = {
    schema: '2.0',
    config: { update_multi: true },
    body: { direction: 'vertical', elements: rows },
    header: {
      title: { tag: 'plain_text', content: '权限模式选择' },
      subtitle: { tag: 'plain_text', content: `当前：${MODE_LABELS[current] || current}` },
      template: 'blue',
      icon: { tag: 'standard_icon', token: 'robot_outlined' },
      padding: '12px 8px 12px 8px',
    },
  };
  return JSON.stringify(card);
}

/**
 * 状态卡片（直接 JSON）
 * 显示当前项目、路径、会话 ID、权限模式、模型，底部提供「新建会话」「选择会话」「切换模型」「切换模式」快捷按钮
 */
function buildStatusCardDirect(state) {
  const { cwd, claude_session_id, permission_mode, claude_model } = state || {};
  const projectPath = cwd || '';
  const displayPath = stripProjectPrefix(projectPath);
  const projectName = displayPath ? displayPath.split('/').filter(Boolean).pop() || displayPath : '未设置';
  const sessionId = claude_session_id ? claude_session_id.slice(0, 8) : '新建';
  const mode = permission_mode || 'default';
  const modeLabel = MODE_LABELS[mode] || mode;
  const model = claude_model || 'sonnet';
  const modelLabel = MODEL_LABELS[model] || model;

  const card = {
    schema: '2.0',
    config: { update_multi: true },
    body: {
      direction: 'vertical',
      elements: [
        {
          tag: 'column_set',
          flex_mode: 'stretch',
          horizontal_spacing: '12px',
          horizontal_align: 'left',
          margin: '0px 0px 0px 0px',
          columns: [
            {
              tag: 'column',
              width: 'weighted',
              weight: 1,
              vertical_spacing: '8px',
              horizontal_align: 'left',
              vertical_align: 'top',
              elements: [
                { tag: 'markdown', content: `**项目**\n${projectName}` },
                { tag: 'markdown', content: `**路径**\n\`${displayPath || '未设置'}\`` },
              ],
            },
            {
              tag: 'column',
              width: 'weighted',
              weight: 1,
              vertical_spacing: '8px',
              horizontal_align: 'left',
              vertical_align: 'top',
              elements: [
                { tag: 'markdown', content: `**会话**\n\`${sessionId}\`` },
                { tag: 'markdown', content: `**模式**\n${modeLabel}` },
                { tag: 'markdown', content: `**模型**\n${modelLabel}` },
              ],
            },
          ],
        },
        { tag: 'hr' },
        {
          tag: 'column_set',
          flex_mode: 'stretch',
          horizontal_spacing: '8px',
          horizontal_align: 'left',
          margin: '0px 0px 0px 0px',
          columns: [
            {
              tag: 'column',
              width: 'auto',
              vertical_spacing: '4px',
              horizontal_align: 'left',
              vertical_align: 'center',
              elements: [{
                tag: 'button',
                type: 'default',
                width: 'default',
                text: { tag: 'plain_text', content: '新建会话' },
                behaviors: [{ type: 'callback', value: { action: 'new_session' } }],
              }],
            },
            {
              tag: 'column',
              width: 'auto',
              vertical_spacing: '4px',
              horizontal_align: 'left',
              vertical_align: 'center',
              elements: [{
                tag: 'button',
                type: 'default',
                width: 'default',
                text: { tag: 'plain_text', content: '选择会话' },
                behaviors: [{ type: 'callback', value: { action: 'show_sessions' } }],
              }],
            },
            {
              tag: 'column',
              width: 'auto',
              vertical_spacing: '4px',
              horizontal_align: 'left',
              vertical_align: 'center',
              elements: [{
                tag: 'button',
                type: 'default',
                width: 'default',
                text: { tag: 'plain_text', content: '切换模型' },
                behaviors: [{ type: 'callback', value: { action: 'show_model_select' } }],
              }],
            },
            {
              tag: 'column',
              width: 'auto',
              vertical_spacing: '4px',
              horizontal_align: 'left',
              vertical_align: 'center',
              elements: [{
                tag: 'button',
                type: 'default',
                width: 'default',
                text: { tag: 'plain_text', content: '切换模式' },
                behaviors: [{ type: 'callback', value: { action: 'show_modes' } }],
              }],
            },
          ],
        },
      ],
    },
    header: {
      title: { tag: 'plain_text', content: '📊 当前状态' },
      subtitle: { tag: 'plain_text', content: '' },
      template: 'green',
      padding: '12px 8px 12px 8px',
    },
  };
  return JSON.stringify(card);
}

/**
 * 模型选择卡片（直接 JSON）
 * 每个模型渲染为一行：左侧显示名称与说明，右侧显示切换按钮
 */
function buildModelSelectCardDirect(currentModel) {
  const current = currentModel || 'sonnet';

  const rows = [];
  MODEL_OPTIONS.forEach((m, i) => {
    const isCurrent = m.key === current;
    rows.push({
      tag: 'column_set',
      flex_mode: 'stretch',
      horizontal_spacing: '12px',
      horizontal_align: 'left',
      margin: '4px 0px 4px 0px',
      columns: [
        {
          tag: 'column',
          width: 'weighted',
          weight: 1,
          vertical_spacing: '4px',
          horizontal_align: 'left',
          vertical_align: 'center',
          elements: [{
            tag: 'markdown',
            content: `${isCurrent ? '✅ ' : ''}**${m.label}**\n${m.desc}`,
          }],
        },
        {
          tag: 'column',
          width: 'auto',
          vertical_spacing: '4px',
          horizontal_align: 'right',
          vertical_align: 'center',
          elements: [{
            tag: 'button',
            type: isCurrent ? 'primary_filled' : 'default',
            width: 'default',
            margin: '0px 0px 0px 0px',
            text: { tag: 'plain_text', content: isCurrent ? '当前' : '切换' },
            disabled: isCurrent,
            behaviors: [{ type: 'callback', value: { action: 'set_claude_model', model: m.key } }],
          }],
        },
      ],
    });
    if (i < MODEL_OPTIONS.length - 1) rows.push({ tag: 'hr' });
  });

  const card = {
    schema: '2.0',
    config: { update_multi: true },
    body: { direction: 'vertical', elements: rows },
    header: {
      title: { tag: 'plain_text', content: '模型选择' },
      subtitle: { tag: 'plain_text', content: `当前：${MODEL_LABELS[current] || current}` },
      template: 'purple',
      icon: { tag: 'standard_icon', token: 'robot_outlined' },
      padding: '12px 8px 12px 8px',
    },
  };
  return JSON.stringify(card);
}

/**
 * 使用下拉选择组件（select_static），用户从下拉框选取后点击「确认」提交。
 *
 * @param {string}   title       卡片标题
 * @param {Array}    items       条目数组，每项 { label, sub?, isCurrent? }
 * @param {string}   actionType  'project' | 'session'
 */
function buildListCardDirect({ title, items, actionType }) {
  const options = (items || []).map((item, i) => ({
    text: {
      tag: 'plain_text',
      content: item.isCurrent ? `✅ ${item.label}` : item.label,
    },
    value: String(i + 1),
  }));

  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: title },
      template: 'blue',
    },
    body: {
      direction: 'vertical',
      elements: [
        {
          tag: 'form',
          name: 'list_form',
          elements: [
            {
              tag: 'select_static',
              placeholder: { tag: 'plain_text', content: '请选择…' },
              options,
              name: 'list_select',
              width: 'fill',
            },
            {
              tag: 'button',
              name: 'list_submit_btn',
              text: { tag: 'plain_text', content: '确认' },
              type: 'primary',
              form_action_type: 'submit',
              behaviors: [{ type: 'callback', value: { action: 'list_select', type: actionType } }],
            },
          ],
        },
      ],
    },
  });
}

/**
 * 删除列表卡片（直接 JSON）
 * 与列表卡片布局一致，但使用红色主题和「确认删除」危险按钮。
 *
 * @param {string}   title       卡片标题
 * @param {Array}    items       条目数组，每项 { label, sub?, isCurrent? }
 * @param {string}   actionType  'project' | 'session'
 */
function buildDeleteListCardDirect({ title, items, actionType }) {
  const options = (items || []).map((item, i) => ({
    text: {
      tag: 'plain_text',
      content: item.isCurrent ? `⚠️ ${item.label}（当前）` : item.label,
    },
    value: String(i + 1),
  }));

  const deleteButtons = actionType === 'project'
    ? [
        {
          tag: 'column',
          width: 'auto',
          elements: [{
            tag: 'button',
            name: 'delete_with_folder_btn',
            text: { tag: 'plain_text', content: '含文件夹删除' },
            type: 'danger',
            form_action_type: 'submit',
            behaviors: [{ type: 'callback', value: { action: 'delete_project', delete_folder: 'true' } }],
          }],
        },
        {
          tag: 'column',
          width: 'auto',
          elements: [{
            tag: 'button',
            name: 'delete_record_btn',
            text: { tag: 'plain_text', content: '仅删除记录' },
            type: 'primary',
            form_action_type: 'submit',
            behaviors: [{ type: 'callback', value: { action: 'delete_project', delete_folder: 'false' } }],
          }],
        },
      ]
    : [
        {
          tag: 'column',
          width: 'auto',
          elements: [{
            tag: 'button',
            name: 'delete_submit_btn',
            text: { tag: 'plain_text', content: '确认删除' },
            type: 'danger',
            form_action_type: 'submit',
            behaviors: [{ type: 'callback', value: { action: `delete_${actionType}` } }],
          }],
        },
      ];

  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: title },
      template: 'red',
    },
    body: {
      direction: 'vertical',
      elements: [
        {
          tag: 'markdown',
          content: '⚠️ **删除操作不可恢复**，请谨慎选择。',
        },
        {
          tag: 'form',
          name: 'delete_form',
          elements: [
            {
              tag: 'select_static',
              placeholder: { tag: 'plain_text', content: '请选择…' },
              options,
              name: 'delete_select',
              width: 'fill',
            },
            {
              tag: 'column_set',
              flex_mode: 'left',
              horizontal_spacing: '8px',
              columns: [
                ...deleteButtons,
                {
                  tag: 'column',
                  width: 'auto',
                  elements: [{
                    tag: 'button',
                    name: 'delete_cancel_btn',
                    text: { tag: 'plain_text', content: '取消' },
                    type: 'default',
                    form_action_type: 'submit',
                    behaviors: [{ type: 'callback', value: { action: 'delete_cancel' } }],
                  }],
                },
              ],
            },
          ],
        },
      ],
    },
  });
}

/**
 * 删除结果卡片（删除成功或失败后更新原卡片用）
 *
 * @param {boolean} success
 * @param {string}  message  结果描述
 */
function buildDeleteResultCard(success, message) {
  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: success ? '✅ 删除成功' : '❌ 删除失败' },
      template: success ? 'green' : 'red',
      padding: '12px 8px 12px 8px',
    },
    body: {
      direction: 'vertical',
      elements: [
        { tag: 'markdown', content: message || '' },
      ],
    },
  });
}

/**
 * 帮助卡片（直接 JSON）
 */
function buildHelpCardDirect(boundEmail, state) {
  const { cwd, permission_mode } = state || {};
  const projectName = cwd ? (cwd.split('/').filter(Boolean).pop() || cwd) : '未设置';
  const modeLabel = MODE_LABELS[permission_mode] || '默认模式';

  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: PRODUCT_FEISHU_CARD_TITLE },
      template: 'blue',
      padding: '12px 8px 12px 8px',
    },
    body: {
      direction: 'vertical',
      elements: [
        {
          tag: 'markdown',
          content: `**已绑定账号**：${boundEmail || '未绑定'}\n**当前项目**：${projectName}\n**当前模式**：${modeLabel}`,
        },
        { tag: 'hr' },
        {
          tag: 'markdown',
          content: [
            '**命令列表**',
            '`/auth <token>` 绑定账号',
            '`/unbind` 解除绑定',
            '`/new` 新建会话',
            '`/list` 会话列表',
            '`/switch <id>` 切换会话',
            '`/project` 当前状态',
            '`/project list` 项目列表',
            '`/project create` 创建新项目',
            '`/project use <路径>` 切换项目',
            '`/project delete` 删除项目',
            '`/delete` 删除当前项目的会话',
            '`/mode` 切换权限模式',
            '`/stop` 中止当前会话',
            '`/help` 显示此帮助',
          ].join('\n'),
        },
        { tag: 'hr' },
        {
          tag: 'markdown',
          content: [
            '**权限模式**',
            ...Object.entries(MODE_LABELS).map(([k, v]) => `\`${k}\` ${v}`),
          ].join('\n'),
        },
      ],
    },
  });
}

/**
 * AskUserQuestion 交互卡片（直接 JSON，无需模板 ID）
 *
 * 每道题渲染为一个下拉选择组件（单选 select_static / 多选 multi_select_static）
 * 底部提供「提交答案」和「跳过」按钮
 *
 * @param {Array}  questions  SDK 传入的 questions 数组
 * @param {string} requestId  用于按钮 value 中的 request_id
 * @returns {string} JSON 字符串（msg_type: 'interactive' 的 content）
 */
function buildAskUserQuestionCard(questions, requestId) {
  const formElements = [];

  questions.forEach((q, qi) => {
    const multiNote = q.multiSelect ? ' 〔可多选〕' : '';
    formElements.push({
      tag: 'markdown',
      content: `**${qi + 1}. ${q.question}**${multiNote}`,
    });

    const options = (q.options || []).map(opt => ({
      text: {
        tag: 'plain_text',
        content: opt.description ? `${opt.label} — ${opt.description}` : opt.label,
      },
      value: opt.label,
    }));

    if (q.multiSelect) {
      formElements.push({
        tag: 'multi_select_static',
        placeholder: { tag: 'plain_text', content: '请选择（可多选）…' },
        options,
        name: `q_${qi}`,
      });
    } else {
      formElements.push({
        tag: 'select_static',
        placeholder: { tag: 'plain_text', content: '请选择…' },
        options,
        name: `q_${qi}`,
      });
    }

    if (qi < questions.length - 1) {
      formElements.push({ tag: 'hr' });
    }
  });

  formElements.push({
    tag: 'column_set',
    flex_mode: 'left',
    horizontal_spacing: '8px',
    columns: [
      {
        tag: 'column',
        width: 'auto',
        elements: [{
          tag: 'button',
          name: 'ask_submit_btn',
          text: { tag: 'plain_text', content: '提交答案' },
          type: 'primary',
          form_action_type: 'submit',
          behaviors: [{ type: 'callback', value: { action: 'ask_user_submit', request_id: requestId } }],
        }],
      },
      {
        tag: 'column',
        width: 'auto',
        elements: [{
          tag: 'button',
          name: 'ask_skip_btn',
          text: { tag: 'plain_text', content: '跳过' },
          type: 'default',
          form_action_type: 'submit',
          behaviors: [{ type: 'callback', value: { action: 'ask_user_skip', request_id: requestId } }],
        }],
      },
    ],
  });

  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: '🤔 Claude 需要您的回答' },
      template: 'blue',
    },
    body: {
      direction: 'vertical',
      elements: [
        {
          tag: 'form',
          name: 'ask_user_form',
          elements: formElements,
        },
      ],
    },
  });
}

/**
 * AskUserQuestion 结果卡片（提交或跳过后更新原卡片用）
 *
 * @param {Object}  answers   { [questionText]: answerLabel }
 * @param {boolean} skipped
 */
function buildAskUserQuestionResultCard(answers, skipped = false) {
  const content = skipped
    ? '已跳过本次问卷。'
    : Object.entries(answers)
        .map(([q, a]) => `• **${q}**：${a || '（未填写）'}`)
        .join('\n');

  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: skipped ? '⏭️ 已跳过' : '✅ 已提交回答' },
      template: skipped ? 'grey' : 'green',
      padding: '12px 8px 12px 8px',
    },
    body: {
      direction: 'vertical',
      elements: [
        { tag: 'markdown', content },
      ],
    },
  });
}

/**
 * 创建项目表单卡片（直接 JSON）
 * 用户填写项目名称和可选的 GitHub 地址，点击确认后触发 create_project_submit 回调
 */
function buildCreateProjectCardDirect() {
  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: '创建新项目' },
      template: 'green',
      icon: { tag: 'standard_icon', token: 'folder_outlined' },
      padding: '12px 8px 12px 8px',
    },
    body: {
      direction: 'vertical',
      elements: [
        {
          tag: 'form',
          name: 'create_project_form',
          elements: [
            { tag: 'markdown', content: '**项目名称**（必填，仅支持字母、数字、`-`、`_`）' },
            {
              tag: 'input',
              name: 'project_name',
              placeholder: { tag: 'plain_text', content: '如：my-project' },
              max_length: 100,
            },
            { tag: 'hr' },
            { tag: 'markdown', content: '**GitHub 仓库地址**（选填，自动克隆公开仓库）' },
            {
              tag: 'input',
              name: 'github_url',
              placeholder: { tag: 'plain_text', content: '如：https://github.com/user/repo.git' },
              max_length: 500,
            },
            { tag: 'hr' },
            {
              tag: 'column_set',
              flex_mode: 'left',
              horizontal_spacing: '8px',
              columns: [
                {
                  tag: 'column',
                  width: 'auto',
                  elements: [{
                    tag: 'button',
                    name: 'create_submit_btn',
                    text: { tag: 'plain_text', content: '确认创建' },
                    type: 'primary',
                    form_action_type: 'submit',
                    behaviors: [{ type: 'callback', value: { action: 'create_project_submit' } }],
                  }],
                },
                {
                  tag: 'column',
                  width: 'auto',
                  elements: [{
                    tag: 'button',
                    name: 'create_cancel_btn',
                    text: { tag: 'plain_text', content: '取消' },
                    type: 'default',
                    form_action_type: 'submit',
                    behaviors: [{ type: 'callback', value: { action: 'create_project_cancel' } }],
                  }],
                },
              ],
            },
          ],
        },
      ],
    },
  });
}

/**
 * 创建项目结果卡片（创建成功或失败后更新原卡片用）
 *
 * @param {boolean} success
 * @param {string}  message  结果描述
 */
function buildCreateProjectResultCard(success, message) {
  return JSON.stringify({
    schema: '2.0',
    config: { update_multi: true },
    header: {
      title: { tag: 'plain_text', content: success ? '✅ 项目创建成功' : '❌ 创建失败' },
      template: success ? 'green' : 'red',
      padding: '12px 8px 12px 8px',
    },
    body: {
      direction: 'vertical',
      elements: [
        { tag: 'markdown', content: message || '' },
      ],
    },
  });
}

// ─── 工具函数 ─────────────────────────────────────────────────────────────────

function truncate(str, maxLen) {
  if (!str) return '';
  return str.length <= maxLen ? str : str.slice(0, maxLen) + '…';
}

/**
 * 判断消息是否含有 Markdown 格式（决定是否使用富文本卡片）
 */
const MARKDOWN_INDICATORS = ['```', '**', '~~', '\n- ', '\n* ', '\n1. ', '\n# ', '---'];

function containsMarkdown(text) {
  return MARKDOWN_INDICATORS.some(ind => text.includes(ind));
}

/**
 * 飞书卡片 Markdown 适配：
 *   # 标题 → **标题**（飞书不支持 # 标题）
 *   > 引用 → 缩进（飞书不支持 > 引用）
 */
function adaptMarkdown(text) {
  const lines = text.split('\n');
  let inCodeBlock = false;
  return lines.map(line => {
    if (line.trimStart().startsWith('```')) { inCodeBlock = !inCodeBlock; return line; }
    if (inCodeBlock) return line;
    for (let lvl = 6; lvl >= 1; lvl--) {
      const prefix = '#'.repeat(lvl) + ' ';
      if (line.startsWith(prefix)) return `**${line.slice(prefix.length)}**`;
    }
    if (line.startsWith('> ')) return '  ' + line.slice(2);
    return line;
  }).join('\n');
}

/**
 * 构建普通文本消息或 Markdown 富文本卡片消息体
 * @returns {{ msgType: string, content: string }}
 */
function buildTextOrMarkdownMessage(text) {
  if (!containsMarkdown(text)) {
    return {
      msgType: 'text',
      content: JSON.stringify({ text }),
    };
  }
  const adapted = adaptMarkdown(text);
  return {
    msgType: 'interactive',
    content: JSON.stringify({
      schema: '2.0',
      config: { update_multi: true },
      header: {
        title: { tag: 'plain_text', content: '' },
        template: 'default',
      },
      body: {
        direction: 'vertical',
        elements: [{
          tag: 'markdown',
          content: adapted,
        }],
      },
    }),
  };
}

/**
 * 长消息分块（飞书单消息建议不超过 4000 字符）
 */
function splitMessage(text, maxLen = 4000) {
  if (text.length <= maxLen) return [text];
  const chunks = [];
  let remaining = text;
  while (remaining.length > 0) {
    let end = Math.min(maxLen, remaining.length);
    if (end < remaining.length) {
      const lastNewline = remaining.lastIndexOf('\n', end);
      if (lastNewline > maxLen * 0.5) end = lastNewline + 1;
    }
    chunks.push(remaining.slice(0, end));
    remaining = remaining.slice(end);
  }
  return chunks;
}

export {
  MODE_LABELS,
  MODEL_LABELS,
  stripProjectPrefix,
  buildToolApprovalCardDirect,
  buildToolApprovalResultCardDirect,
  buildModeSelectCardDirect,
  buildModelSelectCardDirect,
  buildStatusCardDirect,
  buildListCardDirect,
  buildDeleteListCardDirect,
  buildDeleteResultCard,
  buildHelpCardDirect,
  buildAskUserQuestionCard,
  buildAskUserQuestionResultCard,
  buildCreateProjectCardDirect,
  buildCreateProjectResultCard,
  buildTextOrMarkdownMessage,
  splitMessage,
  truncate,
};
