local _, addonTable = ...

local MK = addonTable.MK or addonTable.MyKeyStone
if not MK then
    return
end

local ACCOUNT_DEBUG_COLOR_PLAYER = "ffffd100"
local ACCOUNT_DEBUG_COLOR_RESULT = "ffffd100"
local ACCOUNT_DEBUG_COLOR_SUCCESS = "ff00ff66"
local ACCOUNT_DEBUG_COLOR_ERROR = "ffff5555"
local ACCOUNT_DEBUG_COLOR_PENDING = "ff77aaff"

local ACCOUNT_DEBUG_STATUS_TEXT = {
    pending = "查询中",
    starting = "网易 API 初始化中",
    connecting = "服务连接中",
    service_connection_missing = "网易 API 离线",
    service_unreachable = "网易 API 离线",
    fresh = "已缓存",
    stale = "缓存过期",
    missing = "未查询",
    failed = "网易 API 无响应",
    unsupported = "网易 API 故障",
    offline = "网易 API 离线",
    no_response = "网易 API 无响应",
    fault = "网易 API 故障",
    ok = "网易 API 正常",
    cooldown = "冷却中",
    unavailable = "无法查询",
    unknown = "未知",
}

local ACCOUNT_DEBUG_REASON_TEXT = {
    waiting_connection = "网易 API 离线",
    service_unreachable = "网易 API 离线",
    timeout = "网易 API 无响应",
    ["bad-name"] = "角色名无效",
    ["missing-faction"] = "网易 API 故障",
    ["missing-server-target"] = "网易 API 故障",
    ["missing-NetEaseSocket-2.0"] = "网易 API 故障",
    ["missing-register-server"] = "网易 API 故障",
    ["server-unsupported"] = "网易 API 故障",
    ["service_target_not_found"] = "网易 API 离线",
    trial = "网易 API 故障",
}

local function FormatAccountDebugColorText(value, color)
    color = color or ACCOUNT_DEBUG_COLOR_PLAYER
    local text = tostring(value or "-")
    if text == "" or text == "-" then
        return string.format("|c%s%s|r", ACCOUNT_DEBUG_COLOR_ERROR, "未获取")
    end
    return string.format("|c%s%s|r", color, text)
end

local function TrimAccountDebugString(value)
    if type(value) ~= "string" then
        return ""
    end

    return value:match("^%s*(.-)%s*$") or ""
end

local function GetAccountDebugCharacterDisplayName()
    local name = UnitName("player") or "Unknown"
    local realm = GetRealmName() or "Unknown"

    return string.format("%s-%s", name, realm)
end

local function FormatAccountDebugBool(value)
    if value == true then
        return FormatAccountDebugColorText("是", ACCOUNT_DEBUG_COLOR_SUCCESS)
    end
    if value == false then
        return FormatAccountDebugColorText("否", ACCOUNT_DEBUG_COLOR_ERROR)
    end
    return FormatAccountDebugColorText("未知", ACCOUNT_DEBUG_COLOR_RESULT)
end

local function FormatAccountDebugNumber(value)
    local numberValue = tonumber(value)
    if not numberValue then
        return FormatAccountDebugColorText("未获取", ACCOUNT_DEBUG_COLOR_ERROR)
    end
    return FormatAccountDebugColorText(numberValue, ACCOUNT_DEBUG_COLOR_RESULT)
end

local function FormatAccountDebugRawValue(value)
    if value == nil or value == "" or value == "-" then
        return FormatAccountDebugColorText("未获取", ACCOUNT_DEBUG_COLOR_ERROR)
    end
    return FormatAccountDebugColorText(value, ACCOUNT_DEBUG_COLOR_RESULT)
end

local function FormatAccountDebugReasonText(value)
    if value == nil or value == "" or value == "-" then
        return FormatAccountDebugColorText("未获取", ACCOUNT_DEBUG_COLOR_ERROR)
    end

    local text = ACCOUNT_DEBUG_REASON_TEXT[tostring(value)] or value
    return FormatAccountDebugColorText(text, ACCOUNT_DEBUG_COLOR_RESULT)
end

local function FormatAccountDebugStatusText(value)
    value = tostring(value or "")
    if value == "" or value == "-" then
        return FormatAccountDebugColorText("未获取", ACCOUNT_DEBUG_COLOR_ERROR)
    end

    local text = ACCOUNT_DEBUG_STATUS_TEXT[value] or value
    if value == "pending" or value == "starting" or value == "connecting" or value == "cooldown" or value == "查询中" then
        return FormatAccountDebugColorText(text, ACCOUNT_DEBUG_COLOR_PENDING)
    end
    if value == "failed" or value == "unsupported" or value == "offline" or value == "no_response" or value == "fault" or value == "unavailable" or value == "service_unreachable" or value == "service_connection_missing"
        or value == "网易 API 离线" or value == "网易 API 无响应" or value == "网易 API 故障" then
        return FormatAccountDebugColorText(text, ACCOUNT_DEBUG_COLOR_ERROR)
    end
    return FormatAccountDebugColorText(text, ACCOUNT_DEBUG_COLOR_RESULT)
end

local function FormatAccountDebugResultText(info)
    if type(info) ~= "table" then
        return FormatAccountDebugStatusText("未获取")
    end
    if info.accountTypeInfo and info.accountTypeInfo.text and info.accountTypeInfo.text ~= "" then
        return FormatAccountDebugStatusText(info.accountTypeInfo.text)
    end
    return FormatAccountDebugStatusText(info.accountStatus or info.queryStatus or "未获取")
end

function MK:DebugAccountTypeLookup(rawName, retryCount, readOnly)
    local accountType = addonTable.AccountType
    if not (accountType and accountType.DebugQuery) then
        self:Print(FormatAccountDebugColorText("[账号类型诊断] NetEaseAPI-1.0 适配层不可用。", ACCOUNT_DEBUG_COLOR_ERROR))
        return
    end

    local queryName = TrimAccountDebugString(rawName or "")
    if queryName == "" then
        queryName = GetAccountDebugCharacterDisplayName()
    end

    local info = accountType.DebugQuery(queryName, nil, readOnly ~= true)
    info = type(info) == "table" and info or {}

    self:Print(string.format(
        "|cff33ff99[账号类型诊断] 查询对象：|r%s",
        FormatAccountDebugColorText(info.leader or queryName, ACCOUNT_DEBUG_COLOR_PLAYER)
    ))
    self:Print(string.format(
        "|cff33ff99[账号类型诊断] NetEaseAPI：|r可用=%s 版本=%s minor=%s 已启动=%s 已连接=%s",
        FormatAccountDebugBool(info.available),
        FormatAccountDebugRawValue(info.major),
        FormatAccountDebugNumber(info.minor),
        FormatAccountDebugBool(info.started),
        FormatAccountDebugBool(info.connected)
    ))
    self:Print(string.format(
        "|cff33ff99[账号类型诊断] 连接摘要：|r状态=%s 原因=%s 消息=%s 服务已连=%s 目标=%s socket=%s 等待=%s秒",
        FormatAccountDebugStatusText(info.serviceStatus or info.connectionStatus),
        FormatAccountDebugReasonText(info.serviceReason or info.connectionReason),
        FormatAccountDebugRawValue(info.serviceMessage or info.connectionMessage),
        FormatAccountDebugBool(info.serviceConnected),
        FormatAccountDebugRawValue(info.connectTarget or info.target),
        FormatAccountDebugRawValue(info.socketStatusText or info.socketStatus),
        FormatAccountDebugNumber(info.waitingSeconds or 0)
    ))
    self:Print(string.format(
        "|cff33ff99[账号类型诊断] 查询状态：|r状态=%s 原因=%s 已缓存=%s 账号显示=%s",
        FormatAccountDebugStatusText(info.displayQueryStatus or info.queryStatus),
        FormatAccountDebugReasonText(info.queryFailureReason),
        FormatAccountDebugBool(info.cached),
        FormatAccountDebugResultText(info)
    ))
    local pendingLabel = info.serviceConnected == false and "待处理" or "待回包"
    self:Print(string.format(
        "|cff33ff99[账号类型诊断] 缓存统计：|r身份=%s %s=%s 失败=%s",
        FormatAccountDebugNumber(info.cacheCount or 0),
        pendingLabel,
        FormatAccountDebugNumber(info.pendingCount or 0),
        FormatAccountDebugNumber(info.failedCount or 0)
    ))

    retryCount = type(retryCount) == "number" and retryCount or 0
    local serviceCooldownRemaining = tonumber(info.serviceCooldownRemaining) or 0
    if info.pending == true and retryCount < 4 and C_Timer and C_Timer.After then
        local delay = 5
        local pendingMessage = info.connected == false
            and "|cff33ff99[账号类型诊断] 正在等待网易账号类型服务连接，%s 秒后自动复查。|r"
            or "|cff33ff99[账号类型诊断] 查询已排队，%s 秒后自动复查。|r"
        self:Print(string.format(
            pendingMessage,
            FormatAccountDebugNumber(delay)
        ))
        C_Timer.After(delay, function()
            if self.DebugAccountTypeLookup then
                self:DebugAccountTypeLookup(queryName, retryCount + 1, true)
            end
        end)
    elseif serviceCooldownRemaining > 0 then
        self:Print(string.format(
            "|cff33ff99[账号类型诊断] %s，已进入冷却，约 %s 秒后可重试。|r",
            FormatAccountDebugRawValue(info.serviceMessage or info.connectionMessage or ACCOUNT_DEBUG_REASON_TEXT[info.queryFailureReason] or "网易 API 故障"),
            FormatAccountDebugNumber(math.ceil(serviceCooldownRemaining))
        ))
    else
        self:Print("|cff33ff99[账号类型诊断] 若状态仍为查询中，可 3-10 秒后再执行同一命令查看回包结果。|r")
    end
end

function MK:RefreshAccountTypeCache()
    local accountType = addonTable.AccountType
    if not (accountType and accountType.ClearCache) then
        self:Print(FormatAccountDebugColorText("[账号类型刷新] NetEaseAPI-1.0 适配层不可用。", ACCOUNT_DEBUG_COLOR_ERROR))
        return
    end

    local clearedCount = accountType.ClearCache()
    self:Print(string.format(
        "|cff33ff99[账号类型刷新] 已清空 NetEaseAPI 账号身份缓存：|r%s |cff33ff99条。|r",
        FormatAccountDebugNumber(clearedCount or 0)
    ))

    if C_LFGList and C_LFGList.RefreshApplicants then
        pcall(C_LFGList.RefreshApplicants)
    end

    if self.RefreshMainWindow then
        self:RefreshMainWindow("NetEaseAPI", "AccountRefresh")
    end

    self:Print("|cff33ff99[账号类型刷新] 当前队伍/集合石/寻找队伍列表会通过 NetEaseAPI-1.0 重新查询。|r")
end
