-- ============================================================================
-- Vamoose's Companion - Animation Resolver
-- Maps behavior intents to concrete animation IDs per companion archetype.
-- ============================================================================

VC = VC or {}
VC.AnimResolver = {}

-- Intents that should randomly pick from available animations instead of first-match
local RANDOM_INTENTS = { FIDGET = true }

-- Resolve intent → animation ID for a specific companion.
-- Walks the archetype's fallback chain; first slot found in companion.animations wins.
-- FIDGET intents randomly pick from all available animations in the chain.
-- Note: Stand=0 is falsy in Lua, so all checks use ~= nil instead of truthiness.
function VC.AnimResolver:Resolve(intent, companion)
    local anims = companion and companion.animations
    if not anims then return 0 end
    local stand = anims.Stand ~= nil and anims.Stand or 0
    if not VC_AnimDB then return stand end
    local archetype = VC_AnimDB.companionArchetype[companion.key]
    local profile = archetype and VC_AnimDB.behaviors[archetype]
    if not profile then return stand end
    local chain = profile[intent]
    if not chain then return stand end

    if RANDOM_INTENTS[intent] then
        -- Collect all available animations from the chain (excluding Stand fallback)
        local available = {}
        for _, slotName in ipairs(chain) do
            if anims[slotName] ~= nil and slotName ~= "Stand" then
                available[#available + 1] = anims[slotName]
            end
        end
        if #available > 0 then
            return available[math.random(#available)]
        end
    end

    for _, slotName in ipairs(chain) do
        if anims[slotName] ~= nil then
            return anims[slotName]
        end
    end
    return stand
end

-- Derive intent from event + quote context (for talking head + portrait reaction)
function VC.AnimResolver:IntentForQuote(event, quote)
    if not VC_AnimDB then return "TALKING" end
    local intent = VC_AnimDB.eventIntents[event and event.eventType]
              or VC_AnimDB.eventIntents._default
    -- Quality escalation: epic/legendary quotes get bigger reactions
    local quality = quote and quote.quality
    if quality and VC_AnimDB.qualityUpgrades[quality] then
        intent = VC_AnimDB.qualityUpgrades[quality]
    end
    return intent
end

