package solutions.tretter.githugandroid

import java.io.File

internal object NativeGitBridge {
    private val loadResult: Result<Unit> by lazy {
        runCatching { System.loadLibrary("githugruntime") }
    }

    fun isAvailable(): Boolean = loadResult.isSuccess

    fun runGitMain(
        library: File,
        workingDir: File,
        arguments: List<String>,
        environment: Map<String, String>,
    ): ProcessExecutionResult {
        loadResult.getOrElse { error ->
            return ProcessExecutionResult(
                exitCode = -1,
                outputLines = listOf("Native Git bridge unavailable: ${error.message ?: error::class.java.simpleName}"),
            )
        }

        val argv = (listOf("git") + arguments).toTypedArray()
        val env = environment.entries.map { (key, value) -> "$key=$value" }.toTypedArray()
        val result = runGitMainNative(
            library.absolutePath,
            workingDir.absolutePath,
            argv,
            env,
        )
        val exitCode = result.getOrNull(0)?.toIntOrNull() ?: -1
        val output = result.getOrNull(1).orEmpty()
        return ProcessExecutionResult(
            exitCode = exitCode,
            outputLines = output.lineSequence().toList().dropLastWhile { it.isEmpty() },
        )
    }

    private external fun runGitMainNative(
        libraryPath: String,
        workingDirectory: String,
        argv: Array<String>,
        environment: Array<String>,
    ): Array<String>
}
