export function parseDiffLines(diff) {
  const lines = [];
  let oldLine = null;
  let newLine = null;
  let previousNewLine = 0;

  diff.split(/\r?\n/).forEach((text, index) => {
    const hunk = parseHunkHeader(text);
    if (hunk) {
      const unchanged = hunk.newStart - previousNewLine - 1;
      if (unchanged > 0) {
        lines.push({
          id: `fold-${previousNewLine}-${hunk.newStart - 1}`,
          kind: "fold",
          text: `${unchanged} unchanged lines`,
          count: unchanged
        });
      }
      oldLine = hunk.oldStart;
      newLine = hunk.newStart;
      return;
    }

    const kind = lineKind(text);
    if (kind === "header") {
      lines.push({ id: `${index}-${text}`, text, kind });
      return;
    }

    const numbered = numberedDiffLine(text, kind, oldLine, newLine);
    lines.push({ id: `${index}-${text}`, text, kind, ...numbered });
    if (kind !== "addition" && oldLine !== null) oldLine += 1;
    if (kind !== "deletion" && newLine !== null) {
      previousNewLine = newLine;
      newLine += 1;
    }
  });

  return lines;
}

function lineKind(line) {
  if (line.startsWith("+++ ") || line.startsWith("--- ") || line.startsWith("@@")) return "header";
  if (line.startsWith("+")) return "addition";
  if (line.startsWith("-")) return "deletion";
  return "context";
}

function parseHunkHeader(line) {
  const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
  return match ? { oldStart: Number(match[1]), newStart: Number(match[2]) } : null;
}

function numberedDiffLine(text, kind, oldLine, newLine) {
  if (oldLine === null || newLine === null) return {};
  if (kind === "addition") return { oldLine: null, newLine, lineNumber: newLine };
  if (kind === "deletion") return { oldLine, newLine: null, lineNumber: oldLine };
  return { oldLine, newLine, lineNumber: newLine };
}
