-- =============================================================================
-- Container State Lua API Examples
-- =============================================================================
-- This file demonstrates how to manage persistent container states using
-- the ecs.container API. Container states are stored in the
-- ContainerStateRegistry singleton, separate from entity inventories.
--
-- Use cases:
--   - Persistent chests that remember their contents across sessions
--   - Shop inventories that reset on a timer
--   - Quest containers that change state based on story progress
--   - Lootable containers that can be emptied permanently
-- =============================================================================

-- =============================================================================
-- Setting Container State
-- =============================================================================

-- Define the contents of a treasure chest
ecs.container.set_state("treasure_chest_001", {
    { itemId = "sword_iron", stackSize = 1 },
    { itemId = "potion_health", stackSize = 3 },
    { itemId = "gold_coin", stackSize = 100 }
})

print("Set state for treasure_chest_001")

-- Define a shop inventory
ecs.container.set_state("blacksmith_shop", {
    { itemId = "sword_iron", stackSize = 3 },
    { itemId = "bow_wood", stackSize = 2 },
    { itemId = "arrow", stackSize = 50 },
    { itemId = "potion_health", stackSize = 5 }
})

print("Set state for blacksmith_shop")

-- =============================================================================
-- Getting Container State
-- =============================================================================

-- Retrieve the contents of a container
local chest_contents = ecs.container.get_state("treasure_chest_001")
print("Treasure chest contents (" .. #chest_contents .. " items):")
for i, slot in ipairs(chest_contents) do
    print("  [" .. i .. "] " .. slot.itemId .. " x" .. slot.stackSize)
end

-- =============================================================================
-- Updating Container State
-- =============================================================================

-- Simulate looting the chest: remove items and update state
local function loot_container(container_id, item_id, count)
    local contents = ecs.container.get_state(container_id)
    local remaining = count

    -- Build new contents minus the looted items
    local new_contents = {}
    for _, slot in ipairs(contents) do
        if slot.itemId == item_id and remaining > 0 then
            local to_remove = math.min(remaining, slot.stackSize)
            slot.stackSize = slot.stackSize - to_remove
            remaining = remaining - to_remove
        end
        if slot.stackSize > 0 then
            table.insert(new_contents, slot)
        end
    end

    ecs.container.set_state(container_id, new_contents)
    print("Looted " .. (count - remaining) .. " " .. item_id .. " from " .. container_id)
    return count - remaining
end

-- Player loots 2 health potions from the chest
loot_container("treasure_chest_001", "potion_health", 2)

-- Check what's left
local remaining = ecs.container.get_state("treasure_chest_001")
print("Remaining in treasure_chest_001:")
for i, slot in ipairs(remaining) do
    print("  [" .. i .. "] " .. slot.itemId .. " x" .. slot.stackSize)
end

-- =============================================================================
-- Clearing Container State
-- =============================================================================

-- Clear a container's state (e.g., after it's been fully looted)
ecs.container.clear_state("treasure_chest_001")
print("Cleared state for treasure_chest_001")

-- Verify it's empty
local empty = ecs.container.get_state("treasure_chest_001")
print("After clear, contents count: " .. #empty)

-- =============================================================================
-- Practical: Shop Restocking
-- =============================================================================

-- Restock a shop's inventory (reset to initial state)
function restock_shop(shop_id)
    local stock = {
        blacksmith_shop = {
            { itemId = "sword_iron", stackSize = 3 },
            { itemId = "bow_wood", stackSize = 2 },
            { itemId = "arrow", stackSize = 50 },
            { itemId = "potion_health", stackSize = 5 }
        },
        alchemist_shop = {
            { itemId = "potion_health", stackSize = 10 },
            { itemId = "potion_stamina", stackSize = 10 }
        }
    }

    if stock[shop_id] then
        ecs.container.set_state(shop_id, stock[shop_id])
        print("Restocked " .. shop_id)
    else
        print("Unknown shop: " .. shop_id)
    end
end

-- Simulate a purchase: remove items from shop
local function buy_from_shop(shop_id, item_id, count)
    local contents = ecs.container.get_state(shop_id)
    local available = 0
    for _, slot in ipairs(contents) do
        if slot.itemId == item_id then
            available = slot.stackSize
            break
        end
    end

    if available >= count then
        loot_container(shop_id, item_id, count)
        print("Purchased " .. count .. " " .. item_id .. " from " .. shop_id)
        return true
    else
        print("Not enough stock in " .. shop_id .. " (have " .. available .. ", need " .. count .. ")")
        return false
    end
end

-- Player buys from blacksmith
buy_from_shop("blacksmith_shop", "sword_iron", 1)
buy_from_shop("blacksmith_shop", "arrow", 10)

-- Restock the shop
restock_shop("blacksmith_shop")

-- =============================================================================
-- Practical: Quest Container with Conditional State
-- =============================================================================

-- A quest container that changes based on story progress
function setup_quest_container(quest_stage)
    if quest_stage == "not_started" then
        ecs.container.set_state("ancient_tomb", {
            { itemId = "potion_health", stackSize = 2 },
            { itemId = "gold_coin", stackSize = 50 }
        })
    elseif quest_stage == "in_progress" then
        ecs.container.set_state("ancient_tomb", {
            { itemId = "potion_health", stackSize = 2 },
            { itemId = "gold_coin", stackSize = 50 },
            { itemId = "amulet_legendary", stackSize = 1 }
        })
    elseif quest_stage == "completed" then
        ecs.container.clear_state("ancient_tomb")
    end
    print("Quest container 'ancient_tomb' set to stage: " .. quest_stage)
end

setup_quest_container("not_started")
setup_quest_container("in_progress")
setup_quest_container("completed")

-- =============================================================================
-- API Reference
-- =============================================================================
--
-- ecs.container.set_state(container_id, slots_table) -> nil
--   Sets the persistent state of a container.
--   Each slot: { itemId = "...", stackSize = N }
--
-- ecs.container.get_state(container_id) -> table of { itemId, stackSize }
--   Returns the current state of a container.
--
-- ecs.container.clear_state(container_id) -> nil
--   Clears all items from a container's state.
--
-- Container state is separate from entity inventories (InventoryComponent).
-- Use containers for persistent world objects like chests, shops, and
-- quest lootables that need to remember their state across sessions.
-- =============================================================================

print("Container examples completed successfully!")
