-- ETB Compact: Decode helpers (v15.37.0)
-- ===========================================================================
-- v15.37.0 stores each Compact item as a Lua-literal STRING (e.g.
-- "{211980,0,12,0,0,0,0,0,2,0,25,1}") instead of a pre-expanded positional
-- table. A string is ~77% cheaper in resident memory than the live table and
-- compiles to a single bytecode constant, so the whole dataset stops costing
-- ~43 MB once materialized. Items are parsed back to their array form on
-- demand here.
--
-- Two entry points:
--   NS.Compact.Decode(raw)  full positional array (numbers + nested tables),
--                           via loadstring. Used by the per-item source decode
--                           (cached downstream), NOT for bulk iteration.
--   NS.Compact.Head(raw)    just the leading FLAT integer fields (1..~20, up to
--                           the first nested table). Fast (pattern match, no
--                           loadstring). Used by full-table iterators that only
--                           read npc / source-type / encounter / instance / etc.
--
-- Both pass real tables straight through, so verbose source data and the
-- AuditPatch additions (which still ship as arrays) keep working unchanged.
-- ===========================================================================

local _, NS = ...
NS.Compact = NS.Compact or {}

function NS.Compact.Decode(raw)
    if type(raw) == "table" then return raw end
    if type(raw) ~= "string" then return nil end
    local f = loadstring("return " .. raw)
    if not f then return nil end
    local ok, arr = pcall(f)
    if ok and type(arr) == "table" then return arr end
    return nil
end

function NS.Compact.Head(raw)
    if type(raw) == "table" then return raw end
    if type(raw) ~= "string" then return nil end
    -- Leading flat portion: everything after the opening brace up to the first
    -- nested table. Fields 1..20 are all plain integers; nested tables (coords,
    -- variants, sources, cost) only appear from field 21 onward.
    local body = raw:match("^{([^{}]*)")
    if not body then return nil end
    local t, i = {}, 0
    for num in body:gmatch("(-?%d+)") do
        i = i + 1
        t[i] = tonumber(num)
    end
    return t
end
