package com.correx.apps.server.registry

import com.correx.core.transitions.graph.WorkflowGraph
import com.correx.infrastructure.workflow.WorkflowLoader
import org.slf4j.LoggerFactory
import java.nio.file.Path
import kotlin.io.path.exists
import kotlin.io.path.listDirectoryEntries

private val log = LoggerFactory.getLogger(FileSystemWorkflowRegistry::class.java)

class FileSystemWorkflowRegistry(
    private val loader: WorkflowLoader,
    private val workflowsDir: Path = Path.of(
        System.getProperty("user.home"), ".config", "correx", "workflows",
    ),
) : WorkflowRegistry {

    private val cache: Map<String, WorkflowGraph> by lazy { loadAll() }

    override fun listAll(): List<WorkflowSummary> =
        cache.values.map { WorkflowSummary(workflowId = it.id, description = it.id) }

    override fun find(workflowId: String): WorkflowGraph? = cache[workflowId]

    private fun loadAll(): Map<String, WorkflowGraph> {
        if (!workflowsDir.exists()) return emptyMap()
        return workflowsDir.listDirectoryEntries("*.toml")
            .mapNotNull { file ->
                runCatching { loader.load(file) }
                    .onFailure { logWarning(file, it) }
                    .getOrNull()
            }
            .associateBy { graph ->
                graph.id.ifBlank { graph.start.value }
            }.also { log.info("cache init done, cache keys: {}", it.keys) }
    }

    private fun logWarning(file: Path, ex: Throwable) {
        log.warn("Skipping {}: {}", file, ex.message)
    }
}
