package com.correx.infrastructure.tools.filesystem

import java.io.IOException
import java.nio.file.Files

/**
 * Produce a `diff -u` unified diff of a file mutation (labelled `a/path` → `b/path`), so the
 * change is auditable downstream — the reviewer stage and the operator can see WHAT changed, not
 * just that something did. Returns "" when there is no change. Best-effort: a diff that cannot be
 * produced is non-fatal.
 */
fun unifiedDiff(pathString: String, original: String, updated: String): String {
    if (original == updated) return ""
    val tmpDir = Files.createTempDirectory("correx-diff")
    val a = tmpDir.resolve("a")
    val b = tmpDir.resolve("b")
    return try {
        Files.write(a, original.toByteArray())
        Files.write(b, updated.toByteArray())
        val process = ProcessBuilder(
            "diff", "-u", "--label", "a/$pathString", "--label", "b/$pathString",
            a.toString(), b.toString(),
        ).redirectErrorStream(true).start()
        val out = process.inputStream.bufferedReader().use { it.readText() }
        process.waitFor()
        out.trim()
    } catch (e: IOException) {
        "(diff unavailable: ${e.message})"
    } finally {
        runCatching {
            Files.deleteIfExists(a)
            Files.deleteIfExists(b)
            Files.deleteIfExists(tmpDir)
        }
    }
}
