-- Portal Authority — core/commands.lua
-- Slash commands, settings opening/coexistence, and lock-state orchestration.
--
-- Depends on: prior core public methods; PortalAuthority.CoreInternal helpers
-- Exposes:    OpenSettings, OpenCustomSettingsSection*, SetGlobalLockState, slash handlers
-- DB keys:    lock-state keys via public APIs; PortalAuthorityCharacterDB._devLocaleOverride via dev-only slash path
-- Events:     none
-- Search key: none

local ADDON_NAME = ...

PortalAuthority = PortalAuthority or {}
PortalAuthority.CoreInternal = PortalAuthority.CoreInternal or {}
local CoreInternal = PortalAuthority.CoreInternal
local L = PortalAuthority.L

local PA_IsUiSurfaceGateEnabled = CoreInternal.PA_IsUiSurfaceGateEnabled
local PA_IsStaticBaselineGateEnabled = CoreInternal.PA_IsStaticBaselineGateEnabled
local PA_IsSettingsBaselineGateEnabled = CoreInternal.PA_IsSettingsBaselineGateEnabled
local PA_IsSettingsEagerBuildGateEnabled = CoreInternal.PA_IsSettingsEagerBuildGateEnabled
local PA_IsSettingsDirectBuildGateEnabled = CoreInternal.PA_IsSettingsDirectBuildGateEnabled
local PA_IsSettingsWindowHostEnabled = CoreInternal.PA_IsSettingsWindowHostEnabled
local PA_IsSettingsWindowDevGateEnabled = CoreInternal.PA_IsSettingsWindowDevGateEnabled
local PA_IsSettingsWindowPublicGateEnabled = CoreInternal.PA_IsSettingsWindowPublicGateEnabled
local PA_IsLocaleDevGateEnabled = CoreInternal.PA_IsLocaleDevGateEnabled
local PA_IsOnboardingD1DevGateEnabled = CoreInternal.PA_IsOnboardingD1DevGateEnabled
local PA_IsOnboardingD3DevGateEnabled = CoreInternal.PA_IsOnboardingD3DevGateEnabled
local PA_IsOnboardingD4DevGateEnabled = CoreInternal.PA_IsOnboardingD4DevGateEnabled
local PA_IsOnboardingD3PublicGateEnabled = CoreInternal.PA_IsOnboardingD3PublicGateEnabled
local PA_IsOnboardingD4PublicGateEnabled = CoreInternal.PA_IsOnboardingD4PublicGateEnabled
local PA_IsOnboardingQualifyingUpgradePublicGateEnabled = CoreInternal.PA_IsOnboardingQualifyingUpgradePublicGateEnabled
local PA_IsOnboardingD3Enabled = CoreInternal.PA_IsOnboardingD3Enabled
local PA_IsOnboardingD4Enabled = CoreInternal.PA_IsOnboardingD4Enabled
local trim = CoreInternal.trim
local clampNumber = CoreInternal.clampNumber
local PA_Clamp = CoreInternal.PA_Clamp
local PA_ToNumber = CoreInternal.PA_ToNumber
local PA_SafeBool = CoreInternal.PA_SafeBool
local PA_CompareSemver = CoreInternal.PA_CompareSemver
local PA_IsSemverStringValid = CoreInternal.PA_IsSemverStringValid
local PA_GetCurrentAddonVersionState = CoreInternal.PA_GetCurrentAddonVersionState
local VALID_OUTLINES = CoreInternal.VALID_OUTLINES
local VALID_SOUND_CHANNELS = CoreInternal.VALID_SOUND_CHANNELS
local BUILTIN_FONT_FALLBACK = CoreInternal.BUILTIN_FONT_FALLBACK
local PLAYER_LOGIN_MESSAGE = CoreInternal.PLAYER_LOGIN_MESSAGE
local DOCK_ENABLE_DEFAULTS_VERSION = CoreInternal.DOCK_ENABLE_DEFAULTS_VERSION
local PA_PrintPortalAuthorityMessage = CoreInternal.PA_PrintPortalAuthorityMessage
local PA_MaybeShowMPlusNotice = CoreInternal.PA_MaybeShowMPlusNotice
local ResetMPlusNoticeShown = CoreInternal.ResetMPlusNoticeShown
local PA_IsSecretValue = CoreInternal.PA_IsSecretValue
local PA_NormalizeSafeString = CoreInternal.PA_NormalizeSafeString
local PA_NormalizeSupportedLocaleCode = CoreInternal.PA_NormalizeSupportedLocaleCode
local PA_SafeStringsEqual = CoreInternal.PA_SafeStringsEqual
local PA_SafeUnitGUID = CoreInternal.PA_SafeUnitGUID

local PA_LOCALE_COMMAND_USAGE = "usage: /pa locale status|reset|<enUS|deDE|esES|esMX|frFR|itIT|koKR|ptBR|ruRU|zhCN|zhTW>"

local function PA_GetLocaleDevCharacterStore()
    if not PortalAuthority or type(PortalAuthority.GetProfilesCharacterStore) ~= "function" then
        return nil
    end
    local ok, charStore = pcall(PortalAuthority.GetProfilesCharacterStore, PortalAuthority)
    if ok and type(charStore) == "table" then
        return charStore
    end
    return nil
end

local function PA_GetEffectiveAddonLocale()
    local activeLocale = PortalAuthority and PortalAuthority._activeLocaleCode or nil
    if activeLocale then
        return activeLocale
    end
    local clientLocale = type(GetLocale) == "function" and GetLocale() or nil
    return PA_NormalizeSupportedLocaleCode(clientLocale) or "enUS"
end

local function PA_GetStoredLocaleOverride()
    local charStore = PA_GetLocaleDevCharacterStore()
    local storedOverride = charStore and charStore._devLocaleOverride or nil
    return PA_NormalizeSupportedLocaleCode and PA_NormalizeSupportedLocaleCode(storedOverride) or nil
end

function PortalAuthority:ShowLoginMessage()
    local chatFrame = DEFAULT_CHAT_FRAME or ChatFrame1
    if not chatFrame or not chatFrame.AddMessage then
        return
    end

    local addonName = "|cffE88BC7Portal Authority|r"
    local loginMessage = L["RUNTIME_LOGIN_MESSAGE"] or PLAYER_LOGIN_MESSAGE or "- type /pa to open settings."
    chatFrame:AddMessage(string.format("%s %s", addonName, loginMessage))
end

function PortalAuthority:CloseCustomSettingsWindowForBlizzardOpen()
    if not PortalAuthority
        or not PortalAuthority.IsSettingsWindowHostEnabled
        or not PortalAuthority:IsSettingsWindowHostEnabled()
        or not PortalAuthority.GetExistingSettingsWindowFrame
    then
        return
    end

    local frame = PortalAuthority:GetExistingSettingsWindowFrame()
    if not frame or not frame.IsShown or not frame:IsShown() then
        return
    end

    if PortalAuthority.CloseSettingsWindow then
        PortalAuthority:CloseSettingsWindow()
    end

    frame = PortalAuthority:GetExistingSettingsWindowFrame()
    if frame and frame.IsShown and frame:IsShown() and frame.Hide then
        frame:Hide()
    end
end

function PortalAuthority:TryHookSettingsPanelCoexistence()
    local self = self or PortalAuthority
    if self._settingsWindowCoexistencePanelHooked then
        return true
    end

    local settingsPanel = self:CpuDiagGetSettingsPanelFrame()
    if not settingsPanel or not settingsPanel.HookScript then
        return false
    end
    if settingsPanel._paSettingsWindowCoexistenceHooked then
        self._settingsWindowCoexistencePanelHooked = true
        return true
    end

    settingsPanel:HookScript("OnShow", function()
        if PortalAuthority and PortalAuthority.CloseCustomSettingsWindowForBlizzardOpen then
            PortalAuthority:CloseCustomSettingsWindowForBlizzardOpen()
        end
    end)
    settingsPanel._paSettingsWindowCoexistenceHooked = true
    self._settingsWindowCoexistencePanelHooked = true
    return true
end

function PortalAuthority:EnsureSettingsHostCoexistenceHooks()
    local installed = false

    if not self._settingsWindowCoexistenceMethodsHooked
        and type(hooksecurefunc) == "function"
        and Settings
    then
        local hookedAnyMethod = false
        local openHookMethods = {
            "Open",
            "OpenToCategory",
            "OpenToCategoryID",
        }
        for i = 1, #openHookMethods do
            local methodName = openHookMethods[i]
            if type(Settings[methodName]) == "function" then
                hooksecurefunc(Settings, methodName, function()
                    if PortalAuthority and PortalAuthority.CloseCustomSettingsWindowForBlizzardOpen then
                        PortalAuthority:CloseCustomSettingsWindowForBlizzardOpen()
                    end
                end)
                hookedAnyMethod = true
            end
        end
        if hookedAnyMethod then
            self._settingsWindowCoexistenceMethodsHooked = true
            installed = true
        end
    elseif self._settingsWindowCoexistenceMethodsHooked then
        installed = true
    end

    if self:TryHookSettingsPanelCoexistence() then
        installed = true
    end

    self._settingsWindowCoexistenceHooksInstalled = installed
    return installed
end

function PortalAuthority:ResolveSettingsSectionKeyFromCategoryID(categoryID)
    if categoryID == nil then
        return "announcements"
    end
    if type(categoryID) ~= "number" then
        return nil
    end

    if type(self.rootCategoryID) == "number" and categoryID == self.rootCategoryID then
        return "root"
    end

    return nil
end

function PortalAuthority:ReadSettingsWindowOpenError(fallback)
    local runtime = self and self._settingsWindowRuntime or nil
    local message = runtime and runtime.lastError or nil
    if type(message) == "string" and message ~= "" then
        return message
    end
    return fallback or L["SETTINGS_WINDOW_HOST_UNAVAILABLE"]
end

function PortalAuthority:OpenCustomSettingsSection(sectionKey, source, opts)
    if type(self.OpenSettingsWindow) ~= "function" then
        return false, L["SETTINGS_WINDOW_HOST_UNAVAILABLE"]
    end

    local openOpts = type(opts) == "table" and opts or {}
    openOpts.source = source or openOpts.source or "open-settings"
    openOpts.targeted = true

    local ok, result = pcall(self.OpenSettingsWindow, self, sectionKey, openOpts)
    if ok and result ~= false then
        return true
    end
    if not ok then
        return false, tostring(result or L["SETTINGS_WINDOW_HOST_UNAVAILABLE"])
    end
    return false, self:ReadSettingsWindowOpenError(L["SETTINGS_WINDOW_HOST_UNAVAILABLE"])
end

function PortalAuthority:OpenCustomSettingsSectionOrRoot(sectionKey, source, opts)
    if self.IsSettingsWindowHostEnabled and self:IsSettingsWindowHostEnabled() then
        return self:OpenCustomSettingsSection(sectionKey, source, opts)
    end
    return self:OpenSettings(self.rootCategoryID)
end
function PortalAuthority:OpenSettings(categoryID)
    if PA_IsSettingsBaselineGateEnabled() then
        PA_PrintPortalAuthorityMessage(L["RUNTIME_COMMANDS_SETTINGS_DISABLED_BASELINE"])
        return false, L["SETTINGS_WINDOW_UNAVAILABLE_BUILD"]
    end
    self:CpuDiagEnsureSettingsHooks()
    if self.EnsureSettingsHostCoexistenceHooks then
        self:EnsureSettingsHostCoexistenceHooks()
    end

    local function canOpenSettingsNow()
        local inCombat = (InCombatLockdown and InCombatLockdown()) or false
        if inCombat or (self.IsPlayerInCombat and self:IsPlayerInCombat()) then
            return false, L["SETTINGS_WINDOW_UNAVAILABLE_COMBAT"]
        end
        return true, nil
    end

    local safeToOpen, safeErr = canOpenSettingsNow()
    if not safeToOpen then
        return false, safeErr
    end

    local sectionKey = self:ResolveSettingsSectionKeyFromCategoryID(categoryID)
    if self.IsSettingsWindowHostEnabled and self:IsSettingsWindowHostEnabled() then
        if sectionKey then
            return self:OpenCustomSettingsSection(sectionKey, "open-settings")
        end

        local customFrame = self.GetExistingSettingsWindowFrame and self:GetExistingSettingsWindowFrame() or nil
        if customFrame and customFrame.IsShown and customFrame:IsShown() then
            if self.CloseSettingsWindow then
                self:CloseSettingsWindow()
            end
            customFrame = self.GetExistingSettingsWindowFrame and self:GetExistingSettingsWindowFrame() or customFrame
            if customFrame and customFrame.IsShown and customFrame:IsShown() and customFrame.Hide then
                customFrame:Hide()
            end
        end
    end

    if type(categoryID) == "number" and not sectionKey then
        categoryID = self.rootCategoryID
    end

    if not Settings then
        return false, "Settings are unavailable."
    end

    local id = categoryID or self.defaultCategoryID or self.rootCategoryID
    if type(id) ~= "number" then
        local category = self.settingsCategory
        if category and category.GetID then
            id = category:GetID()
        end
    end

    if type(id) == "number" then
        local function openCategoryOnce()
            local okToOpen = canOpenSettingsNow()
            if not okToOpen then
                return false
            end
            if Settings.OpenToCategoryID then
                Settings.OpenToCategoryID(id)
                return true
            end
            if Settings.OpenToCategory then
                Settings.OpenToCategory(id)
                return true
            end
            return false
        end

        if openCategoryOnce() then
            if C_Timer and C_Timer.After then
                C_Timer.After(0, function()
                    openCategoryOnce()
                    if PortalAuthority and PortalAuthority.CpuDiagEnsureSettingsHooks then
                        PortalAuthority:CpuDiagEnsureSettingsHooks()
                    end
                end)
            end
            self:CpuDiagEnsureSettingsHooks()
            return true
        end
    end

    print("|cffE88BC7PortalAuthority:|r could not open settings (category ID missing)")
    return false, "Settings are unavailable."
end

local PA_DIAG_WALK_ORDER = {
    "root",
    "announcements",
    "dock",
    "timers",
    "interrupt",
    "combat",
    "keystone",
    "profiles",
}

local PA_DIAG_PANEL_SETTLE_DELAY = 0.08
local PA_DIAG_PANEL_RETRY_DELAY = 0.08
local PA_DIAG_PANEL_MAX_ATTEMPTS = 2
local PA_TOOLTIP_DIAG_ARM_TIMEOUT_SECONDS = 60
local PA_TOOLTIP_DIAG_CAPTURE_DURATION_SECONDS = 5
local PA_TOOLTIP_DIAG_SAMPLE_INTERVAL_SECONDS = 0.1
local PA_TOOLTIP_DIAG_EVENT_CAPACITY = 64
local PA_TOOLTIP_DIAG_STACK_MAX_LINES = 8
local PA_TOOLTIP_DIAG_STACK_MAX_CHARS = 700

function PortalAuthority:SetGlobalLockState(locked)
    self:EnsureDB()
    local db = PortalAuthorityDB
    if not db then
        return false
    end

    locked = not not locked
    local desiredUnlocked = not locked
    local priorDeferredSharedRefresh = self._deferSharedMarkerTickerRefresh and true or false

    -- 1) Mythic+ Dock
    db.dockLocked = locked

    -- 2) Combat Alerts (On-screen Alerts anchor)
    db.deathAlertLocked = locked

    -- 3) Timers
    db.modules = db.modules or {}
    db.modules.timers = db.modules.timers or {}
    db.modules.timers.locked = locked

    -- 4) Interrupt Tracker
    db.modules.interruptTracker = db.modules.interruptTracker or {}
    db.modules.interruptTracker.locked = locked

    self._deferSharedMarkerTickerRefresh = true

    local modulesApi = self.Modules
    if modulesApi and modulesApi.SetUnlocked then
        modulesApi:SetUnlocked(desiredUnlocked)
    end

    local timersModule = modulesApi and modulesApi.registry and modulesApi.registry.timers or nil
    if timersModule then
        local timersEnabled = timersModule.IsEnabled and timersModule:IsEnabled()
        if desiredUnlocked and timersEnabled and timersModule.Initialize and not (timersModule.frame or timersModule.mainFrame) then
            timersModule:Initialize()
        end
        if timersModule.ApplyPosition then
            timersModule:ApplyPosition()
        end
        if timersModule.EvaluateVisibility and (timersModule.frame or timersModule.mainFrame) then
            timersModule:EvaluateVisibility("slash-global-lock-toggle")
        end
        if desiredUnlocked and timersModule.Tick then
            timersModule:Tick()
        end
    end

    if modulesApi and modulesApi.NotifyPositionChanged then
        local tdb = db.modules and db.modules.timers or nil
        if tdb then
            modulesApi:NotifyPositionChanged(
                "timers",
                math.floor(tonumber(tdb.x) or 0),
                math.floor(tonumber(tdb.y) or 0)
            )
        end
        local idb = db.modules and db.modules.interruptTracker or nil
        if idb then
            modulesApi:NotifyPositionChanged(
                "interruptTracker",
                math.floor(tonumber(idb.x) or 0),
                math.floor(tonumber(idb.y) or 0)
            )
        end
    end

    local interruptModule = modulesApi and modulesApi.registry and modulesApi.registry.interruptTracker or nil
    if interruptModule then
        local interruptEnabled = interruptModule.IsEnabled and interruptModule:IsEnabled()
        if desiredUnlocked and interruptEnabled and interruptModule.Initialize and not interruptModule.frame then
            interruptModule:Initialize()
        end
        if interruptModule.ApplyPosition then
            interruptModule:ApplyPosition()
        end
        if interruptModule.EvaluateVisibility then
            interruptModule:EvaluateVisibility("slash-global-lock-toggle")
        end
    end

    if self.UpdateDockMovableState then
        self:UpdateDockMovableState()
    else
        if self.ApplyDockPosition then
            self:ApplyDockPosition()
        end
        if self.UpdateDockVisibility then
            self:UpdateDockVisibility(true)
        elseif self.RefreshDockVisibility then
            self:RefreshDockVisibility(true)
        end
    end
    if self.ApplyDockCombatVisibilityDriver then
        self:ApplyDockCombatVisibilityDriver()
    end

    if self.ApplyCombatAlertsSettings then
        self:ApplyCombatAlertsSettings()
    end

    if self.RefreshOptionsPanels then
        self:RefreshOptionsPanels()
    end

    self._deferSharedMarkerTickerRefresh = priorDeferredSharedRefresh and true or nil
    if not priorDeferredSharedRefresh then
        self:UpdateMoveHintTickerState()
    end

    return locked
end

SLASH_PORTALAUTHORITY1 = "/pa"
local function PA_HandlePullSlash(msg)
    local seconds = PortalAuthority:KeystoneUtility_GetPullSeconds(false)
    local raw = trim(msg)
    if raw ~= "" then
        local maybe = tonumber(raw)
        if maybe then
            seconds = math.floor(PA_Clamp(maybe, seconds, 1, 60))
        end
    end
    PortalAuthority:KeystoneUtility_StartPull(seconds)
end

SlashCmdList.PORTALAUTHORITY = function(msg)
    local rawCommand = trim(msg)
    local command = rawCommand:lower()
    local pullArg = command:match("^pull%s*(.*)$")
    if pullArg ~= nil then
        PA_HandlePullSlash(pullArg)
        return
    end

    local diagDumpArg = command:match("^diagdump%s*(.*)$")
    if diagDumpArg ~= nil then
        PortalAuthority:StartDiagDump(trim(diagDumpArg))
        return
    end

    local devSettingsArg = command:match("^devsettings%s*(.*)$")
    if devSettingsArg ~= nil then
        if not (PortalAuthority.IsSettingsWindowDevGateEnabled and PortalAuthority:IsSettingsWindowDevGateEnabled()) then
            PA_PrintPortalAuthorityMessage("Settings window dev commands are unavailable in this build.")
            return
        end

        devSettingsArg = trim(devSettingsArg)
        if devSettingsArg == "" then
            local ok = PortalAuthority.OpenSettingsWindow and PortalAuthority:OpenSettingsWindow(nil, { source = "slash-devsettings" }) or false
            if not ok then
                local runtime = PortalAuthority._settingsWindowRuntime
                PA_PrintPortalAuthorityMessage((runtime and runtime.lastError) or "Settings window is unavailable.")
            end
            return
        end

        local sectionKey = PortalAuthority.NormalizeSettingsWindowSectionKey and PortalAuthority:NormalizeSettingsWindowSectionKey(devSettingsArg) or nil
        if not sectionKey then
            PA_PrintPortalAuthorityMessage("usage: /pa devsettings [root|home|announcements|dock|timers|interrupt|combat|keystone|profiles]")
            return
        end

        local ok = PortalAuthority.OpenSettingsWindowToSection and PortalAuthority:OpenSettingsWindowToSection(sectionKey) or false
        if not ok then
            local runtime = PortalAuthority._settingsWindowRuntime
            PA_PrintPortalAuthorityMessage((runtime and runtime.lastError) or "Settings window is unavailable.")
        end
        return
    end

    local localeArg = rawCommand:match("^[Ll][Oo][Cc][Aa][Ll][Ee]%s*(.*)$")
    if localeArg ~= nil then
        if not (PA_IsLocaleDevGateEnabled and PA_IsLocaleDevGateEnabled()) then
            PA_PrintPortalAuthorityMessage("Locale dev commands are unavailable in this build.")
            return
        end

        localeArg = trim(localeArg)
        local localeCommand = localeArg:lower()
        local clientLocale = type(GetLocale) == "function" and tostring(GetLocale() or "") or ""
        local storedOverride = PA_GetStoredLocaleOverride() or (PortalAuthority and PortalAuthority._devLocaleOverride or nil)
        local effectiveLocale = PA_GetEffectiveAddonLocale()

        if localeArg == "" or localeCommand == "status" then
            PA_PrintPortalAuthorityMessage(
                string.format(
                    "Locale override: %s. Effective addon locale: %s. Client locale: %s.",
                    storedOverride or "none",
                    effectiveLocale,
                    clientLocale ~= "" and clientLocale or "unknown"
                )
            )
            return
        end

        local charStore = PA_GetLocaleDevCharacterStore()
        if not charStore then
            PA_PrintPortalAuthorityMessage("Locale override storage is unavailable.")
            return
        end

        if localeCommand == "reset" then
            charStore._devLocaleOverride = nil
            PortalAuthority._devLocaleOverride = nil
            PA_PrintPortalAuthorityMessage("Locale override reset. Type /reload to apply.")
            return
        end

        local normalizedLocale = PA_NormalizeSupportedLocaleCode and PA_NormalizeSupportedLocaleCode(localeArg) or nil
        if not normalizedLocale then
            PA_PrintPortalAuthorityMessage(PA_LOCALE_COMMAND_USAGE)
            return
        end

        charStore._devLocaleOverride = normalizedLocale
        PortalAuthority._devLocaleOverride = normalizedLocale
        PA_PrintPortalAuthorityMessage(string.format("Locale override set to %s. Type /reload to apply.", normalizedLocale))
        return
    end

    local perfArg = command:match("^perf%s*(.*)$")
    if perfArg ~= nil then
        perfArg = trim(perfArg)
        if perfArg == "on" then
            PortalAuthority._perf = PortalAuthority._perf or {}
            PortalAuthority._perf.enabled = true
            PortalAuthority:PerfReset()
            print("|cffffd100Portal Authority Perf:|r enabled and reset.")
            return
        end
        if perfArg == "off" then
            PortalAuthority._perf = PortalAuthority._perf or {}
            PortalAuthority._perf.enabled = false
            print("|cffffd100Portal Authority Perf:|r disabled.")
            return
        end
        if perfArg == "reset" then
            PortalAuthority:PerfReset()
            print("|cffffd100Portal Authority Perf:|r stats reset.")
            return
        end
        if perfArg == "dump" or perfArg == "" then
            PortalAuthority:PerfDump()
            return
        end

        print("|cffffd100Portal Authority Perf:|r usage: /pa perf on|off|dump|reset")
        return
    end

    local summonDebugArg = command:match("^summondebug%s*(.*)$")
    if summonDebugArg ~= nil then
        summonDebugArg = trim(summonDebugArg)
        if summonDebugArg == "" or summonDebugArg == "on" then
            PortalAuthority.summonDebugEnabled = true
            print("|cffffd100Portal Authority:|r Summon debug enabled.")
            return
        end
        if summonDebugArg == "off" then
            PortalAuthority.summonDebugEnabled = false
            print("|cffffd100Portal Authority:|r Summon debug disabled.")
            return
        end
        print("|cffffd100Portal Authority:|r usage: /pa summondebug on|off")
        return
    end

    local dockDiagArg = command:match("^dockdiag%s*(.*)$")
    if dockDiagArg ~= nil then
        dockDiagArg = trim(dockDiagArg)
        if dockDiagArg == "" or dockDiagArg == "status" then
            if PortalAuthority.GetDockDiagStatusLines then
                for _, line in ipairs(PortalAuthority:GetDockDiagStatusLines() or {}) do
                    print(line)
                end
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "reset" then
            if PortalAuthority.ResetDockDiagOverrides then
                PortalAuthority:ResetDockDiagOverrides()
                print("|cffffd100Portal Authority:|r Dock diagnostics reset.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "labels off" then
            if PortalAuthority.SetDockDiagLabelMode then
                PortalAuthority:SetDockDiagLabelMode("OFF")
                print("|cffffd100Portal Authority:|r DockDiag labels override set to OFF.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "labels on" then
            if PortalAuthority.SetDockDiagLabelMode then
                PortalAuthority:SetDockDiagLabelMode("OUTSIDE")
                print("|cffffd100Portal Authority:|r DockDiag labels override set to OUTSIDE.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "labelrender normal" then
            if PortalAuthority.SetDockDiagLabelRenderMode then
                PortalAuthority:SetDockDiagLabelRenderMode("NORMAL")
                print("|cffffd100Portal Authority:|r DockDiag labelrender override set to NORMAL.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "labelrender blank" then
            if PortalAuthority.SetDockDiagLabelRenderMode then
                PortalAuthority:SetDockDiagLabelRenderMode("BLANK")
                print("|cffffd100Portal Authority:|r DockDiag labelrender override set to BLANK.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "labelrender plain" then
            if PortalAuthority.SetDockDiagLabelRenderMode then
                PortalAuthority:SetDockDiagLabelRenderMode("PLAIN")
                print("|cffffd100Portal Authority:|r DockDiag labelrender override set to PLAIN.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "visibility normal" then
            if PortalAuthority.SetDockDiagVisibilityMode then
                PortalAuthority:SetDockDiagVisibilityMode("NORMAL")
                print("|cffffd100Portal Authority:|r DockDiag visibility override set to NORMAL.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "visibility hide" then
            if PortalAuthority.SetDockDiagVisibilityMode then
                PortalAuthority:SetDockDiagVisibilityMode("HIDE")
                print("|cffffd100Portal Authority:|r DockDiag visibility override set to HIDE.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "sort type" then
            if PortalAuthority.SetDockDiagSortMode then
                PortalAuthority:SetDockDiagSortMode("TYPE_ID")
                print("|cffffd100Portal Authority:|r DockDiag sort override set to TYPE_ID.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "sort cooldown" then
            if PortalAuthority.SetDockDiagSortMode then
                PortalAuthority:SetDockDiagSortMode("COOLDOWN")
                print("|cffffd100Portal Authority:|r DockDiag sort override set to COOLDOWN.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end
        if dockDiagArg == "sort restore" then
            if PortalAuthority.SetDockDiagSortMode then
                PortalAuthority:SetDockDiagSortMode(nil)
                print("|cffffd100Portal Authority:|r DockDiag sort override cleared.")
            else
                print("|cffffd100Portal Authority:|r Dock diagnostics are unavailable.")
            end
            return
        end

        print("|cffffd100Portal Authority:|r usage: /pa dockdiag status|labels off|labels on|labelrender normal|labelrender blank|labelrender plain|visibility normal|visibility hide|sort type|sort cooldown|sort restore|reset")
        return
    end

    local cpuDiagArg = command:match("^cpudiag%s*(.*)$")
    if cpuDiagArg ~= nil then
        cpuDiagArg = trim(cpuDiagArg)
        if cpuDiagArg == "" or cpuDiagArg == "status" then
            if PortalAuthority.GetCpuDiagStatusLines then
                for _, line in ipairs(PortalAuthority:GetCpuDiagStatusLines() or {}) do
                    print(line)
                end
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end
        if cpuDiagArg == "reset" then
            if PA_IsStaticBaselineGateEnabled() then
                print("|cffffd100Portal Authority:|r CpuDiag witness is disabled in this build.")
                return
            end
            if PortalAuthority.ResetCpuDiag then
                PortalAuthority:ResetCpuDiag()
                print("|cffffd100Portal Authority:|r CPU diagnostics reset.")
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end
        if cpuDiagArg == "mark good" then
            if PA_IsStaticBaselineGateEnabled() then
                print("|cffffd100Portal Authority:|r CpuDiag witness is disabled in this build.")
                return
            end
            if PortalAuthority.CpuDiagAppendIdleWitnessEntry then
                PortalAuthority:CpuDiagScheduleIdleWitnessStart()
                if PortalAuthority:CpuDiagAppendIdleWitnessEntry({ "user_good" }, "good") then
                    print("|cffffd100Portal Authority:|r CpuDiag witness marked GOOD.")
                else
                    print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
                end
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end
        if cpuDiagArg == "mark bad" then
            if PA_IsStaticBaselineGateEnabled() then
                print("|cffffd100Portal Authority:|r CpuDiag witness is disabled in this build.")
                return
            end
            if PortalAuthority.CpuDiagAppendIdleWitnessEntry then
                PortalAuthority:CpuDiagScheduleIdleWitnessStart()
                if PortalAuthority:CpuDiagAppendIdleWitnessEntry({ "user_bad" }, "bad") then
                    print("|cffffd100Portal Authority:|r CpuDiag witness marked BAD.")
                else
                    print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
                end
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end
        if cpuDiagArg == "timers visibility normal" then
            if PortalAuthority.SetCpuDiagVisibilityMode and PortalAuthority:SetCpuDiagVisibilityMode("timers", "NORMAL") then
                print("|cffffd100Portal Authority:|r CpuDiag Timers visibility override set to NORMAL.")
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end
        if cpuDiagArg == "timers visibility hide" then
            if PortalAuthority.SetCpuDiagVisibilityMode and PortalAuthority:SetCpuDiagVisibilityMode("timers", "HIDE") then
                print("|cffffd100Portal Authority:|r CpuDiag Timers visibility override set to HIDE.")
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end
        if cpuDiagArg == "interrupt visibility normal" then
            if PortalAuthority.SetCpuDiagVisibilityMode and PortalAuthority:SetCpuDiagVisibilityMode("interrupt", "NORMAL") then
                print("|cffffd100Portal Authority:|r CpuDiag Interrupt visibility override set to NORMAL.")
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end
        if cpuDiagArg == "interrupt visibility hide" then
            if PortalAuthority.SetCpuDiagVisibilityMode and PortalAuthority:SetCpuDiagVisibilityMode("interrupt", "HIDE") then
                print("|cffffd100Portal Authority:|r CpuDiag Interrupt visibility override set to HIDE.")
            else
                print("|cffffd100Portal Authority:|r CPU diagnostics are unavailable.")
            end
            return
        end

        print("|cffffd100Portal Authority:|r usage: /pa cpudiag status|reset|mark good|mark bad|timers visibility normal|timers visibility hide|interrupt visibility normal|interrupt visibility hide")
        return
    end

    local onboardingD1Arg = command:match("^dev%s+onboarding%-d1%s*(.*)$")
    if onboardingD1Arg ~= nil then
        if not PA_IsOnboardingD1DevGateEnabled() then
            print("|cffffd100Portal Authority:|r Onboarding D1 dev commands are unavailable in this build.")
            return
        end

        onboardingD1Arg = trim(onboardingD1Arg)
        if onboardingD1Arg == "" or onboardingD1Arg == "help" then
            print("|cffffd100Portal Authority:|r usage: /pa dev onboarding-d1 first-install|qualifying-upgrade|normalize-active|clear-reset-state")
            return
        end

        if not PortalAuthority.Profiles_RunOnboardingD1Exercise then
            print("|cffffd100Portal Authority:|r Onboarding D1 exercise path is unavailable.")
            return
        end

        local ok, response, shouldReload = PortalAuthority:Profiles_RunOnboardingD1Exercise(onboardingD1Arg)
        print("|cffffd100Portal Authority:|r " .. tostring(response or (ok and "Completed." or "Failed.")))
        if ok and shouldReload then
            ReloadUI()
        end
        return
    end

    local onboardingD3Arg = command:match("^dev%s+onboarding%-d3%s*(.*)$")
    if onboardingD3Arg ~= nil then
        if not PA_IsOnboardingD3DevGateEnabled() then
            print("|cffffd100Portal Authority:|r Onboarding D3 dev commands are unavailable in this build.")
            return
        end
        PortalAuthority:HandleOnboardingD3Slash(onboardingD3Arg)
        return
    end

    local onboardingD4Arg = command:match("^dev%s+onboarding%-d4%s*(.*)$")
    if onboardingD4Arg ~= nil then
        if not PA_IsOnboardingD4DevGateEnabled() then
            print("|cffffd100Portal Authority:|r Onboarding D4 dev commands are unavailable in this build.")
            return
        end
        PortalAuthority:HandleOnboardingD4Slash(onboardingD4Arg)
        return
    end

    local s8DevArg = command:match("^dev%s+s8%s*(.*)$")
    if s8DevArg ~= nil then
        if not (PortalAuthority.IsSettingsWindowDevGateEnabled and PortalAuthority:IsSettingsWindowDevGateEnabled()) then
            print("|cffffd100Portal Authority:|r S8 announcement dev commands are unavailable in this build.")
            return
        end
        PortalAuthority:HandleS8AnnouncementSlash(s8DevArg)
        return
    end

    if rawCommand == "2.3.7" then
        local ok, err = PortalAuthority:ShowInterruptTrackerApiWarningPopup("slash-preview-2.3.7", {
            ignorePending = true,
            consumeOnAcknowledge = false,
        })
        if not ok and err then
            PA_PrintPortalAuthorityMessage(err)
        end
        return
    end

    if command == "onboarding" then
        if not PA_IsOnboardingD3Enabled() then
            print("|cffffd100Portal Authority:|r Premium onboarding is unavailable in this build.")
            return
        end
        local ok, response = PortalAuthority:StartExplicitPremiumOnboarding("slash-onboarding")
        PA_PrintPortalAuthorityMessage(response or (ok and "Premium onboarding opened." or "Premium onboarding failed."))
        return
    end

    if command == "updates" then
        local ok, err = PortalAuthority:HandleSlashUpdatesEntry()
        if not ok and err then
            print("|cffE88BC7Portal Authority:|r " .. tostring(err))
        end
        return
    end

    if command == "lock" then
        PortalAuthority:SetGlobalLockState(true)
        PA_PrintPortalAuthorityMessage(L["RUNTIME_COMMANDS_LOCK_ALL"])
        return
    end

    if command == "unlock" then
        PortalAuthority:SetGlobalLockState(false)
        PA_PrintPortalAuthorityMessage(L["RUNTIME_COMMANDS_UNLOCK_ALL"])
        return
    end

    if command == "who" then
        local modulesApi = PortalAuthority.Modules
        local interruptModule = modulesApi and modulesApi.registry and modulesApi.registry.interruptTracker or nil
        if not interruptModule or not interruptModule.GetWhoReportLines then
            PA_PrintPortalAuthorityMessage(L["RUNTIME_COMMANDS_INTERRUPT_TRACKER_UNAVAILABLE"])
            return
        end
        if interruptModule.Initialize then
            interruptModule:Initialize()
        end
        local lines, message = interruptModule:GetWhoReportLines()
        if message then
            print((tostring(message or "")):gsub("^Portal Authority:", "|cffE88BC7Portal Authority:|r", 1))
            return
        end
        for _, line in ipairs(lines or {}) do
            print("|cffE88BC7Portal Authority:|r " .. tostring(line))
        end
        return
    end

    if command == "dock" then
        PortalAuthorityDB.dockEnabled = not PortalAuthorityDB.dockEnabled
        if PortalAuthority.UpdateDockVisibility then
            PortalAuthority:UpdateDockVisibility(true)
        elseif PortalAuthority.RefreshDockVisibility then
            PortalAuthority:RefreshDockVisibility(true)
        end
        if PortalAuthority.RefreshOptionsPanels then
            PortalAuthority:RefreshOptionsPanels()
        end
        PA_PrintPortalAuthorityMessage(PortalAuthorityDB.dockEnabled and L["RUNTIME_COMMANDS_DOCK_ENABLED"] or L["RUNTIME_COMMANDS_DOCK_DISABLED"])
        return
    end

    if command == "debugdock" then
        if PortalAuthority.DebugDockBindingState then
            PortalAuthority:DebugDockBindingState()
        else
            PA_PrintPortalAuthorityMessage(L["RUNTIME_COMMANDS_DOCK_DEBUG_UNAVAILABLE"])
        end
        return
    end

    local ok, err = PortalAuthority:HandleSlashRootEntry()
    if ok == false and err then
        PA_PrintPortalAuthorityMessage(err)
    end
end

if SlashCmdList.PULL == nil then
    SLASH_PORTALAUTHORITYPULL1 = "/pull"
    SlashCmdList.PORTALAUTHORITYPULL = function(msg)
        PA_HandlePullSlash(msg)
    end
end
