local addonName = ...
local Test = {}
_G.ApiVaultDebugTest = Test

Test.version = "1.1.2"
Test.publicApiVersion = 1
Test.lastReport = nil

local function Print(message)
    DEFAULT_CHAT_FRAME:AddMessage("|cff99ddffApiVaultDebugTest|r: " .. tostring(message))
end

local function GetBridge()
    if not ApiVault or type(ApiVault.GetPublicAPI) ~= "function" then
        return nil, "ApiVault Public API is unavailable. Enable ApiVault and reload UI."
    end
    local ok, bridge, err = pcall(ApiVault.GetPublicAPI, ApiVault, "ApiVaultDebugTest", Test.publicApiVersion)
    if not ok then
        return nil, tostring(bridge)
    end
    if not bridge then
        return nil, tostring(err or "ApiVault:GetPublicAPI returned nil")
    end
    return bridge
end

local function Call(bridge, method, ...)
    if not bridge or type(bridge[method]) ~= "function" then
        Print("Bridge method unavailable: " .. tostring(method))
        return false, "method unavailable"
    end
    local ok, result = pcall(bridge[method], bridge, ...)
    if not ok then
        Print(method .. " failed: " .. tostring(result))
        return false, result
    end
    return true, result
end

function Test:Register()
    local bridge, err = GetBridge()
    if not bridge then
        Print(err)
        return nil
    end
    local interfaceVersion = 0
    if type(GetBuildInfo) == "function" then
        local _, _, _, interface = GetBuildInfo()
        interfaceVersion = interface or 0
    end
    Call(bridge, "RegisterAddon", {
        name = "ApiVaultDebugTest",
        version = Test.version,
        author = "DruxlyeSofty",
        interface = interfaceVersion,
        purpose = "External ApiVault Public API test harness",
    })
    return bridge
end

function Test:Run()
    local bridge = self:Register()
    if not bridge then return end

    Call(bridge, "StartSession", "Public API harness run")
    Call(bridge, "Log", "info", "ApiVaultDebugTest run started", { command = "/avdt run" })
    Call(bridge, "Log", "debug", "Testing public bridge methods", { apiVersion = Test.publicApiVersion })
    Call(bridge, "TraceAPI", "C_Item.GetItemInfo", {
        file = "ApiVaultDebugTest/Core.lua",
        line = 83,
        context = "Synthetic public API trace. Function is not called by the harness.",
    })
    Call(bridge, "TraceEvent", "BAG_UPDATE", {
        file = "ApiVaultDebugTest/Core.lua",
        line = 88,
        registration = "RegisterEvent",
        context = "Synthetic event trace. Event is not registered by the harness.",
    })
    Call(bridge, "ReportSecureRisk", {
        pattern = "SetAttribute",
        file = "ApiVaultDebugTest/Core.lua",
        line = 94,
        context = "Synthetic secure-risk report only. The harness does not call SetAttribute.",
        combatSensitive = true,
    })
    Call(bridge, "ReportSavedVariables", {
        name = "ApiVaultDebugTestDB",
        initialized = _G.ApiVaultDebugTestDB ~= nil,
        schemaVersion = nil,
        note = "No SavedVariables are declared by the harness; this is a bridge data test.",
    })
    Call(bridge, "Checkpoint", "Synthetic checkpoint", {
        step = "bridge-methods",
        ok = true,
    })
    Call(bridge, "ReportError", {
        message = "Synthetic test error: attempt to index field 'settings' (a nil value)",
        file = "ApiVaultDebugTest/Core.lua",
        line = 112,
        stack = debugstack and debugstack() or "debugstack unavailable",
        category = "synthetic-test-error",
        context = "Data-only error report generated by /avdt run.",
    })
    Call(bridge, "EndSession", "Public API harness run")

    local ok, report = Call(bridge, "ExportReport")
    if ok then
        Test.lastReport = report
    end
    Print("Public API test run completed. Open /av devapi or /av reports in ApiVault.")
end

function Test:ErrorOnly()
    local bridge = self:Register()
    if not bridge then return end
    Call(bridge, "ReportError", {
        message = "Synthetic explicit error report from /avdt error",
        file = "ApiVaultDebugTest/Core.lua",
        line = 132,
        stack = debugstack and debugstack() or "debugstack unavailable",
        category = "manual-test-error",
        context = "Data-only error report. No Lua error was thrown.",
    })
    Print("Synthetic error report sent to ApiVault.")
end

function Test:Report()
    local bridge = self:Register()
    if not bridge then return end
    local ok, report = Call(bridge, "ExportReport")
    if ok then
        Test.lastReport = report
        Print("Report exported to ApiVaultDebugTest.lastReport. Also visible in /av reports.")
        if report then
            local firstLine = tostring(report):match("([^\n]+)") or "report generated"
            Print(firstLine)
        end
    end
end

function Test:Help()
    Print("Commands: /avdt, /avdt run, /avdt error, /avdt report")
    Print("This addon tests ApiVault:GetPublicAPI from an external addon. No protected calls are executed.")
end

SLASH_APIVAULTDEBUGTEST1 = "/avdt"
SlashCmdList.APIVAULTDEBUGTEST = function(msg)
    msg = string.lower((msg or ""):gsub("^%s+", ""):gsub("%s+$", ""))
    if msg == "run" then
        Test:Run()
    elseif msg == "error" then
        Test:ErrorOnly()
    elseif msg == "report" then
        Test:Report()
    else
        Test:Help()
        local bridge = Test:Register()
        if bridge then
            Print("Bridge available. Use /avdt run to send test data.")
        end
    end
end

local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(_, event, loadedName)
    if loadedName == addonName then
        Print("loaded. Use /avdt run to test ApiVault Public API.")
    end
end)
