-- BisManagerGenerated.lua
-- Provides API to load generated BiS presets into profiles
-- DB structure: GearManagerBiSDB[CLASS][SPEC][presetLabel] = { HEAD = {...}, ... }

local BisManager = _G.BisManager
if not BisManager then return end

function BisManager:BuildGeneratedProfileSlots(presetKey, data)
    local slots = {}
    local count = 0

    for slotKey, itemIDs in pairs(data or {}) do
        if slotKey ~= "_sourceUrl" and type(itemIDs) == "table" and #itemIDs > 0 then
            slots[slotKey] = {}
            for _, id in ipairs(itemIDs) do
                id = tonumber(id)
                slots[slotKey][#slots[slotKey] + 1] = {
                    itemID = id,
                }
                count = count + 1
            end
        end
    end

    return slots, count
end

------------------------------------------------------------------------
-- Detect current player class/spec
------------------------------------------------------------------------

function BisManager:GetPlayerClassSpecKey()
    local specIndex = GetSpecialization()
    if not specIndex then return nil, nil end

    local specID = GetSpecializationInfo(specIndex)
    if not specID then return nil, nil end

    local SPEC_ID_MAP = self.SPEC_ID_MAP or {}
    local entry = SPEC_ID_MAP[specID]
    if entry then
        return entry.class, entry.spec
    end

    -- Fallback: use classFile token (always English) + localized spec name
    local _, classFile = UnitClass("player")
    local classKey = classFile and classFile:upper():gsub(" ", "") or nil
    return classKey, nil
end

--- Returns specID, classKey, specKey for debug/display purposes
function BisManager:GetPlayerSpecInfo()
    local specIndex = GetSpecialization()
    if not specIndex then return nil, nil, nil end
    local specID = GetSpecializationInfo(specIndex)
    if not specID then return nil, nil, nil end
    local SPEC_ID_MAP = self.SPEC_ID_MAP or {}
    local entry = SPEC_ID_MAP[specID]
    if entry then
        return specID, entry.class, entry.spec
    end
    local _, classFile = UnitClass("player")
    return specID, classFile and classFile:upper():gsub(" ", "") or "?", "?"
end

------------------------------------------------------------------------
-- Get the player's preset table: GearManagerBiSDB[class][spec]
------------------------------------------------------------------------

function BisManager:GetPlayerPresets()
    if type(GearManagerBiSDB) ~= "table" then return nil end
    local classKey, specKey = self:GetPlayerClassSpecKey()
    if not classKey or not specKey then return nil end
    local classData = GearManagerBiSDB[classKey]
    if type(classData) ~= "table" then return nil end
    return classData[specKey]
end

------------------------------------------------------------------------
-- API: list / get / load presets
------------------------------------------------------------------------

function BisManager:GetGeneratedBiSKeys()
    local keys = {}
    local presets = self:GetPlayerPresets()
    if not presets then return keys end
    for k in pairs(presets) do
        keys[#keys + 1] = k
    end
    table.sort(keys)
    return keys
end

function BisManager:GetGeneratedBiS(presetKey)
    local presets = self:GetPlayerPresets()
    if not presets then return nil end
    return presets[presetKey]
end

function BisManager:GetGeneratedBiSSourceUrl(presetKey)
    local data = self:GetGeneratedBiS(presetKey)
    if data then return data._sourceUrl end
    return nil
end

function BisManager:LoadGeneratedBiS(presetKey, profileName)
    local data = self:GetGeneratedBiS(presetKey)
    if not data then return 0 end

    profileName = profileName or presetKey
    local profile = self:GetOrCreateProfile(profileName)
    if not profile then return 0 end

    profile.slots = {}
    profile.autoGenerated = true
    profile.generatedPresetKey = presetKey
    profile.sourceUrl = data._sourceUrl
    local count
    profile.slots, count = self:BuildGeneratedProfileSlots(presetKey, data)

    if count > 0 then
        self:SetActiveProfile(profileName)
        self:RefreshAll()
    end
    return count
end

------------------------------------------------------------------------
-- Auto-create profiles from BiS presets on login
------------------------------------------------------------------------

function BisManager:AutoCreateBiSProfiles()
    local presets = self:GetPlayerPresets()
    if not presets then return end

    for presetKey, data in pairs(presets) do
        local profile = self:GetOrCreateProfile(presetKey)
        if profile then
            profile.slots = {}
            profile.autoGenerated = true
            profile.generatedPresetKey = presetKey
            profile.sourceUrl = data._sourceUrl
            profile.slots = self:BuildGeneratedProfileSlots(presetKey, data)
        end
    end
end

------------------------------------------------------------------------
-- Slash command: /bis preset [key]
------------------------------------------------------------------------

local origHandleSlash = BisManager.HandleSlashCommand
function BisManager:HandleSlashCommand(msg)
    local cmd, rest = (msg or ""):match("^(%S+)%s*(.-)$")
    cmd = string.lower(cmd or "")

    if cmd == "preset" or cmd == "wowhead" or cmd == "wh" then
        rest = (rest or ""):match("^%s*(.-)%s*$")
        if rest == "" or rest == "list" then
            local keys = self:GetGeneratedBiSKeys()
            if #keys == 0 then
                DEFAULT_CHAT_FRAME:AddMessage("|cff5cc8ffBisManager|r: No BiS presets found for your class/spec.")
                return
            end
            DEFAULT_CHAT_FRAME:AddMessage("|cff5cc8ffBisManager|r: BiS presets:")
            for _, k in ipairs(keys) do
                DEFAULT_CHAT_FRAME:AddMessage("  |cff4cff4c" .. k .. "|r")
            end
            return
        end

        local count = self:LoadGeneratedBiS(rest, rest)
        if count > 0 then
            DEFAULT_CHAT_FRAME:AddMessage(("|cff5cc8ffBisManager|r: Loaded %d items from |cffffffff%s|r."):format(count, rest))
        else
            DEFAULT_CHAT_FRAME:AddMessage("|cff5cc8ffBisManager|r: Preset not found: " .. rest)
        end
        return
    end

    origHandleSlash(self, msg)
end
