const fs = require("node:fs")
const path = require("node:path")

function parseSettings(settingsFile) {
    const settings = fs.readFileSync(settingsFile, "utf-8").toString().split("\n").filter(line => line.trim() !== "")
    const parseSettings = {}
    for (let i = 0; i < settings.length; i++) {
        const line = settings[i].trim()
        const [key, value] = line.split(":")
        if (key && value) {
            const trimmedValue = value.trim().toLowerCase()
            if (trimmedValue === "true" || trimmedValue === "false") {
                parseSettings[key.trim()] = trimmedValue === "true"
            } else {
                parseSettings[key.trim()] = isNaN(value) ? value.trim() : parseInt(value, 10)
            }
        }
    }
    return parseSettings
}

function stringfySettings(settingsFile) {
    const settingsObject = JSON.parse(fs.readFileSync(settingsFile, "utf-8").toString())
    const settingsArray = []
    if (typeof settingsObject !== "object" || settingsObject === null) {
        throw new Error("Invalid settings object")
    }
    for (const settingKey in settingsObject) {
        if (Object.prototype.hasOwnProperty.call(settingsObject, settingKey)) {
            const settingValue = settingsObject[settingKey]
            if (typeof settingValue === "object" || typeof settingValue === "function" || typeof settingValue === "symbol") {
                throw new Error(`Invalid value for setting "${settingKey}": ${settingValue}`)
            }
            settingsArray.push(`${settingKey}:${settingValue}`)
        }
    }
    return settingsArray.join("\n")
}

module.exports = {
    parseSettings,
    stringfySettings
}