/*
 * diff-view.js — shared plain-text diff-line classification, no dependency.
 *
 * There is no diff/syntax-highlighting library in this project (see
 * package.json), so a unified-diff string is colored by hand: split into
 * lines, tag each by its leading character. Used by both the self-edit
 * approval banner (Chatbot.jsx, reviewing a change BEFORE it's applied) and
 * the nexus-edit result block (Markdown.jsx, showing one AFTER) — one small
 * shared vocabulary so both read the same way.
 */

/**
 * Split unified-diff text (from difflib.unified_diff on the backend) into
 * {text, kind} lines. kind is one of "add" | "remove" | "hunk" | "file" |
 * "context". The "+++"/"---" file markers and "@@" hunk headers get their own
 * kind so they aren't colored as if they were real added/removed lines (a
 * bare "+++" line is not "code that was added").
 */
export function diffLines(text) {
  return (text || "").replace(/\n$/, "").split("\n").map((line) => {
    if (line.startsWith("+++") || line.startsWith("---")) return { text: line, kind: "file" };
    if (line.startsWith("@@")) return { text: line, kind: "hunk" };
    if (line.startsWith("+")) return { text: line, kind: "add" };
    if (line.startsWith("-")) return { text: line, kind: "remove" };
    return { text: line, kind: "context" };
  });
}

export const DIFF_LINE_COLOR = {
  add: "#8aff8a",
  remove: "#ff8a80",
  hunk: "#7a92a8",
  file: "#7a92a8",
  context: "#ccc",
};

/**
 * before/after key-value pairs (playbook fields, settings keys) rendered
 * through the same add/remove vocabulary as a real diff, so a settings or
 * playbook change reads the same way a source diff does: one line removed,
 * one line added, per changed key. Unchanged keys are omitted entirely —
 * this is "what's different," not a full dump.
 */
export function keyValueDiffLines(before, after, keys) {
  const lines = [];
  for (const key of keys) {
    const b = before ? before[key] : undefined;
    const a = after ? after[key] : undefined;
    const bStr = JSON.stringify(b);
    const aStr = JSON.stringify(a);
    if (bStr === aStr) continue;
    if (b !== undefined) lines.push({ text: `- ${key}: ${bStr}`, kind: "remove" });
    if (a !== undefined) lines.push({ text: `+ ${key}: ${aStr}`, kind: "add" });
  }
  return lines;
}
