-- ============================================================================
-- HDG_PriceIntegration.lua - Price Addon Integration Module
-- ============================================================================
-- Handles integration with TSM and Auctionator for material pricing
-- ============================================================================

HDG_PriceIntegration = {}

-- ============================================================================
-- PRICE LOOKUP
-- ============================================================================

-- Lazy-built vendor price cache from ReagentsDB "Vendor:copper" entries
local vendorPriceCache

local function GetVendorPrice(itemID)
    if not vendorPriceCache then
        vendorPriceCache = {}
        if HDG_ReagentsDB then
            for id, src in pairs(HDG_ReagentsDB) do
                if type(src) == "string" then
                    local copper = src:match("^Vendor:(%d+)$")
                    if copper then vendorPriceCache[id] = tonumber(copper) end
                end
            end
        end
    end
    return vendorPriceCache[itemID]
end

-- Helper to check if TSM is available
local function IsTSMAvailable()
    return TSM_API and TSM_API.GetCustomPriceValue
end

-- Helper to check if Auctionator is available
local function IsAuctionatorAvailable()
    return Auctionator and Auctionator.API and Auctionator.API.v1 and Auctionator.API.v1.GetAuctionPriceByItemID
end

-- Helper to get price from TSM
local function GetTSMPrice(itemID)
    if not IsTSMAvailable() then return nil end
    local price = TSM_API.GetCustomPriceValue("DBMarket", "i:" .. itemID)
    if price and price > 0 then
        return price
    end
    return nil
end

-- Helper to get price from Auctionator
local function GetAuctionatorPrice(itemID)
    if not IsAuctionatorAvailable() then return nil end
    local price = Auctionator.API.v1.GetAuctionPriceByItemID("HousingDecorGuide", itemID)
    if price and price > 0 then
        return price
    end
    return nil
end

--- Get market price for an item from TSM or Auctionator
-- @param itemID The item ID to get price for
-- @param forceAddon Optional: force using specific addon ("TSM" or "Auctionator")
-- @return price (in copper), source ("TSM", "Auctionator", or nil)
function HDG_PriceIntegration.GetItemPrice(itemID, forceAddon)
    if not itemID then return nil, nil end

    -- Determine which addon to use
    local preferred = forceAddon or (HDG_Settings and HDG_Settings.preferredPriceAddon)

    -- If user has a preference, try only that addon
    if preferred == "TSM" then
        local price = GetTSMPrice(itemID)
        if price then return price, "TSM" end
    elseif preferred == "Auctionator" then
        local price = GetAuctionatorPrice(itemID)
        if price then return price, "Auctionator" end
    else
        -- Default: Try TSM first (more accurate market data), then Auctionator
        local price = GetTSMPrice(itemID)
        if price then return price, "TSM" end

        price = GetAuctionatorPrice(itemID)
        if price then return price, "Auctionator" end
    end

    -- Fallback: vendor price from ReagentsDB (always checked)
    local vendorPrice = GetVendorPrice(itemID)
    if vendorPrice then
        return vendorPrice, "Vendor"
    end

    return nil, nil
end

-- ============================================================================
-- FORMATTING
-- ============================================================================

--- Format copper value as gold string
-- @param copper Amount in copper
-- @param useTextures Whether to use coin textures (default false for compact display)
-- @return Formatted string
function HDG_PriceIntegration.FormatGold(copper, useTextures)
    if not copper or copper == 0 then return "0g" end

    if useTextures then
        return C_CurrencyInfo.GetCoinTextureString(copper)
    end

    local gold = math.floor(copper / 10000)
    local silver = math.floor((copper % 10000) / 100)

    if gold > 0 then
        if silver > 0 then
            return string.format("%d.%02dg", gold, silver)
        end
        return string.format("%dg", gold)
    elseif silver > 0 then
        return string.format("%ds", silver)
    else
        return string.format("%dc", copper % 100)
    end
end

--- Format copper value as gold-only with comma separators (e.g., "1,234g")
-- @param copper Amount in copper
-- @return Formatted string with commas, gold only
function HDG_PriceIntegration.FormatGoldOnly(copper)
    if not copper or copper == 0 then return "0g" end

    local gold = math.floor(copper / 10000)
    if _G.HDG_UIHelpers and _G.HDG_UIHelpers.FormatWithCommas then
        return _G.HDG_UIHelpers.FormatWithCommas(gold) .. "g"
    end
    return gold .. "g"
end

-- ============================================================================
-- ADDON DETECTION
-- ============================================================================

--- Check if any price addon is available
-- @return boolean, string (addon name or nil)
function HDG_PriceIntegration.HasPriceAddon()
    if IsTSMAvailable() then
        return true, "TSM"
    end
    if IsAuctionatorAvailable() then
        return true, "Auctionator"
    end
    return false, nil
end

--- Check if TSM is available
-- @return boolean
function HDG_PriceIntegration.IsTSMAvailable()
    return IsTSMAvailable()
end

--- Check if Auctionator is available
-- @return boolean
function HDG_PriceIntegration.IsAuctionatorAvailable()
    return IsAuctionatorAvailable()
end

--- Get list of available price addons
-- @return table of addon names (e.g., {"TSM", "Auctionator"} or {"TSM"} or {})
function HDG_PriceIntegration.GetAvailableAddons()
    local addons = {}
    if IsTSMAvailable() then
        table.insert(addons, "TSM")
    end
    if IsAuctionatorAvailable() then
        table.insert(addons, "Auctionator")
    end
    return addons
end

--- Get the name of the active price addon
-- @return string or nil
function HDG_PriceIntegration.GetActiveAddon()
    local hasAddon, addonName = HDG_PriceIntegration.HasPriceAddon()
    return hasAddon and addonName or nil
end

-- ============================================================================
-- TSM-SPECIFIC DATA
-- ============================================================================

--- Get TSM region sale average price
-- @param itemID The item ID to get region sale average for
-- @return price (in copper) or nil
function HDG_PriceIntegration.GetRegionSaleAvg(itemID)
    if not IsTSMAvailable() or not itemID then return nil end

    local price = TSM_API.GetCustomPriceValue("DBRegionSaleAvg", "i:" .. itemID)
    if price and price > 0 then
        return price
    end
    return nil
end

-- ============================================================================
-- BULK PRICING
-- ============================================================================

--- Calculate total price for a list of materials
-- @param materials Table of {itemID, amount} pairs
-- @return totalPrice (copper), itemsWithPrice (count), itemsWithoutPrice (count)
function HDG_PriceIntegration.CalculateTotalPrice(materials)
    local totalPrice = 0
    local itemsWithPrice = 0
    local itemsWithoutPrice = 0

    for _, mat in ipairs(materials) do
        local price, _ = HDG_PriceIntegration.GetItemPrice(mat.id or mat.itemID)
        local amount = mat.amount or mat.qty or 1

        if price then
            totalPrice = totalPrice + (price * amount)
            itemsWithPrice = itemsWithPrice + 1
        else
            itemsWithoutPrice = itemsWithoutPrice + 1
        end
    end

    return totalPrice, itemsWithPrice, itemsWithoutPrice
end
