package com.correx.infrastructure.tools.filesystem

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption

/**
 * Crash-safe write primitive shared by the write tool and the undo reverser:
 * stage into a temp file in the target's OWN directory (same filesystem, so the
 * rename is atomic) then atomically swap. A partial write is never observable at
 * [target]; on failure the temp is cleaned and the original is left untouched.
 * Falls back to a non-atomic replace only if the platform rejects ATOMIC_MOVE.
 */
internal object AtomicFileWriter {
    fun write(target: Path, content: ByteArray) {
        target.parent?.let { Files.createDirectories(it) }
        val dir = target.parent ?: Paths.get(".")
        val tmp = Files.createTempFile(dir, ".${target.fileName}", ".tmp")
        runCatching {
            Files.write(tmp, content)
            runCatching { Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE) }
                .getOrElse { Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING) }
        }.onFailure {
            Files.deleteIfExists(tmp)
            throw it
        }
    }
}
