---@class AddonPrivate
local Private = select(2, ...)

---@class Commands
local commands = {}
Private.Commands = commands

local const = Private.constants

function commands:AddCommand(cmdName, cmdFunc)
    local addon = Private.Addon
    addon:RegisterChatCommand(cmdName, function(...) cmdFunc(self, ...) end)
end

function commands:InitCommands()
    self:AddCommand("drustminimap", self.DrustMinimap)
    self:AddCommand("drustui", self.DrustUI)
    self:AddCommand("drusthud", self.DrustHud)
    self:AddCommand("drustroute", self.DrustRoute)
    self:AddCommand("drustdebugdungeon", self.DrustDebugDungeon)
    self:AddCommand("drustdebugwq", self.DrustDebugWQ)
    self:AddCommand("drustexportnotes", self.DrustExportNotes)
    self:AddCommand("drustreward", self.DrustReward)
    self:AddCommand("drustrewarddemo", self.DrustRewardDemo)
    self:AddCommand("drustrares", self.DrustRares)
    self:AddCommand("drusttheater", self.DrustTheater)
    self:AddCommand("drusttheaterdebug", self.DrustTheaterDebug)
    self:AddCommand("drustwhatsnew", self.DrustWhatsNew)
    self:AddCommand("drustdebug", self.DrustDebug)
end

function commands:DrustWhatsNew()
    if Private.WhatsNew then Private.WhatsNew:Show() end
    if Private.RouteHud then Private.RouteHud:ShowPreview() end
end

function commands:DrustTheater()
    if Private.TheaterTroupe then Private.TheaterTroupe:Print() end
end

function commands:DrustTheaterDebug()
    if Private.TheaterTroupe then Private.TheaterTroupe:Debug() end
end

function commands:DrustRares(input)
    local addon = Private.Addon
    if not Private.RareAlerts then return end
    input = (input or ""):lower():gsub("%s+", "")
    local s = Private.Settings:Rares()
    if input == "relevant" then
        s.onlyRelevant = not s.onlyRelevant
        Private.RareAlerts:UpdateFilterLabel()
        Private.RareAlerts:Refresh()
        addon:Print(s.onlyRelevant and "Rare alerts: showing |cff00ff00only meta-relevant|r rares."
            or "Rare alerts: showing |cff00ff00all|r nearby rares.")
        return
    end
    Private.RareAlerts:Toggle()
    if Private.RareAlerts:IsEnabled() then
        addon:Print("Rare alerts |cff00ff00enabled|r. Popup shows nearby rares; click Track to set a waypoint. (/drustrares relevant to filter to meta rares.)")
    else
        addon:Print("Rare alerts |cffff0000disabled|r.")
    end
end

function commands:DrustRewardDemo()
    if Private.RewardPreview then Private.RewardPreview:ShowDemo() end
end

function commands:DrustReward()
    local addon = Private.Addon
    if not Private.RewardPreview then return end
    Private.RewardPreview:Toggle()
    if Private.RewardPreview:IsEnabled() then
        addon:Print("Reward model preview |cff00ff00enabled|r. Click an achievement (with reward data) to preview it.")
    else
        addon:Print("Reward model preview |cffff0000disabled|r.")
    end
end

function commands:DrustExportNotes()
    local addon = Private.Addon
    if not (Private.RouteHud and Private.RouteHud.ExportNotes) then
        addon:Print("|cffff0000Notes export unavailable — the game is running an OLD copy of the addon. Re-copy the files.|r")
        return
    end
    if not Private.RouteHud.frame then Private.RouteHud:Initialize() end
    local count = Private.RouteHud:ExportNotes()
    addon:Print(string.format("Exported |cff00ff00%d|r waypoint note(s). Ctrl+A, Ctrl+C to copy the block.", count))
end

function commands:DrustDebugWQ()
    local addon = Private.Addon
    if not (Private.Objectives and Private.Objectives.GetWorldQuests) then
        addon:Print("|cffff0000Objectives:GetWorldQuests is MISSING — the game is running an OLD copy of the addon (not the edited files). Check your AddOns folder / re-copy.|r")
        return
    end
    local mapID = C_Map.GetBestMapForUnit("player")
    local hasAPI = Private.Objectives:HasWorldQuestAPI()
    local wqs = Private.Objectives:GetWorldQuests(mapID)
    addon:Print(string.format("WQ debug: new code LOADED. mapID=%s, C_TaskQuest API=%s, found |cff00ff00%d|r world quests nearby.",
        tostring(mapID), tostring(hasAPI), #wqs))
    for i = 1, math.min(#wqs, 5) do
        local q = wqs[i]
        addon:Print(string.format("  - %s |cff888888(%s)|r %s", q.title, q.mapName or "?",
            Private.Objectives:FormatTimeLeft(Private.Objectives:GetQuestTimeLeft(q.questID))))
    end
    addon:Print("RouteHud loaded: " .. tostring(Private.RouteHud ~= nil) .. ", crazy-arrow WaypointsUtil:TrackPoint = " .. tostring(Private.WaypointsUtil and Private.WaypointsUtil.TrackPoint ~= nil))
end

function commands:DrustDebugDungeon()
    local on = Private.Objectives:ToggleDebugDungeon()
    Private.Objectives:InvalidateSummaries()
    if Private.NearbyHud then Private.NearbyHud:Refresh() end
    if Private.RouteHud then Private.RouteHud:Refresh() end
    if on then
        Private.Addon:Print("Debug dungeon injected at your position (Algeth'ar Academy). Open the windows to test the Find Group button. Run /drustdebugdungeon again to remove.")
    else
        Private.Addon:Print("Debug dungeon removed.")
    end
end

function commands:DrustRoute()
    Private.RouteHud:Toggle()
    local addon = Private.Addon
    if Private.RouteHud:IsEnabled() then
        addon:Print("Do-it-now Route shown. Click a step to route to it; /drustroute to hide.")
    else
        addon:Print("Do-it-now Route hidden.")
    end
end

function commands:DrustHud()
    Private.NearbyHud:Toggle()
    local addon = Private.Addon
    if Private.NearbyHud:IsEnabled() then
        addon:Print("Nearby Now HUD shown. Drag to move; /drusthud to hide.")
    else
        addon:Print("Nearby Now HUD hidden.")
    end
end

function commands:DrustMinimap()
    local addon = Private.Addon
    addon.DB.minimap.hide = not addon.DB.minimap.hide
    if addon.DB.minimap.hide then
        Private.MinimapButton:GetIcon():Hide(const.ADDON_NAME)
        addon:Print("Minimap icon hidden.")
    else
        Private.MinimapButton:GetIcon():Show(const.ADDON_NAME)
        addon:Print("Minimap icon shown.")
    end
end

function commands:DrustUI()
    Private.UI:ToggleUI()
end

function commands:DrustDebug(input)
    local achievementID = tonumber(input)
    if not achievementID then
        print("Error: Please provide a valid achievement ID. Example: /drustdebug 41205")
        return
    end

    -- Function to search for the achievement ID in a given table
    local function FindAchievementByID(partsTable, id)
        if not partsTable or type(partsTable) ~= "table" then
            return nil
        end

        for _, achievement in ipairs(partsTable) do
            if achievement.achievementID == id then
                return achievement
            end
        end
        return nil
    end

    -- Search in DrustWaypointsPart1
    local foundInPart1 = FindAchievementByID(DrustWaypointsPart1, achievementID)
    if foundInPart1 then
        print(string.format("Achievement found in DrustWaypointsPart1: %s (ID: %d)", foundInPart1.name, foundInPart1.achievementID))
    else
        print("Achievement not found in DrustWaypointsPart1.")
    end

    -- Search in DrustWaypointsPart2
    local foundInPart2 = FindAchievementByID(DrustWaypointsPart2, achievementID)
    if foundInPart2 then
        print(string.format("Achievement found in DrustWaypointsPart2: %s (ID: %d)", foundInPart2.name, foundInPart2.achievementID))
    else
        print("Achievement not found in DrustWaypointsPart2.")
    end

    -- Combine results
    if not foundInPart1 and not foundInPart2 then
        print(string.format("Achievement ID %d not found in any Waypoints data.", achievementID))
    end
end