-- ApiVault API Compatibility Matrix. Added in v1.2.0 must-have tooling rebuild.
-- Compares documented metadata, source usage and runtime global presence where available.
local addonName, ApiVault = ...

ApiVault.APICompatibilityMatrix = ApiVault.APICompatibilityMatrix or {}
local Matrix = ApiVault.APICompatibilityMatrix

local function resolve(path)
	local current = _G
	for part in string.gmatch(tostring(path or ""), "[^%.]+") do
		if type(current) ~= "table" then return nil end
		current = current[part]
		if current == nil then return nil end
	end
	return current
end

function Matrix:IsDocumented(apiName)
	if ApiVault.Index and ApiVault.Index.byName and ApiVault.Index.byName[apiName] then
		return true
	end
	if ApiVault.APIData and ApiVault.APIData.functions then
		for _, entry in ipairs(ApiVault.APIData.functions) do
			if entry then
				local full = entry.fullName or entry.name
				if not string.find(tostring(full or ""), "%.") and entry.system then
					full = tostring(entry.system) .. "." .. tostring(entry.name)
				end
				if full == apiName or entry.name == apiName then
					return true
				end
			end
		end
	end
	return false
end

function Matrix:HasSourceUsage(apiName)
	if ApiVault.SourceUsage and ApiVault.SourceUsage.FindByAPI then
		local ok, uses = pcall(ApiVault.SourceUsage.FindByAPI, ApiVault.SourceUsage, apiName)
		return ok and uses and #uses > 0 or false
	end
	return false
end

function Matrix:Check(apiName)
	local runtimeValue = resolve(apiName)
	return {
		api = tostring(apiName or ""),
		documented = self:IsDocumented(apiName),
		runtimeGlobal = runtimeValue ~= nil,
		runtimeType = type(runtimeValue),
		sourceUsage = self:HasSourceUsage(apiName),
		risk = "review",
		note = "Compatibility matrix is evidence-based: documented metadata, runtime _G presence and source usage metadata. It does not invent build behavior.",
	}
end

function Matrix:FormatReport(apiListText)
	local lines = {}
	table.insert(lines, "ApiVault API Compatibility Matrix")
	table.insert(lines, "")
	local count = 0
	for token in string.gmatch(tostring(apiListText or ""), "([%w_]+%.[%w_]+)") do
		count = count + 1
		local row = self:Check(token)
		table.insert(lines, tostring(row.api) .. " | documented=" .. tostring(row.documented) .. " | runtimeGlobal=" .. tostring(row.runtimeGlobal) .. " | runtimeType=" .. tostring(row.runtimeType) .. " | sourceUsage=" .. tostring(row.sourceUsage) .. " | risk=" .. tostring(row.risk))
	end
	if count == 0 then
		table.insert(lines, "Paste API names such as C_Item.GetItemInfo or C_Container.GetContainerNumSlots.")
	end
	return table.concat(lines, "\n")
end

function Matrix:GetStats()
	return 4
end
