import { parseUnifiedDiff, type DiffHunk } from "@/boxes/diff-apply"

interface ParsedFile {
  filename: string
  additions: number
  deletions: number
}

export function getRevertDiffFiles(diffText: string): ParsedFile[] {
  if (!diffText) return []

  try {
    // Parse file headers from the diff text to extract filenames
    const files: ParsedFile[] = []
    const fileBlocks = diffText.split(/(?=diff --git )/)

    for (const block of fileBlocks) {
      if (!block.startsWith("diff --git")) continue

      const headerMatch = block.match(/^diff --git (?:a\/(.+?) b\/(.+?)|(.+?) (.+?))\n/)
      if (!headerMatch) continue

      const candidates = [headerMatch[1], headerMatch[2], headerMatch[3], headerMatch[4]]
      const filename = candidates.find((c) => c && c !== "/dev/null") ?? "unknown"
      const hunks = parseUnifiedDiff(block)

      const additions = hunks.reduce(
        (sum, h) => sum + h.lines.filter((l) => l.startsWith("+")).length, 0,
      )
      const deletions = hunks.reduce(
        (sum, h) => sum + h.lines.filter((l) => l.startsWith("-")).length, 0,
      )

      files.push({ filename: filename.replace(/^[ab]\//, ""), additions, deletions })
    }

    return files
  } catch {
    return []
  }
}
