import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";

import { parseUserAttachments } from "../web/static/js/attachments.js";

const chatJs = readFileSync("web/static/js/chat.js", "utf8");

test("user attachment protocol lines are separated from visible message text", () => {
  const parsed = parseUserAttachments(
    "请比较这张图\n\n[用户上传的参考图] 项目/显微照片.png\n[用户上传的文件] 项目/数据表.xlsx",
  );
  assert.equal(parsed.content, "请比较这张图");
  assert.deepEqual(parsed.attachments, [
    { path: "项目/显微照片.png", kind: "image" },
    { path: "项目/数据表.xlsx", kind: "file" },
  ]);
});

test("attachment-only messages have an empty visible body", () => {
  const parsed = parseUserAttachments("[用户上传的参考图] 项目/照片 01.png");
  assert.equal(parsed.content, "");
  assert.deepEqual(parsed.attachments, [{ path: "项目/照片 01.png", kind: "image" }]);
});

test("ordinary bracketed text remains visible", () => {
  const content = "[备注] 这不是附件\n继续处理";
  assert.deepEqual(parseUserAttachments(content), { content, attachments: [] });
});

test("new sends use structured attachments and history keeps a legacy fallback", () => {
  assert.match(chatJs, /attachments:\s*pendingAttachments\.map/);
  assert.match(chatJs, /Array\.isArray\(m\.attachment_refs\)/);
  assert.match(chatJs, /structuredAttachments === null/);
  assert.doesNotMatch(chatJs, /content = content \? `\$\{content\}\\n\\n\$\{lines\}`/);
});
