import { test } from "node:test";
import assert from "node:assert/strict";
import { MessageHistory, conflictMarkerLines, parseIdentityShow, placeholder, signingLabel } from "../out/commitbox.mjs";

const SIGNED = `# identity Andy McCall <a@example.org>
  key      f1add784
  created  2026-09-26 18:12:11Z (2 days ago)
  secret   * available
  signing  every change (core.sign = change)
`;

test("signing state from oxy identity show", () => {
  const s = parseIdentityShow(SIGNED);
  assert.deepEqual(s, { who: "Andy McCall <a@example.org>", secret: true, mode: "change" });
  assert.equal(signingLabel(s), "✔ signed as Andy McCall");
  const sealed = parseIdentityShow(SIGNED.replace("every change (core.sign = change)", "at push via seals (core.sign = seal)"));
  assert.equal(signingLabel(sealed), "◈ sealed at push as Andy McCall");
  const keyless = parseIdentityShow(SIGNED.replace("* available", "x not found in the key directory"));
  assert.match(signingLabel(keyless), /unsigned: the key for Andy McCall is missing/);
  assert.equal(parseIdentityShow("No identity configured; run `oxy identity create`."), null);
  assert.match(signingLabel(null), /unsigned: no identity/);
  assert.equal(signingLabel(undefined), "", "not known yet");
});

test("placeholder follows the mode", () => {
  assert.equal(placeholder({ amend: false, resolution: false, signing: "✔ signed as A" }), "Message (Ctrl+Enter to commit) · ✔ signed as A");
  assert.match(placeholder({ amend: true, resolution: false, signing: "" }), /^Amend the last change.*Ctrl\+Enter to amend\)$/);
  assert.match(placeholder({ amend: false, resolution: true, signing: "" }), /^Describe the resolution/);
});

test("message history is newest first, unique and bounded", () => {
  const h = new MessageHistory(["b", "", "a"]);
  h.add("  c  ");
  h.add("a");
  h.add("");
  assert.deepEqual(h.entries, ["a", "c", "b"]);
  for (let i = 0; i < 40; i++) {
    h.add(`m${i}`);
  }
  assert.equal(h.entries.length, MessageHistory.LIMIT);
  assert.equal(h.entries[0], "m39");
});

test("conflict markers: Oxygen's and Git's, not look-alikes", () => {
  const oxy = ['a', '<<<<<<< oxy conflict 1 of 1, side 1 of 2: change k7m2p9 "x"', "one", '======= oxy conflict 1 of 1, side 2 of 2: change q3x8w1 "y"', "two", ">>>>>>> oxy conflict 1 of 1 end", ""].join("\n");
  assert.deepEqual(conflictMarkerLines(oxy), [2, 6]);
  assert.deepEqual(conflictMarkerLines("x\n<<<<<<< HEAD\ny\n=======\nz\n>>>>>>> feature\r\n"), [2, 6]);
  assert.deepEqual(conflictMarkerLines("<<<<<<<< eight\n  <<<<<<< indented\na <<<<<<< b\n"), []);
});
