-- ApiVault Performance Audit Assistant. Added in v1.2.0 must-have tooling rebuild.
-- Text-pattern scanner and checklist generator. Does not execute scanned code.
local addonName, ApiVault = ...

ApiVault.PerformanceAuditAssistant = ApiVault.PerformanceAuditAssistant or {}
local Assistant = ApiVault.PerformanceAuditAssistant

Assistant.rules = {
	{ pattern = "OnUpdate", risk = "high", note = "OnUpdate usage; ensure throttling and avoid allocations." },
	{ pattern = "C_Timer.NewTicker", risk = "medium", note = "Ticker usage; ensure cancel path and interval cap." },
	{ pattern = "string.format", risk = "medium", note = "string.format in hot path can add allocation pressure." },
	{ pattern = "table.insert", risk = "low", note = "table.insert in large loops may add overhead; check hot paths." },
	{ pattern = "pairs(", risk = "low", note = "pairs in refresh loops may be expensive for large tables." },
	{ pattern = "GetItemInfo", risk = "medium", note = "Item info can be cache-dependent; batch and cache results." },
	{ pattern = "C_Item.", risk = "medium", note = "C_Item calls in scan loops should be throttled/cached." },
	{ pattern = "C_Container.", risk = "medium", note = "Container scanning should be incremental/batched." },
}

function Assistant:ScanText(text)
	text = tostring(text or "")
	local hits = {}
	for _, rule in ipairs(self.rules) do
		if string.find(text, rule.pattern, 1, true) then
			table.insert(hits, rule)
		end
	end
	return hits
end

function Assistant:FormatReport(text)
	local hits = self:ScanText(text)
	local lines = {}
	table.insert(lines, "ApiVault Performance Audit Assistant")
	table.insert(lines, "hits: " .. tostring(#hits))
	table.insert(lines, "")
	for _, hit in ipairs(hits) do
		table.insert(lines, "- [" .. tostring(hit.risk) .. "] " .. tostring(hit.pattern) .. ": " .. tostring(hit.note))
	end
	if #hits == 0 then
		table.insert(lines, "No performance hotspot patterns detected in supplied text.")
	end
	table.insert(lines, "")
	table.insert(lines, "General checklist:")
	table.insert(lines, "[ ] Avoid full UI rebuilds when a row update is enough.")
	table.insert(lines, "[ ] Batch inventory/bank scans.")
	table.insert(lines, "[ ] Reuse tables in refresh paths.")
	table.insert(lines, "[ ] Cap logs and debug timelines.")
	table.insert(lines, "[ ] Throttle OnUpdate paths.")
	table.insert(lines, "[ ] Cancel timers/tickers on hide/unload where possible.")
	return table.concat(lines, "\n")
end

function Assistant:GetStats()
	return #self.rules
end
