local MOD_NAME = "NotOnlyTitanium"
local SAVED_PATH = "./ue4ss/Mods/SN2ModSettings/saved/" .. MOD_NAME .. ".lua"
local MANIFEST_FILE = "./ue4ss/Mods/SN2ModSettings/registrations/" .. MOD_NAME .. ".lua"

local DEFAULTS = {
    SpeedEnabled        = false,
    SpeedMultiplier     = 1.0,
    CustomLootEnabled   = true,
    NewScanRewardChance = 35,
    Titanium_Chance     = 65,
    Quartz_Chance       = 40,
    Copper_Chance       = 35,
    Silver_Chance       = 10,
    Depth_Tier1         = 100,
    Depth_Tier2         = 150,
    Depth_Tier3         = 250,
    Depth_Tier4         = 300,
    Gold_Chance         = 10,
    Lead_Chance         = 15,
    Lithium_Chance      = 18,
    Sulfur_Chance       = 18,
    ConduitCrystal_Chance = 14,
    Enamel_Chance       = 12,
    Celestine_Chance    = 14,
    Atacamite_Chance    = 10,
    Troilite_Chance     = 10,
    DepthReductionPerTier = 4,
}

local LOOT_KEYS = {
    "NewScanRewardChance", "Titanium_Chance", "Quartz_Chance", "Copper_Chance",
    "Silver_Chance", "Depth_Tier1", "Depth_Tier2", "Depth_Tier3", "Depth_Tier4",
    "Gold_Chance", "Lead_Chance", "Lithium_Chance", "Sulfur_Chance",
    "ConduitCrystal_Chance", "Enamel_Chance", "Celestine_Chance",
    "Atacamite_Chance", "Troilite_Chance", "DepthReductionPerTier",
}

local Config = {}
for k, v in pairs(DEFAULTS) do Config[k] = v end

_G.NOT_ONLY_TITANIUM_CONFIG   = Config
_G.NOT_ONLY_TITANIUM_DEFAULTS = DEFAULTS

local ModRef = nil
pcall(function()
    ModRef = api:get_mod("SN2ModSettings")
end)

local function toBool(raw)
    if type(raw) == "boolean" then
        return raw
    end
    if type(raw) == "number" then
        return raw ~= 0
    end
    local s = tostring(raw):lower()
    return s ~= "false" and s ~= "0" and s ~= ""
end

local function read_lua_table(path)
    local ok_open, f = pcall(io.open, path, "r")
    if not ok_open or not f then return nil end
    local ok_read, content = pcall(function() return f:read("*all") end)
    pcall(function() f:close() end)
    if not ok_read or not content then return nil end
    local fn = load(content)
    if not fn then return nil end
    local ok, data = pcall(fn)
    if not ok or type(data) ~= "table" then return nil end
    return data
end

local function applyData(data)
    if type(data) ~= "table" then return false end
    local changed = false

    local function set(k, raw)
        if raw == nil then return end
        local default = DEFAULTS[k]
        local v
        if type(default) == "boolean" then
            v = toBool(raw)
        else
            v = tonumber(raw)
        end
        if v ~= nil and Config[k] ~= v then
            Config[k] = v
            changed = true
        end
    end

    set("SpeedEnabled",    data.SpeedEnabled)
    set("SpeedMultiplier", data.SpeedMultiplier)

    local customOn = toBool(data.CustomLootEnabled ~= nil and data.CustomLootEnabled or true)
    if data.CustomLootEnabled ~= nil then
        customOn = toBool(data.CustomLootEnabled)
    else
        customOn = true
    end

    if Config.CustomLootEnabled ~= customOn then
        Config.CustomLootEnabled = customOn
        changed = true
    end

    if customOn then
        for _, k in ipairs(LOOT_KEYS) do
            set(k, data[k])
        end
    else
        for _, k in ipairs(LOOT_KEYS) do
            if Config[k] ~= DEFAULTS[k] then
                Config[k] = DEFAULTS[k]
                changed = true
            end
        end
    end

    return changed
end

local function load_saved_config()
    local changed = false
    local got_any_shared = false

    if ModRef then
        local function getShared(key)
            local ok, val = pcall(function()
                return ModRef:GetSharedVariable(MOD_NAME .. "_" .. key)
            end)
            if ok then return val end
            return nil
        end

        local rawSpeedEnabled = getShared("SpeedEnabled")
        if rawSpeedEnabled ~= nil then
            got_any_shared = true
            local v = toBool(rawSpeedEnabled)
            if Config.SpeedEnabled ~= v then Config.SpeedEnabled = v; changed = true end
        end

        local rawSpeed = getShared("SpeedMultiplier")
        if rawSpeed ~= nil then
            got_any_shared = true
            local v = tonumber(rawSpeed) or DEFAULTS.SpeedMultiplier
            if Config.SpeedMultiplier ~= v then Config.SpeedMultiplier = v; changed = true end
        end

        local rawCustom = getShared("CustomLootEnabled")
        if rawCustom ~= nil then
            got_any_shared = true
            local v = toBool(rawCustom)
            if Config.CustomLootEnabled ~= v then Config.CustomLootEnabled = v; changed = true end
        end

        if Config.CustomLootEnabled then
            for _, k in ipairs(LOOT_KEYS) do
                local raw = getShared(k)
                if raw ~= nil then
                    got_any_shared = true
                    local v = tonumber(raw)
                    if v ~= nil and Config[k] ~= v then Config[k] = v; changed = true end
                end
            end
        else
            for _, k in ipairs(LOOT_KEYS) do
                if Config[k] ~= DEFAULTS[k] then Config[k] = DEFAULTS[k]; changed = true end
            end
        end
    end

    if not got_any_shared then
        local data = read_lua_table(SAVED_PATH)
        if data then
            return applyData(data)
        end
    end

    return changed
end

_G.NOT_ONLY_TITANIUM_LOAD_CONFIG = load_saved_config

LoopAsync(1500, function()
    local ok, err = pcall(function()
        local changed = false

        if ModRef then
            ExecuteInGameThread(function()
                local ok2, err2 = pcall(function()
                    changed = load_saved_config()
                end)
                if not ok2 then
                    print("[NotOnlyTitanium] ERROR in load_saved_config: " .. tostring(err2))
                end
            end)
        else
            local ok2, err2 = pcall(function()
                changed = load_saved_config()
            end)
            if not ok2 then
                print("[NotOnlyTitanium] ERROR in load_saved_config: " .. tostring(err2))
            end
        end

        if changed then
            ExecuteInGameThread(function()
                local ok3, err3 = pcall(function()
                    if _G.NOT_ONLY_TITANIUM_SPEED_APPLY_ALL then
                        _G.NOT_ONLY_TITANIUM_SPEED_APPLY_ALL()
                    end
                end)
                if not ok3 then
                    print("[NotOnlyTitanium] ERROR in SPEED_APPLY_ALL: " .. tostring(err3))
                end
            end)
        end
    end)

    if not ok then
        print("[NotOnlyTitanium] ERROR in LoopAsync: " .. tostring(err))
    end
end)

local function ensure_dir(path)
    local ok, err = pcall(function()
        local dir = path:match("(.*[/\\])")
        if not dir or dir == "" then return end
        if package.config:sub(1,1) == "\\" then
            os.execute('mkdir "' .. dir:gsub("/", "\\") .. '" 2>nul')
        else
            os.execute('mkdir -p "' .. dir .. '" 2>/dev/null')
        end
    end)
    if not ok then
        print("[NotOnlyTitanium] ERROR in ensure_dir: " .. tostring(err))
    end
end

local function write_file(path, content)
    ensure_dir(path)
    local ok, f = pcall(io.open, path, "w")
    if not ok or not f then
        print("[NotOnlyTitanium] ERROR: cannot write manifest: " .. path)
        return
    end
    local ok2, err2 = pcall(function() f:write(content) end)
    pcall(function() f:close() end)
    if not ok2 then
        print("[NotOnlyTitanium] ERROR: cannot write content: " .. tostring(err2))
    end
end

local function save_manifest()
    write_file(MANIFEST_FILE, [[
return {
    name    = "NotOnlyTitanium",
    display = "Not Only Titanium",
    settings = {
        {
            key     = "SpeedEnabled",
            title   = "Scanner speed module",
            description     = "Enables a multiplier that increases the scan speed of the Scanner tool. Disable this to keep vanilla scan times.",
            type    = "toggle",
            default = false,
        },
        {
            key        = "SpeedMultiplier",
            title      = "Speed multiplier",
            description       = "How many times faster the scanner works compared to vanilla. 1.0 = no change, 2.0 = twice as fast, up to 10.0. Has no effect when speed boost is disabled.",
            type       = "slider",
            default    = 1.0,
            min        = 1.0,
            max        = 10.0,
            step       = 0.5,
            enabled_by = "SpeedEnabled",
        },
        {
            key     = "CustomLootEnabled",
            title   = "Custom loot config",
            description     = "When ON, you can customize loot to your preference. When OFF, loot values revert to the mod defaults.",
            type    = "toggle",
            default = false,
        },
        {
            key        = "NewScanRewardChance",
            title      = "First scan reward chance (%)",
            description        = "Probability that scanning an unknown object will drop any resource at all. Set to 0 to disable scan rewards entirely.",
            type       = "slider",
            default    = 35,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Titanium_Chance",
            title      = "Titanium chance",
            description        = "Drop chance for Titanium. Available at all depths.",
            type       = "slider",
            default    = 65,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Quartz_Chance",
            title      = "Quartz chance",
            description        = "Drop chance for Quartz. Available at all depths.",
            type       = "slider",
            default    = 40,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Copper_Chance",
            title      = "Copper chance",
            description        = "Drop chance for Copper Ore. Available at all depths.",
            type       = "slider",
            default    = 35,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Silver_Chance",
            title      = "Silver chance",
            description        = "Drop chance for Silver Ore. Available at all depths.",
            type       = "slider",
            default    = 10,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Depth_Tier1",
            title      = "Tier 1 depth — Gold & Lead unlock (m)",
            description        = "Depth in metres at which Gold and Lead are added to the loot pool. Keep this value lower than Tier 2.",
            type       = "slider",
            default    = 100,
            min        = 0,
            max        = 400,
            step       = 10,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Depth_Tier2",
            title      = "Tier 2 depth — Lithium & Sulfur unlock (m)",
            description        = "Depth at which Lithium and Sulfur enter the loot pool. Should be deeper than Tier 1.",
            type       = "slider",
            default    = 150,
            min        = 0,
            max        = 400,
            step       = 10,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Depth_Tier3",
            title      = "Tier 3 depth — Conduit Crystal, Enamel & Celestine unlock (m)",
            description        = "Depth at which rare crystal resources unlock. Recommended to keep above 200m.",
            type       = "slider",
            default    = 250,
            min        = 0,
            max        = 400,
            step       = 10,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Depth_Tier4",
            title      = "Tier 4 depth — Atacamite & Troilite unlock (m)",
            description        = "Depth at which the deepest exotic minerals unlock. Should be the largest depth value of all tiers.",
            type       = "slider",
            default    = 300,
            min        = 0,
            max        = 400,
            step       = 10,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "DepthReductionPerTier",
            title      = "Chance penalty per 100m depth tier",
            description        = "Reduces drop chances for shallow resources the deeper you go. For example, a value of 4 means Quartz loses 4% chance for every 100m depth tier above the surface.",
            type       = "slider",
            default    = 4,
            min        = 0,
            max        = 20,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Gold_Chance",
            title      = "Gold chance (tier 1+)",
            description        = "Drop chance for Gold. Only available once you reach the Tier 1 depth threshold.",
            type       = "slider",
            default    = 10,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Lead_Chance",
            title      = "Lead chance (tier 1+)",
            description        = "Drop chance for Lead. Only available once you reach the Tier 1 depth threshold.",
            type       = "slider",
            default    = 15,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Lithium_Chance",
            title      = "Lithium chance (tier 2+)",
            description        = "Drop chance for Lithium. Only available once you reach the Tier 2 depth threshold.",
            type       = "slider",
            default    = 18,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Sulfur_Chance",
            title      = "Sulfur chance (tier 2+)",
            description        = "Drop chance for Sulfur. Only available once you reach the Tier 2 depth threshold.",
            type       = "slider",
            default    = 18,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "ConduitCrystal_Chance",
            title      = "Conduit Crystal chance (tier 3+)",
            description        = "Drop chance for Conduit Crystal. Only available once you reach the Tier 3 depth threshold.",
            type       = "slider",
            default    = 14,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Enamel_Chance",
            title      = "Enamel chance (tier 3+)",
            description        = "Drop chance for Enamel. Only available once you reach the Tier 3 depth threshold.",
            type       = "slider",
            default    = 12,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Celestine_Chance",
            title      = "Celestine chance (tier 3+)",
            description        = "Drop chance for Celestine. Only available once you reach the Tier 3 depth threshold.",
            type       = "slider",
            default    = 14,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Atacamite_Chance",
            title      = "Atacamite chance (tier 4+)",
            description        = "Drop chance for Atacamite. Only available once you reach the Tier 4 depth threshold.",
            type       = "slider",
            default    = 10,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
        {
            key        = "Troilite_Chance",
            title      = "Troilite chance (tier 4+)",
            description        = "Drop chance for Troilite. Only available once you reach the Tier 4 depth threshold.",
            type       = "slider",
            default    = 10,
            min        = 0,
            max        = 100,
            step       = 1,
            enabled_by = "CustomLootEnabled",
        },
    }
}
]])
end

pcall(save_manifest)