package com.correx.core.toolintent

import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest

/** Abstracts filesystem observation so rules are testable and replay never re-stats. */
interface WorldProbe {
    fun exists(path: Path): Boolean

    /** Symlink-resolved real path if it exists; otherwise the normalized absolute path. */
    fun resolveReal(path: Path): Path

    /** Content hash of the file's current bytes, or null if it can't be read. Used by the
     *  stale-write gate to compare against the hash captured when the file was read. Defaulted
     *  so probes/fakes that don't observe content need not implement it. */
    fun contentHash(path: Path): String? = null
}

class FileSystemWorldProbe : WorldProbe {
    override fun exists(path: Path): Boolean = Files.exists(path)

    override fun resolveReal(path: Path): Path =
        runCatching { path.toRealPath() }.getOrElse { path.toAbsolutePath().normalize() }

    override fun contentHash(path: Path): String? = runCatching {
        MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(path))
            .joinToString("") { "%02x".format(it) }
    }.getOrNull()
}
