import type { DiffPatch } from '../protocol/messages.js';

export function computeDiff(oldLines: string[], newLines: string[]): DiffPatch[] {
  const patches: DiffPatch[] = [];
  const maxLen = Math.max(oldLines.length, newLines.length);

  let i = 0;
  while (i < maxLen) {
    // Skip identical lines
    if (i < oldLines.length && i < newLines.length && oldLines[i] === newLines[i]) {
      i++;
      continue;
    }

    // Found a difference — collect consecutive changed lines
    const start = i;

    // Advance through differing lines
    while (
      i < maxLen &&
      !(i < oldLines.length && i < newLines.length && oldLines[i] === newLines[i])
    ) {
      i++;
    }

    patches.push({
      startLine: start,
      deleteCount: Math.min(i, oldLines.length) - start,
      insertLines: newLines.slice(start, Math.min(i, newLines.length)),
    });
  }

  return patches;
}

export function applyDiff(lines: string[], patches: DiffPatch[]): string[] {
  const result = [...lines];
  let offset = 0;

  for (const patch of patches) {
    const adjustedStart = patch.startLine + offset;
    result.splice(adjustedStart, patch.deleteCount, ...patch.insertLines);
    offset += patch.insertLines.length - patch.deleteCount;
  }

  return result;
}
