package com.correx.core.config

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

object ProjectProfileLoader {
    fun profilePath(workspaceRoot: String): Path =
        Paths.get(workspaceRoot, ".correx", "project.toml")

    fun load(workspaceRoot: String): ProjectProfile {
        val path = profilePath(workspaceRoot)
        if (!Files.exists(path)) return ProjectProfile()
        return runCatching { parse(Files.readString(path)) }.getOrElse { e ->
            System.err.println("Warning: Failed to parse project profile at $path: ${e.message}")
            ProjectProfile()
        }
    }

    private fun parse(content: String): ProjectProfile {
        val (rootKeys, sections) = SimpleToml.parse(content)
        val commandsSection = sections["commands"] ?: emptyMap()
        return ProjectProfile(
            about = SimpleToml.asString(rootKeys["about"], ""),
            conventions = SimpleToml.asStringList(rootKeys["conventions"]),
            commands = commandsSection.mapValues { (_, v) -> v.toString() } +
                sections.filterKeys { it.startsWith("commands.") }
                    .flatMap { (section, values) ->
                        val toolchain = section.removePrefix("commands.")
                        values.map { (alias, value) -> "$toolchain.$alias" to value.toString() }
                    }
                    .toMap(),
        )
    }
}
