-- =============================================================================
-- Quest Reward Lua API Examples
-- =============================================================================
-- This file demonstrates how to use the inventory and container APIs
-- together to implement quest reward systems.
--
-- This combines:
--   - ecs.inventory.* for player inventory management
--   - ecs.container.* for quest container state
--   - ecs.items.* for item registry queries
--   - ecs.send_event / ecs.subscribe_event for event-driven quest flow
-- =============================================================================

-- =============================================================================
-- Setup: Create player and quest-related entities
-- =============================================================================

-- Create the player entity with an inventory
local player = ecs.create_entity()
ecs.set_entity_name(player, "player")
ecs.set_component(player, "Inventory", {
    maxSlots = 30,
    maxWeight = 100.0,
    isContainer = false,
    containerId = ""
})

print("Created player entity (ID: " .. player .. ")")

-- Create a quest giver NPC
local quest_giver = ecs.create_entity()
ecs.set_entity_name(quest_giver, "quest_giver_elder")
ecs.set_component(quest_giver, "Inventory", {
    maxSlots = 10,
    maxWeight = 50.0,
    isContainer = false,
    containerId = ""
})

print("Created quest giver entity (ID: " .. quest_giver .. ")")

-- =============================================================================
-- Quest Reward Distribution
-- =============================================================================

-- Give the player starting equipment
ecs.inventory.add(player, "sword_iron", 1)
ecs.inventory.add(player, "potion_health", 3)
ecs.inventory.add(player, "gold_coin", 25)

print("Player starting equipment added")

-- Give the quest giver some reward items
ecs.inventory.add(quest_giver, "gold_coin", 200)
ecs.inventory.add(quest_giver, "potion_health", 2)
ecs.inventory.add(quest_giver, "amulet_legendary", 1)

print("Quest giver reward items added")

-- =============================================================================
-- Quest Completion: Reward Player
-- =============================================================================

-- Complete a quest and give the player rewards
function complete_quest(quest_name, reward_items, xp_reward)
    print("=== Quest Completed: " .. quest_name .. " ===")
    print("XP Reward: " .. xp_reward)

    -- Give each reward item to the player
    for _, reward in ipairs(reward_items) do
        local item_def = ecs.items.find(reward.itemId)
        if item_def then
            ecs.inventory.add(player, reward.itemId, reward.count)
            print("  Received: " .. reward.count .. "x " .. item_def.itemName)
        else
            print("  WARNING: Unknown item '" .. reward.itemId .. "'")
        end
    end

    -- Send a quest completion event
    ecs.send_event("quest_completed", {
        quest_name = quest_name,
        player_id = player,
        xp_rewarded = xp_reward
    })

    print("Quest completion event sent")
end

-- Complete "The Lost Artifact" quest
complete_quest("The Lost Artifact", {
    { itemId = "gold_coin", count = 100 },
    { itemId = "potion_health", count = 2 }
}, 500)

-- =============================================================================
-- Quest Item Requirement Check
-- =============================================================================

-- Check if the player has the required items for a quest
function has_quest_items(quest_requirements)
    for _, req in ipairs(quest_requirements) do
        local count = ecs.inventory.count(player, req.itemId)
        if count < req.count then
            local def = ecs.items.find(req.itemId)
            local name = def and def.itemName or req.itemId
            print("  Missing: " .. (req.count - count) .. " more " .. name)
            return false
        end
    end
    return true
end

-- Remove quest items from the player's inventory (turn in)
function remove_quest_items(quest_requirements)
    for _, req in ipairs(quest_requirements) do
        ecs.inventory.remove(player, req.itemId, req.count)
        local def = ecs.items.find(req.itemId)
        local name = def and def.itemName or req.itemId
        print("  Removed: " .. req.count .. "x " .. name)
    end
end

-- Define a quest that requires items
local bandit_quest = {
    name = "Bandit Menace",
    requirements = {
        { itemId = "sword_iron", count = 1 },
        { itemId = "potion_health", count = 2 }
    },
    rewards = {
        { itemId = "gold_coin", count = 150 },
        { itemId = "bow_wood", count = 1 }
    },
    xp = 750
}

-- Check if player can start the quest
print("Checking quest requirements for '" .. bandit_quest.name .. "':")
if has_quest_items(bandit_quest.requirements) then
    print("Player has all required items!")
    remove_quest_items(bandit_quest.requirements)
    complete_quest(bandit_quest.name, bandit_quest.rewards, bandit_quest.xp)
else
    print("Player does not meet quest requirements")
end

-- =============================================================================
-- Quest Container Loot
-- =============================================================================

-- Set up a quest-related container (e.g., a treasure chest at the quest location)
ecs.container.set_state("bandit_hideout_chest", {
    { itemId = "gold_coin", stackSize = 200 },
    { itemId = "potion_health", stackSize = 2 },
    { itemId = "potion_stamina", stackSize = 1 }
})

print("Bandit hideout chest populated with loot")

-- Player loots the chest
local chest_loot = ecs.container.get_state("bandit_hideout_chest")
print("Looting bandit hideout chest:")
for _, slot in ipairs(chest_loot) do
    ecs.inventory.add(player, slot.itemId, slot.stackSize)
    local def = ecs.items.find(slot.itemId)
    local name = def and def.itemName or slot.itemId
    print("  Acquired: " .. slot.stackSize .. "x " .. name)
end

-- Clear the chest after looting
ecs.container.clear_state("bandit_hideout_chest")
print("Chest cleared after looting")

-- =============================================================================
-- Quest Progression with Event Subscriptions
-- =============================================================================

-- Track quest state
local quest_state = {
    active_quests = {},
    completed_quests = {}
}

-- Subscribe to quest completion events
local quest_sub = ecs.subscribe_event("quest_completed", function(event, params)
    local quest_name = params.quest_name or "unknown"
    local xp = params.xp_rewarded or 0

    -- Track completed quests
    table.insert(quest_state.completed_quests, quest_name)

    print("[Quest Log] Completed: " .. quest_name .. " (+" .. xp .. " XP)")
    print("[Quest Log] Total completed: " .. #quest_state.completed_quests)
end)

print("Subscribed to quest_completed events (ID: " .. quest_sub .. ")")

-- =============================================================================
-- Practical: Full Quest Flow
-- =============================================================================

function run_quest_flow(quest_name, requirements, rewards, xp)
    print("\n=== Starting Quest: " .. quest_name .. " ===")

    -- 1. Check requirements
    if not has_quest_items(requirements) then
        print("Cannot start quest - missing items")
        return false
    end

    -- 2. Remove quest items
    print("Turning in quest items:")
    remove_quest_items(requirements)

    -- 3. Complete quest and give rewards
    complete_quest(quest_name, rewards, xp)

    return true
end

-- Run a second quest
run_quest_flow(
    "The Blacksmith's Request",
    {
        { itemId = "gold_coin", count = 50 }
    },
    {
        { itemId = "sword_iron", count = 1 },
        { itemId = "gold_coin", count = 75 }
    },
    300
)

-- =============================================================================
-- Summary
-- =============================================================================
-- Quest reward patterns demonstrated:
--
-- 1. Direct reward: ecs.inventory.add() to give items to the player
-- 2. Requirement check: ecs.inventory.count() to verify quest items
-- 3. Item removal: ecs.inventory.remove() to consume quest items
-- 4. Container loot: ecs.container.get_state() + ecs.inventory.add()
-- 5. Event-driven: ecs.send_event() + ecs.subscribe_event() for quest flow
-- 6. Item lookup: ecs.items.find() for display names and metadata
-- =============================================================================

print("Quest reward examples completed successfully!")
