package com.correx.core.config

import java.nio.file.Files

/**
 * Serializes an [OperatorProfile] back to TOML text that [ProfileLoader] reads identically,
 * mirroring [ProjectProfileWriter]'s regenerate-the-file, skip-empty-sections approach.
 */
object OperatorProfileWriter {

    /** Renders [profile] as TOML. String values escape `\` and `"`; empty sections are skipped. */
    fun serialize(profile: OperatorProfile): String {
        val b = StringBuilder()

        if (profile.about.isNotBlank()) {
            b.append("about = ").append(str(profile.about)).append('\n')
        }

        val prefs = profile.preferences
        val hasPrefs = prefs.approvalMode.isNotBlank() ||
            prefs.preferredModels.isNotEmpty() ||
            prefs.conventions.isNotEmpty()
        if (hasPrefs) {
            if (b.isNotEmpty()) b.append('\n')
            b.append("[preferences]\n")
            if (prefs.approvalMode.isNotBlank()) {
                b.append("approval_mode = ").append(str(prefs.approvalMode)).append('\n')
            }
            if (prefs.preferredModels.isNotEmpty()) {
                b.append("preferred_models = ").append(list(prefs.preferredModels)).append('\n')
            }
            if (prefs.conventions.isNotEmpty()) {
                b.append("conventions = ").append(list(prefs.conventions)).append('\n')
            }
        }

        return b.toString()
    }

    /** Writes [profile] to `<homeDir>/.config/correx/profile.toml`, creating parent dirs if missing. */
    fun write(profile: OperatorProfile, homeDir: String = System.getProperty("user.home")) {
        val path = ProfileLoader.profilePath(homeDir)
        Files.createDirectories(path.parent)
        Files.writeString(path, serialize(profile))
    }

    private fun str(v: String): String = "\"" + v.replace("\\", "\\\\").replace("\"", "\\\"") + "\""

    private fun list(v: List<String>): String = "[" + v.joinToString(", ") { str(it) } + "]"
}
