-- harmony_preview_export.lua
-- Visual-regression harness (stage 1 of 2). Runs the REAL engine over sample
-- dyes (2 per colour group) through every applicable strategy and writes a flat
-- file the Python renderer (harmony_preview_render.py) turns into swatch sheets.
-- Driven by harmony_preview.sh; not a test_*.lua, so run_all.sh ignores it.
-- Run from the addon root:  lua tests/harmony_preview_export.lua
dofile("Core/VDS_ColorMath.lua")
dofile("Core/VDS_HarmonyWheel.lua")
dofile("Core/VDS_Harmony.lua")
dofile("Data/VDS_ColorMapDB.lua")
local H, HW, byName = VDS.Harmony, VDS.HarmonyWheel, VDS_ColorMapDB.byName

local function unpackRGB(v)
    local u = tonumber(v) % 4294967296
    return { r = (math.floor(u / 65536) % 256) / 255,
             g = (math.floor(u / 256) % 256) / 255,
             b = (u % 256) / 255 }
end

local infos, order = {}, {}
local f = assert(io.open("/tmp/dyecolor.csv", "r"), "missing /tmp/dyecolor.csv (harmony_preview.sh fetches it)")
f:read("l")
for line in f:lines() do
    local name, id, _, _, _, start =
        line:match('^"([^"]*)",(%-?%d+),(%-?%d+),(%-?%d+),(%-?%d+),(%-?%d+)')
    if name and id then
        id = tonumber(id)
        infos[id] = { name = name, colorGroup = byName[name], swatchRGB = unpackRGB(start) }
        order[#order + 1] = id
    end
end
f:close()

local byGroup = {}
for _, id in ipairs(order) do
    local g = infos[id].colorGroup
    if g then byGroup[g] = byGroup[g] or {}; table.insert(byGroup[g], id) end
end

local GROUPS = { "Red", "Orange", "Yellow", "Green", "Teal", "Blue", "Purple", "Pink",
                 "Brown", "Grey", "Black", "White" }
local CHROM = { "Neutral", "Monochromatic", "Analogous", "Complement", "Split", "Triad", "Clash" }
local NEU   = { "Tones", "Contrast", "Accent" }

local function rgb255(c) return math.floor(c.r * 255 + 0.5), math.floor(c.g * 255 + 0.5), math.floor(c.b * 255 + 0.5) end

local out = assert(io.open("/tmp/harmony_data.txt", "w"))
for _, grp in ipairs(GROUPS) do
    local ids = byGroup[grp] or {}
    for s = 1, math.min(2, #ids) do                  -- 2 samples per group
        local id = ids[s]
        local a  = infos[id]
        out:write(string.format("DYE\t%s\t%s\t%d\t%d\t%d\n", a.name, grp, rgb255(a.swatchRGB)))
        local res = H.forDye(id, infos, {})
        local strategies = HW.ANGLE[grp] and CHROM or NEU
        for _, key in ipairs(strategies) do
            local picks = H.autoFill(res, key, 2)    -- 3-channel scheme: anchor + 2 fills
            local parts = { string.format("%s=%d,%d,%d", a.name, rgb255(a.swatchRGB)) }  -- anchor first
            for _, p in ipairs(picks) do
                local pi = infos[p.dyeID]
                parts[#parts + 1] = string.format("%s=%d,%d,%d", pi.name, rgb255(pi.swatchRGB))
            end
            out:write("S\t" .. key .. "\t" .. table.concat(parts, ";") .. "\n")
        end
    end
end
out:close()
print("wrote /tmp/harmony_data.txt")
