---@diagnostic disable: undefined-field, undefined-global
---@type string
local AddonName = ...
---@class Private
local Private = select(2, ...)
local wt = Private.Ace
---@class WTAPI
local WTAPI = WTAPI

-- Establishes the core Private.* state fields (version, active-instance/encounter-note
-- tables, comm-handler registry, CallbackHandler pub/sub host) that every later-loading
-- file in the bootstrap chain and beyond reads or extends.
--
-- Expected Private.* dependencies: only Private.Ace, created by WildThings.lua, which
-- loads immediately before this file per WildThings.toc -- Init.lua is otherwise the
-- FIRST file to populate Private.* state, so it has no other inbound dependency.
--
-- Timing: every statement below (Private.OurVersion, Private.activeInstances,
-- Private.commHandlers, Private.callbacks, etc.) runs at file-load time, NOT inside
-- wt:OnInitialize()/wt:OnEnable() -- these fields exist and are readable by any file
-- that loads AFTER Init.lua in the TOC. SavedVariables are NOT yet available at this
-- point (WildThingsSavedVars is only guaranteed populated from wt:OnInitialize()
-- onward, per WildThings.lua's EnsureSettings() call), so nothing here may read
-- WildThingsSavedVars.

-- Private.OurVersion is derived from the TOC's `## Version:` field, never hand-maintained.
-- The packager rewrites that field's `v4.0.1` placeholder to the release tag at
-- build time, so a packaged build reports its true version here and in every Lua error's
-- locals dump (this is what the Shell status bar shows too). It was hardcoded
-- until v4.0.0 and had gone stale at "v3.0.18", which made bug reports unattributable -- the
-- errors that exposed the packaging fault (.planning/debug/resolved/packaged-build-nil-calls.md)
-- all claimed to come from a release that predates the files in their own stack traces.
--
-- An unpackaged build (deploy.ps1 copies the TOC verbatim) still carries the literal
-- placeholder, which contains "@" and is not a version -- that case, and a nil/empty result
-- from a client without the metadata API, both fall back to "dev".
local tocVersion = C_AddOns and C_AddOns.GetAddOnMetadata
    and C_AddOns.GetAddOnMetadata(AddonName, "Version")
if type(tocVersion) ~= "string" or tocVersion == "" or tocVersion:find("@", 1, true) then
    tocVersion = "dev"
end
Private.OurVersion = tocVersion

Private.activeInstances = {}
Private.partyPoliceAvailable = true

-- Populated by RegisterCommEvent calls at file-load time (Core.lua, PartyMode.lua,
-- Versions.lua all load AFTER Init.lua per WildThings.toc, so this table+function
-- must exist before any of them run their top-level RegisterCommEvent calls).
-- The actual AceComm:RegisterComm("WT_MSG", ...) wiring stays in Transmission.lua's
-- Private:InitializeTransmission(), called from wt:OnInitialize() after all files load.
Private.commHandlers = {}
function Private:RegisterCommEvent(event, handler)
    Private.commHandlers[event] = handler
end

-- CallbackHandler-1.0 pub/sub host (HYGIENE-04). This milestone dedicates the
-- host to WT_ROSTER_CHANGED; it coexists with Private.NotifyProgressChanged
-- (the ad-hoc progress-bar hook), which stays untouched. CallbackHandler
-- stores one handler per registration "self" key, so every subscriber MUST
-- register using dot syntax with its own distinct string identity as the
-- first argument (e.g. Private.RegisterCallback("MyUniqueID", event, fn)) --
-- never colon syntax on Private itself, which would collapse every
-- subscriber onto the same key and silently drop all but the last one.
Private.callbacks = LibStub("CallbackHandler-1.0"):New(Private, "RegisterCallback", "UnregisterCallback")

function Private:FireCallback(event, ...)
    Private.callbacks:Fire(event, ...)
end

-- Takes a spell ID and returns an in-line icon string
Private.gsubIcon = function(spellID, width, height)
    spellID = tonumber(spellID)
    local info = C_Spell.GetSpellInfo(spellID)
    local spellTexture = info and info.originalIconID or "Interface\\Icons\\INV_MISC_QUESTIONMARK"

    return string.format("%s %s", CreateTextureMarkup(spellTexture, 64, 64, width, height, 5/64, 59/64, 5/60, 59/64, 0, 0), "")
end

-- NOTE (WR-05, pre-existing v1-era behavior, deliberately left unchanged):
-- for instance IDs 1861/2164 (undocumented -- believed to be a test/PTR
-- instance from early development), the addon only activates for a single
-- hardcoded developer battletag. Every other guild member gets `false`
-- (silent no-op, zero feedback) for those two specific instances.
-- This is surprising, single-developer-only gating left in shared code --
-- flagged by code review but NOT changed here; removing/relaxing it changes
-- who the addon works for, which is a product/user decision, not a code fix.
-- The comparison itself is fenced out of packaged builds so the battletag
-- (PII) never reaches a public release; the packaged build returns `false`
-- for 1861/2164, which is what every non-author client does anyway.
Private.CheckInstanceID = function(instanceID)
    if Private.activeInstances[instanceID] == nil then
      return false
    else
        if instanceID == 1861 or instanceID == 2164 then
            return false
        else
            return true
        end
    end
end

function WTAPI:ParseTooltipText(tooltipText)
    if tooltipText and tooltipText.lines and tooltipText.lines[2] and tooltipText.lines[2].leftText then
        tooltipText = tooltipText.lines[2].leftText
        local debuffType = "none";
        local tooltipSize = {};
        if(tooltipText) then
        for t in tooltipText:gmatch("(-?%d[%d%.,]*)") do
            if (LARGE_NUMBER_SEPERATOR == ",") then
            t = t:gsub(",", "");
            else
            t = t:gsub("%.", "");
            t = t:gsub(",", ".");
            end
            tinsert(tooltipSize, tonumber(t));
        end
        end

        if (#tooltipSize > 0) then
        return tooltipText, debuffType, unpack(tooltipSize);
        else
        return tooltipText, debuffType, 0;
        end
    end
end
