package com.correx.infrastructure.inference.llama.cpp

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

/**
 * Manages the lifecycle of a llama.cpp server process.
 */
class LlamaProcess(
    private val command: List<String>,
    private val logFile: File
) {
    private var process: Process? = null

    val isAlive: Boolean
        get() = process?.isAlive ?: false

    /** The OS pid of the running process, or null when not started / not alive. */
    val pid: Long?
        get() = process?.takeIf { it.isAlive }?.pid()

    suspend fun start() = withContext(Dispatchers.IO) {
        if (isAlive) return@withContext

        logFile.parentFile?.mkdirs()
        
        process = ProcessBuilder(command)
            .redirectOutput(logFile)
            .redirectErrorStream(true)
            .start()
    }

    suspend fun stop() = withContext(Dispatchers.IO) {
        process?.destroyForcibly()
        try {
            process?.waitFor()
        } catch (_: Exception) {
            // Process already dead or timeout
        }
        process = null
    }
}
