--[[
    Cerebro - Command Registry: Diagnostic Commands
    Extracted from UI/CommandRegistry.lua (Phase 2a decomposition)

    Commands:
      show_status      (original lines 68-85)
      self_test        (original lines 86-102)
      support          (original lines 103-143)
      audit_officers   (original lines 144-195)
      version          (original lines 792-801)
      toggle_debug     (original lines 1045-1091)
      run_verification (original lines 1111-1123)

    @module UI.Commands.Diagnostic
    @version 0.12.0
]]--

local AddonName, PrivateTable = ...
local Cerebro = LibStub("AceAddon-3.0"):GetAddon(AddonName)

Cerebro._commandDefs = Cerebro._commandDefs or {}
local defs = Cerebro._commandDefs

-- Diagnostics Commands
defs[#defs + 1] = {
	id = "show_status",
	displayName = "Show Status",
	description = "Displays addon status, role, and diagnostics",
	officerOnly = false,
	hidden = false,
	dangerous = false,
	slash = "/cb status [--debug]",
	-- FIX #1: Use GetModule instead of Cerebro.modules.Diagnostics
	handler = function(ctx, argv)
		local diagnostics = Cerebro:GetModule("Diagnostics", true)
		if diagnostics then
			diagnostics:ShowStatus(argv)
		else
			Cerebro:Print("Diagnostics module not loaded.")
		end
	end
}

defs[#defs + 1] = {
	id = "self_test",
	displayName = "Run Self-Test",
	description = "Runs registered health checks with PASS/FAIL summary",
	officerOnly = false,
	hidden = false,
	dangerous = false,
	slash = "/cb selftest [--debug]",
	handler = function(ctx, argv)
		local diagnostics = Cerebro:GetModule("Diagnostics", true)
		if diagnostics and diagnostics.RunSelfTest then
			diagnostics:RunSelfTest(argv)
		else
			Cerebro:Print("Diagnostics module not loaded.")
		end
	end
}

defs[#defs + 1] = {
	id = "support",
	displayName = "Support Report",
	description = "Opens a diagnostic report inspector. Self mode: /cb support. Remote mode (officer-only): /cb support <PlayerName> [count]",
	officerOnly = false,
	hidden = false,
	dangerous = false,
	slash = "/cb support [PlayerName] [count]",
	handler = function(ctx, argv)
		local diagnostics = Cerebro:GetModule("Diagnostics", true)
		if not diagnostics then
			Cerebro:Print("Diagnostics module not loaded.")
			return
		end

		-- Parse args: /cb support [PlayerName] [traceCount]
		-- Case 1: /cb support → self, default count
		-- Case 2: /cb support 100 → self, 100 events
		-- Case 3: /cb support Mysterthunt → remote, default count
		-- Case 4: /cb support Mysterthunt 100 → remote, 100 events
		local arg1 = argv and argv[1]
		local arg2 = argv and argv[2]

		if not arg1 then
			-- Self mode, default count
			diagnostics:ShowSelfSupport()
			return
		end

		-- Is arg1 a number? → self mode with custom count
		local asNum = tonumber(arg1)
		if asNum then
			diagnostics:ShowSelfSupport(asNum)
			return
		end

		-- arg1 is a player name → remote mode
		local traceCount = arg2 and tonumber(arg2) or nil
		diagnostics:SendSupportRequest(arg1, traceCount)
	end
}

defs[#defs + 1] = {
	id = "audit_officers",
	displayName = "Audit Officer Detection",
	description = "Lists all players in standings with their guild rank and IsOfficer() status",
	officerOnly = false,
	hidden = false,
	dangerous = false,
	aliases = {"auditofficers"},
	slash = "/cb auditofficers",
	handler = function(ctx)
		local players = Cerebro.db.global.players or {}
		local officers = {}
		local raiders = {}
		local unknown = {}

		for name, _ in pairs(players) do
			local rankName, _rankIndex = nil, nil

			-- Look up in guild roster
			for i = 1, GetNumGuildMembers() do
				local guildName, guildRank, _guildRankIndex = GetGuildRosterInfo(i)
			if guildName and Cerebro:GetFullPlayerName(guildName) == name then
				rankName = guildRank
				break
			end
			end

			local shortName = Cerebro:GetShortPlayerName(name) or name
			local isOfficer = Cerebro:IsOfficer(name)

			if not rankName then
				table.insert(unknown, shortName)
			elseif isOfficer then
				table.insert(officers, string.format("%s(%s)", shortName, rankName))
			else
				table.insert(raiders, string.format("%s(%s)", shortName, rankName))
			end
		end

		-- Compact output
		Cerebro:Print("=== Officer Audit ===")
		Cerebro:Print(string.format("|cff00ff00Officers (%d):|r %s",
			#officers, #officers > 0 and table.concat(officers, ", ") or "None"))
		Cerebro:Print(string.format("|cff888888Raiders (%d):|r %s",
			#raiders, #raiders > 0 and table.concat(raiders, ", ") or "None"))
		if #unknown > 0 then
			Cerebro:Print(string.format("|cffff8800Unknown (%d):|r %s",
				#unknown, table.concat(unknown, ", ")))
		end
		Cerebro:Print("=====================")
	end
}

-- Diagnostics
defs[#defs + 1] = {
	id = "version",
	displayName = "Show Version",
	description = "Displays addon version information",
	officerOnly = false,
	slash = "/cb version",
	handler = function(ctx)
		Cerebro:Print("Cerebro v" .. (Cerebro.version or "unknown"))
	end
}

-- Debug Toggle
defs[#defs + 1] = {
	id = "toggle_debug",
	displayName = "Toggle Debug Mode",
	description = "Controls debug output. Usage: /cb debug [simple|technical|both|on|off]",
	officerOnly = false,
	hidden = false,
	dangerous = false,
	slash = "/cb debug [simple|technical|both|on|off]",
	handler = function(ctx)
		local arg = ctx.args and ctx.args:lower() or ""
		local validLevels = { simple = true, technical = true, both = true, off = true }
		local newLevel

		if arg == "on" or arg == "1" or arg == "true" then
			newLevel = "both"
		elseif arg == "off" or arg == "0" or arg == "false" then
			newLevel = "off"
		elseif validLevels[arg] then
			newLevel = arg
		elseif arg == "" then
			-- No argument: cycle off → simple → technical → both → off
			local current = Cerebro:GetDebugLevel()
			local cycle = { off = "simple", simple = "technical", technical = "both", both = "off" }
			newLevel = cycle[current] or "simple"
		else
			Cerebro:Print("Usage: /cb debug [simple|technical|both|on|off]")
			Cerebro:Print("  simple    — User-friendly sync/session messages")
			Cerebro:Print("  technical — Implementation detail (hashes, internal state)")
			Cerebro:Print("  both      — All debug messages")
			Cerebro:Print("  off       — No debug output")
			return
		end

		-- Update both fields for backward compatibility
		Cerebro.db.global.config.debugLevel = newLevel
		Cerebro.db.global.config.debug = (newLevel ~= "off")

		local labels = {
			off = "|cff888888OFF|r",
			simple = "|cff66bbffSIMPLE|r",
			technical = "|cff888888TECHNICAL|r",
			both = "|cff00ff00BOTH|r",
		}
		Cerebro:Print("Debug mode: " .. (labels[newLevel] or newLevel))
	end
}

-- Verification
defs[#defs + 1] = {
	id = "run_verification",
	displayName = "Run Logic Verification",
	description = "Executes internal EPGP logic tests",
	officerOnly = false,
	hidden = true, -- Diagnostic command
	dangerous = false,
	slash = "/cb verify",
	handler = function(ctx)
		Cerebro:RunVerification()
	end
}

defs[#defs + 1] = {
	id = "validate",
	displayName = "Run Validation Suite",
	description = "Run all integrity tests and display results in a UI frame",
	officerOnly = false,
	hidden = false,
	dangerous = false,
	aliases = {"validate"},
	slash = "/cb validate [phase]",
	usage = "/cb validate       — Run all test phases\n/cb validate 3   — Run phase 3 only",
	handler = function(ctx, argv)
		local validate = Cerebro.modules.Validate
		if not validate then
			Cerebro:Print("Validate module not loaded.")
			return
		end
		validate:Run(argv and argv[1])
	end
}

-- Support API status (SPEC §8). Read-only diagnostic showing the contract
-- version and current test-mode state. Used to verify that the Cerebro-Support
-- companion addon can attach successfully.
defs[#defs + 1] = {
	id = "support_api",
	displayName = "Show Support API Status",
	description = "Display SupportAPI contract version and test-mode state (SPEC §8)",
	officerOnly = false,
	hidden = false,
	dangerous = false,
	slash = "/cb supportapi",
	handler = function(ctx, argv)
		local supportAPI = Cerebro.modules.SupportAPI
		if not supportAPI then
			Cerebro:Print("|cffff8800SupportAPI module not loaded.|r")
			return
		end

		local s = supportAPI:GetDiagnosticState()
		Cerebro:Print("=== |cff00ff00Cerebro Support API|r ===")
		Cerebro:Print(string.format("Contract version: |cffffffff%d|r", s.contractVersion))
		Cerebro:Print(string.format("Addon version:    |cffffffff%s|r", tostring(s.addonVersion)))
		Cerebro:Print(string.format("Officer:          |cffffffff%s|r", tostring(s.isOfficer)))
		if s.inTestMode then
			Cerebro:Print(string.format("Test mode:        |cffffaa00ACTIVE|r (run=%s, deadline=%ds)",
				tostring(s.activeRunID), tonumber(s.activeDeadline) or 0))
		else
			Cerebro:Print("Test mode:        |cff888888inactive|r")
		end
		Cerebro:Print(string.format("Observers:        |cffffffff%d|r", s.observerCount))
		Cerebro:Print(string.format("Max deadline:     |cffffffff%ds|r", s.maxDeadlineSeconds))
		Cerebro:Print("==============================")
	end
}
