-- HDG_HT_LayoutDump.lua
-- Effective-LAYOUT_CONFIG dumper. Serialises the resolved layout (defaults +
-- user overrides + picker reorderings) into a copy-paste dialog so a tester
-- can round-trip in-game tweaks back into HDG_HT_LayoutConfig.lua.
--
-- Public API:
--   privateDB.HDG_HT.LayoutDump.Dump()  — opens the copy dialog
--   _G.HDG_PrintOrder()                 — prints effective widget order to chat

local _, privateDB = ...
privateDB.HDG_HT = privateDB.HDG_HT or {}
local LayoutDump = {}
privateDB.HDG_HT.LayoutDump = LayoutDump

local HDG_HT = privateDB.HDG_HT
local LayoutStore = privateDB.HDG_HT.LayoutStore

local function GetSavedOverrides()
    return LayoutStore.GetAll()
end

-- Recursive Lua-table → string serializer. Stable key order; one-line numbers
-- and short strings; nested tables on their own lines.
local function serialize(v, indent)
    indent = indent or ""
    local t = type(v)
    if t == "string" then
        return string.format("%q", v)
    elseif t == "number" or t == "boolean" then
        return tostring(v)
    elseif t == "table" then
        local nextIndent = indent .. "    "
        local lines = { "{" }
        local nKeys, sKeys = {}, {}
        for k in pairs(v) do
            if type(k) == "number" then nKeys[#nKeys+1] = k
            else sKeys[#sKeys+1] = k end
        end
        table.sort(nKeys)
        table.sort(sKeys)
        for _, k in ipairs(nKeys) do
            lines[#lines+1] = nextIndent .. serialize(v[k], nextIndent) .. ","
        end
        for _, k in ipairs(sKeys) do
            local keyStr = k:match("^[%a_][%w_]*$") and k or string.format("[%q]", k)
            lines[#lines+1] = nextIndent .. keyStr .. " = " .. serialize(v[k], nextIndent) .. ","
        end
        lines[#lines+1] = indent .. "}"
        return table.concat(lines, "\n")
    end
    return "nil"
end

-- Reusable copy/paste dialog: scrollframe + multiline editbox + Close.
-- Auto-selects all on focus. Built lazily on first call.
local _copyDialog
local function ShowCopyDialog(title, text)
    if not _copyDialog then
        local d = CreateFrame("Frame", "HDG_HT_CopyDialog", UIParent, "BasicFrameTemplateWithInset")
        d:SetSize(640, 420)
        d:SetPoint("CENTER")
        d:SetFrameStrata("DIALOG")
        d:SetMovable(true); d:EnableMouse(true)
        d:RegisterForDrag("LeftButton")
        d:SetScript("OnDragStart", d.StartMoving)
        d:SetScript("OnDragStop",  d.StopMovingOrSizing)
        d.title = d:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        d.title:SetPoint("TOP", 0, -5)

        local hint = d:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        hint:SetPoint("TOPLEFT", 12, -28)
        hint:SetText("Press Ctrl+A to select all, then Ctrl+C to copy.")
        hint:SetTextColor(0.7, 0.7, 0.7)

        local scroll = CreateFrame("ScrollFrame", nil, d, "InputScrollFrameTemplate")
        scroll:SetPoint("TOPLEFT", 12, -46)
        scroll:SetPoint("BOTTOMRIGHT", -32, 12)
        scroll.CharCount:Hide()

        local eb = scroll.EditBox
        eb:SetFontObject("GameFontHighlightSmall")
        eb:SetMaxLetters(0)
        eb:SetAutoFocus(false)
        eb:SetMultiLine(true)
        eb:SetScript("OnEscapePressed", function() d:Hide() end)
        eb:SetScript("OnEditFocusGained", function(self) self:HighlightText() end)

        d.editBox = eb
        _copyDialog = d
    end
    _copyDialog.title:SetText(title or "")
    _copyDialog.editBox:SetText(text or "")
    _copyDialog:Show()
    _copyDialog.editBox:SetFocus()
    _copyDialog.editBox:HighlightText()
end
LayoutDump.ShowCopyDialog = ShowCopyDialog

-- Build the effective LAYOUT_CONFIG (defaults + overrides + reorderings) and
-- show it in the copy dialog. The serializer renders widgets table keys
-- alphabetically (Lua key order is unspecified), so user reorderings are
-- preserved via sequential integer `order` fields — a paste back into source
-- replays the user's display sequence exactly.
function LayoutDump.Dump()
    local cfg = HDG_HT.LayoutConfig
    if not cfg or not HDG_HT.Resolver then
        print("|cFFFF0000[HDG]|r Cockpit not loaded.")
        return
    end
    local effective = HDG_HT.Resolver.Resolve(cfg, GetSavedOverrides())
    local out = {
        grid    = cfg.grid,
        cards   = cfg.cards,
        widgets = {},
    }
    for i, spec in ipairs(effective) do
        local widgetCopy = {}
        for k, v in pairs(spec) do
            if k ~= "id" and k ~= "order" then widgetCopy[k] = v end
        end
        widgetCopy.order = i
        out.widgets[spec.id] = widgetCopy
    end
    ShowCopyDialog("HDG Cockpit — Effective LAYOUT_CONFIG",
        "-- paste into HDG_HT_LayoutConfig.lua to graduate runtime tweaks\nlocal LAYOUT_CONFIG = "
        .. serialize(out))
end

-- Quick /run-friendly inspector: prints the effective widget order to chat.
function _G.HDG_PrintOrder()
    if not HDG_HT.LayoutConfig or not HDG_HT.Resolver then return end
    local effective = HDG_HT.Resolver.Resolve(HDG_HT.LayoutConfig, GetSavedOverrides())
    print("|cFFfcd34d[HDG cockpit]|r Effective widget order (" .. #effective .. "):")
    local quoted = {}
    for i, spec in ipairs(effective) do
        print(string.format("  %2d. %s", i, spec.id))
        quoted[i] = '"' .. spec.id .. '"'
    end
    print("  → " .. "{ " .. table.concat(quoted, ", ") .. " }")
end
