const PATCH_BLOCK_RE = /```mindspace-page-update\s*\n([\s\S]*?)```/i;

export function extractMindSpacePagePatch(text) {
  const match = String(text ?? '').match(PATCH_BLOCK_RE);
  if (!match) return null;
  const raw = match[1].trim();
  if (!raw) return null;
  try {
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
    const patch = {};
    if (typeof parsed.title === 'string') patch.title = parsed.title;
    if (typeof parsed.summary === 'string') patch.summary = parsed.summary;
    if (typeof parsed.content === 'string') patch.content = parsed.content;
    return Object.keys(patch).length > 0 ? patch : null;
  } catch {
    return null;
  }
}

export function mergeMindSpacePagePatch(base, patch) {
  return {
    title: patch.title ?? base.title,
    summary: patch.summary ?? base.summary,
    content: patch.content ?? base.content,
  };
}

export function normalizeMindSpacePagePatchInput(input = {}) {
  const patch = {};
  if (typeof input.title === 'string') patch.title = input.title;
  if (typeof input.summary === 'string') patch.summary = input.summary;
  if (typeof input.content === 'string') patch.content = input.content;
  return Object.keys(patch).length > 0 ? patch : null;
}

export function buildMindSpacePageSaveInstructions(page, options = {}) {
  if (!page?.id) return [];
  const h5ApiBase = String(options.h5ApiBase ?? '').replace(/\/$/, '');
  const sessionId = String(options.sessionId ?? '').trim();
  const lines = [
    '【页面实时修改（硬性）】',
    `用户要求修改当前页面（id: ${page.id}）时，必须让界面预览立刻更新。优先使用 API，其次使用补丁代码块。`,
  ];

  if (h5ApiBase && sessionId) {
    lines.push(
      '1. **优先** 每次完成一处修改后，立即用 shell 调用（可多次调用，改一点调一次）：',
      '```bash',
      `curl -sS -X POST '${h5ApiBase}/api/agent/mindspace_page_patch' \\`,
      "  -H 'Content-Type: application/json' \\",
      `  -d '{"session_id":"${sessionId}","page_id":"${page.id}","title":"修改后的标题"}'`,
      '```',
      '- 只传实际变更字段：`title` / `summary` / `content`',
      '- HTML 页面改标题或正文时，`content` 传完整 HTML',
      '- 禁止只改工作区里的其它 html 文件而不调此 API',
    );
  }

  lines.push(
    '2. **备用** 若 curl 失败，在回复末尾输出：',
    '```mindspace-page-update',
    JSON.stringify(
      {
        title: '修改后的标题（如有变更）',
        summary: '修改后的摘要（如有变更）',
        content:
          page.contentFormat === 'html'
            ? '<!-- 完整 HTML，如有变更 -->'
            : '修改后的正文（如有变更）',
      },
      null,
      2,
    ),
    '```',
    '- 只填写实际变更的字段',
    '- 禁止只口头说「已修改」而不调用 API 或输出补丁块',
    '',
  );

  return lines;
}
