-- ApiVault in-game documentation content. Added in v1.2.0 documentation rebuild.
-- Metadata/documentation only. No runtime file reads and no protected/secure execution.
local addonName, ApiVault = ...

ApiVault.Documentation = ApiVault.Documentation or {}
local Docs = ApiVault.Documentation

Docs.version = "1.3.4"
Docs.policy = "in-game manual content; generated from project documentation; no runtime source file reads"
Docs.sections = {
    {
        key = "intro",
        title = "1. Overview",
        body = [=[
ApiVault is an in-game developer reference, metadata explorer, safe test lab and debug bridge for World of Warcraft addon authors.

ApiVault is built around one strict principle: it should help developers find, inspect, compare, test and debug information without bypassing Blizzard's protected/secure execution model.

ApiVault can help you:
- browse documented Blizzard APIs, events and tables
- inspect source usage metadata generated from Interface.zip
- browse bundled Interface reference metadata
- inspect XML templates and TOC modules
- inspect symbols, widgets, constants, slash commands, bindings and settings references
- run safe API tests through SafeRunner
- record event payloads manually
- audit pasted addon snippets
- inspect loaded addon metadata
- connect external addons through the Public Developer Debug API
- ingest external error records for Bug Advisor analysis

Important distinction:
Source usage reference is static metadata. It shows where a reference was found in the bundled/generated Interface source metadata. It does not prove that the code path is currently active or being called live.
]=],
    },
    {
        key = "safety",
        title = "2. Safety Model",
        body = [=[
ApiVault is not a protected/secure execution bypass.

Hard rules:
- ApiVault does not automatically execute protected APIs.
- ApiVault does not automatically call SetAttribute.
- ApiVault does not create secure buttons for automated tests.
- ApiVault does not force protected/secure execution.
- ApiVault does not read bundled source files at runtime.
- ApiVault does not display full Blizzard source code in-game.
- External addon input is treated as data only.
- Bug Advisor output is advisory, not a guaranteed fix.

SafeRunner policy:
- safe entries may be tested through guarded execution
- protected entries are blocked
- metadata-only entries are blocked
- review-required entries are blocked unless an explicit user-controlled policy allows safe inspection
- secure-sensitive entries remain inspect-only

When secure or combat-sensitive behavior is involved, test out-of-combat and in combat in the live client.
]=],
    },
    {
        key = "install",
        title = "3. Installation and First Run",
        body = [=[
Installation:
1. Extract the zip.
2. Place the ApiVault folder in:
   World of Warcraft/_retail_/Interface/AddOns/
3. If the package includes ApiVaultDebugTest, place that folder next to ApiVault.
4. Restart the WoW client fully.
5. Enable ApiVault in the addon list.
6. Run:
   /av stats
   /apivault

Expected:
- ApiVault loads without startup Lua errors.
- /av stats prints metadata counts.
- /apivault opens the main UI.
- Examples/Interface files are not loaded by the TOC.

If a Lua error appears:
- capture the first error stack
- report the exact file/line/message
- do not continue with later errors until the first one is fixed
]=],
    },
    {
        key = "main-ui",
        title = "4. Main Interface",
        body = [=[
Open the main window with:
- /apivault
- /av

The main window contains:
- search box
- function/event/table filters
- result list
- detail panel
- argument builder area for functions
- result/event log
- action buttons
- navigation buttons for secondary tools

The Documentation button opens this manual in-game.

Main API filter meanings:
- Function: documented API function from Blizzard_APIDocumentationGenerated
- Event: documented event metadata
- Table: documented API table/structure metadata

Important:
The Function list is not every function in WoW. It is the documented API function list. For broader coverage, use Symbol Browser, Widget Browser, Catalogs and Runtime Globals.
]=],
    },
    {
        key = "api-browser",
        title = "5. API Browser",
        body = [=[
The API Browser lets you inspect documented Blizzard API metadata.

Use it to:
- search functions/events/tables
- view arguments
- view return values
- view event payload fields
- inspect risk classification
- inspect generated examples
- inspect source usage references
- inspect linked secure patterns
- open related tools

Developer workflow:
1. Search for a function, for example C_Item.GetItemInfo.
2. Open the detail view.
3. Check arguments and returns.
4. Check source usage metadata.
5. Check Source Examples.
6. Check Secure Pattern references.
7. If classified safe, test via SafeRunner.

Reminder:
Documentation metadata does not guarantee runtime availability in every game state. Some APIs depend on cache state, player state, loaded modules, combat lockdown or server data.
]=],
    },
    {
        key = "source-usage",
        title = "6. Source Usage Reference",
        body = [=[
Source Usage Reference shows static metadata generated from Interface.zip and the bundled Interface reference.

It can show:
- API names referenced in Blizzard source
- event registrations found in source
- module name
- sourcePath
- addonPath
- line number
- short context label
- usage counts

It cannot prove:
- that a code path is currently active
- that a module is loaded now
- that a function was called this session
- that an API is safe in all contexts
- that a usage pattern is recommended for addon authors

Correct interpretation:
"Blizzard source metadata contains a reference to this API here."

Incorrect interpretation:
"Blizzard is calling this API live right now."
]=],
    },
    {
        key = "interface-browser",
        title = "7. Interface Resource Browser",
        body = [=[
Commands:
- /av interface
- /av resources

The Interface Resource Browser shows metadata for files and folders under the bundled Interface reference tree.

It can show:
- file path
- sourcePath
- addonPath
- file type
- size
- line count
- hash metadata
- module
- API usage count
- event usage count
- XML template count
- secure pattern count

Important:
ApiVault does not read these files at runtime. The browser uses generated metadata.
]=],
    },
    {
        key = "xml",
        title = "8. XML Template Catalog",
        body = [=[
Commands:
- /av templates
- /av xml

The XML Template Catalog shows metadata for XML templates and UI frame definitions.

It can show:
- template/frame name
- frame type
- virtual flag
- inherits metadata
- inherited-by samples
- mixin references
- script handlers
- parentKey
- frame strata
- module
- source/addon path
- secure/reference flags

Use this when:
- finding template names
- checking inheritance
- discovering script handlers
- finding templates linked to a module or file

Metadata warning:
A template being present does not automatically mean it is safe or recommended for your addon. Validate in-game.
]=],
    },
    {
        key = "modules",
        title = "9. TOC Module Browser",
        body = [=[
Commands:
- /av modules
- /av toc

The TOC Module Browser shows metadata parsed from Blizzard .toc files.

It can show:
- module name
- TOC path
- title
- notes
- interface version
- dependencies
- required dependencies
- optional dependencies
- LoadOnDemand flags
- SavedVariables declarations
- SavedVariablesPerCharacter declarations
- secure/useSecureEnvironment flags
- Lua/XML/other file counts
- linked APIs/events/templates/secure patterns

Use this to understand how Blizzard modules are structured and loaded.
]=],
    },
    {
        key = "symbols",
        title = "10. Symbols, Globals and Function Coverage",
        body = [=[
Commands:
- /av symbols
- /av globals
- /av mixins

ApiVault separates documented APIs from broader symbol coverage.

Documented API Function:
- parsed from Blizzard_APIDocumentationGenerated
- shown in the main API browser

Source Symbol:
- parsed from bundled Interface source metadata
- may be global, local, table function, method, mixin method or XML script handler
- not necessarily callable by your addon

Runtime Global:
- found by read-only _G inspection in the current session
- session-specific
- functions are not called by ApiVault

Use Symbol Browser and Runtime Globals when the API browser does not show the function-like name you are looking for.
]=],
    },
    {
        key = "catalogs",
        title = "11. Catalogs: Constants, Slash Commands, Bindings, Settings",
        body = [=[
Commands:
- /av catalogs
- /av constants
- /av slash
- /av bindings
- /av settings

Catalogs expose metadata for:
- constants
- slash command declarations
- SlashCmdList handlers
- binding headers/names/commands
- CVar and settings references

Safety:
- ApiVault does not execute slash commands automatically.
- ApiVault does not change CVars from catalog views.
- Settings/CVar behavior is marked as metadata unless proven by uploaded source.
]=],
    },
    {
        key = "widgets",
        title = "12. Widget / Frame / ScriptObject Explorer",
        body = [=[
Commands:
- /av widgets
- /av frameapi
- /av scripts
- /av createframe
- /av scriptobjects

This browser helps inspect:
- widget method metadata
- frame/script object method references
- XML script handlers
- CreateFrame usage references
- SetScript / HookScript references

Use it for UI development:
- finding frame methods
- checking script handlers
- discovering CreateFrame examples
- investigating widget-related errors

Methods are metadata/inspect-only unless ApiVault explicitly identifies a safe test path.
]=],
    },
    {
        key = "secure",
        title = "13. Secure Pattern Reference",
        body = [=[
Commands:
- /av secure

Secure Pattern Reference indexes secure and taint-sensitive metadata.

Examples:
- SetAttribute
- GetAttribute
- RegisterStateDriver
- UnregisterStateDriver
- SecureActionButtonTemplate
- SecureHandler templates
- SecureUnitButtonTemplate
- SecureFrameTemplate
- InCombatLockdown
- hooksecurefunc
- sec = NotAllowed
- secret/restricted API metadata

Use it to:
- identify taint-sensitive areas
- build OOC/combat test checklists
- locate secure pattern references
- avoid unsafe automatic execution

These entries are inspect-only unless explicitly safe-readonly.
]=],
    },
    {
        key = "examples",
        title = "14. Source Examples",
        body = [=[
Commands:
- /av examples

Source Examples are generated/sanitized examples derived from metadata and usage references. They are not full Blizzard source copies.

Each example may include:
- owner API/event/template/module
- sourcePath
- addonPath
- module
- line number
- context label
- generated snippet
- risk class
- uncertain notes

Policy:
- no full function bodies
- no multiline copied Blizzard source blocks
- no automatic protected execution
- uncertain behavior must be labeled
]=],
    },
    {
        key = "testlab",
        title = "15. Runtime Test Lab",
        body = [=[
Commands:
- /av testlab
- /av tests
- /av testhistory
- /av runtime
- /av lab

Runtime Test Lab provides:
- argument builder
- typed argument input
- safer return serializer
- table depth cap
- table key cap
- recursive table detection
- frame/userdata summarizer
- test history
- blocked reason panel

Use it for controlled safe tests.

Do not use it to force protected/secure calls. Protected, metadata-only and review-required items remain blocked by policy.
]=],
    },
    {
        key = "eventlab",
        title = "16. Event Lab + Payload Recorder",
        body = [=[
Commands:
- /av events
- /av eventlab
- /av payloads
- /av recorder

Event Lab provides:
- manual event listener
- start/stop event recording
- stop all listeners
- capped payload history
- payload serialization
- event frequency/count metadata
- generated listener snippets

Safety:
- no auto-register-all
- event name must be explicit
- payload logs are capped
- use only for debugging and validation
]=],
    },
    {
        key = "audit",
        title = "17. Addon Audit Mode",
        body = [=[
Commands:
- /av audit
- /av scan
- /av addoncheck
- /av auditmode

Addon Audit Mode lets you paste Lua/XML/TOC text and generate checklist-style findings.

It can detect:
- C_* API references
- event registrations
- XML template references
- TOC metadata
- SavedVariables declarations
- secure-sensitive patterns
- OnUpdate / timer patterns
- dynamic execution warnings

Policy:
- no automatic code rewriting
- no definitive fix without source context
- uncertain findings are advisory
]=],
    },
    {
        key = "debug-api",
        title = "18. Public Developer Debug API",
        body = [=[
Commands:
- /av devapi
- /av debugbridge
- /av addondebug
- /av reports

External addons can register debug data through ApiVault:

local AV = ApiVault and ApiVault.GetPublicAPI and ApiVault:GetPublicAPI("MyAddon", 1)

Bridge methods:
- RegisterAddon(metadata)
- Log(level, message, context)
- ReportError(errorInfo)
- TraceAPI(apiName, traceInfo)
- TraceEvent(eventName, traceInfo)
- ReportSecureRisk(riskInfo)
- ReportSavedVariables(svInfo)
- Checkpoint(label, data)
- StartSession(name)
- EndSession(name)
- GetReport()
- ExportReport()
- HasCapability(name)
- GetCapabilities()
- GetVersion()

External input is data only. ApiVault does not execute addon-provided code.
]=],
    },
    {
        key = "bugadvisor",
        title = "19. Bug Advisor / External Error Bridge",
        body = [=[
Commands:
- /av bugadvisor
- /av bugs
- /av externalerrors
- /av errorbridge

Generic ingest:

ApiVault.BugAdvisor:IngestError({
    addon = "MyAddon",
    message = "...",
    stack = "...",
    source = "Custom"
})

Convenience ingest:

ApiVault:IngestExternalError({
    addon = "MyAddon",
    message = "...",
    stack = "...",
    source = "CustomBugDetector"
})

Bug Advisor can:
- normalize error records
- classify error categories
- parse stack frames
- link errors to APIs/events/templates/modules/secure patterns
- generate suggested fix checklists
- generate copyable bug reports

No BugGrabber internals are assumed unless BugGrabber source/API is supplied. The included adapter shape is passive.
]=],
    },
    {
        key = "dashboard",
        title = "20. Developer Debug Dashboard",
        body = [=[
Commands:
- /av dashboard
- /av debugdashboard
- /av timeline
- /av debugtimeline

The dashboard can show:
- registered addons overview
- unified debug timeline
- error timeline
- API trace timeline
- event trace timeline
- secure-risk timeline
- SavedVariables status
- session view
- export complete debug report

This is most useful when external addons use ApiVault's Public Developer Debug API.
]=],
    },
    {
        key = "addons",
        title = "21. Loaded Addon Runtime Inspector",
        body = [=[
Commands:
- /av addons
- /av loaded

This inspector shows read-only runtime addon metadata:
- name
- title
- notes
- version
- author
- interface
- loaded/loadable status
- enable state
- dependencies
- optional dependencies
- SavedVariables metadata

Policy:
- does not force-load LoadOnDemand addons
- does not inspect runtime source files
- metadata is session-specific
]=],
    },
    {
        key = "builddiff",
        title = "22. Build Diff Support",
        body = [=[
Commands:
- /av diff
- /av builddiff
- /av manifest

Build Diff Support currently includes:
- current build manifest
- pasted compact manifest comparison
- numeric diff output

A true build-to-build diff requires a second generated Interface manifest from another Interface.zip. ApiVault does not invent build differences.
]=],
    },
    {
        key = "favorites",
        title = "23. Favorites, Recent Items and Export",
        body = [=[
Favorites/recent commands:
- /av favorites
- /av favs
- /av recent
- /av history

Export/checklist commands:
- /av export
- /av checklist
- /av checklists

Developer actions:
- /av polish
- /av todo
- /av actions
- /av compact

These tools help with:
- saving frequently used entries
- tracking recent searches
- copying generated summaries
- copying test checklists
- exporting audit notes
- toggling compact mode
]=],
    },
    {
        key = "layout",
        title = "24. UI Stability and Layout",
        body = [=[
Commands:
- /av layout
- /av uistability
- /av clamp
- /av windows

UI Stability manages:
- shared window strata
- top-level behavior where supported
- screen clamping
- compact mode
- output caps for long logs/reports
- scroll normalization

If a window opens off-screen or overlaps badly:
1. Try /av clamp
2. Toggle compact mode with /av compact
3. Reopen the panel
4. Report a screenshot if layout remains broken
]=],
    },
    {
        key = "commands",
        title = "25. Complete Slash Command Reference",
        body = [=[
Main:
- /apivault — open or toggle the main ApiVault window
- /av — open or toggle the main ApiVault window
- /av stats — print loaded metadata/runtime counts
- /av compat — print compatibility/build context

Search and browsing:
- /av search — open Unified Search
- /av global — open Unified Search
- /av interface — open Interface Resource Browser
- /av resources — open Interface Resource Browser
- /av templates — open XML Template Catalog
- /av xml — open XML Template Catalog
- /av modules — open TOC Module Browser
- /av toc — open TOC Module Browser
- /av symbols — open Symbol Browser
- /av globals — open Runtime Global Inspector
- /av mixins — open mixin/symbol view
- /av catalogs — open catalog browser
- /av catalog — open catalog browser
- /av constants — open constants catalog
- /av slash — open slash command catalog
- /av bindings — open bindings catalog
- /av settings — open settings/CVar catalog
- /av widgets — open Widget Browser
- /av frameapi — open widget/frame API view
- /av scripts — open script handler view
- /av createframe — open CreateFrame usage view
- /av scriptobjects — open ScriptObject/widget method view

Examples, secure and cross-links:
- /av examples — open Source Example Browser
- /av secure — open Secure Pattern Reference
- /av links — open cross-link information
- /av crosslinks — open cross-link information

Testing and runtime tools:
- /av testlab — open Runtime Test Lab
- /av tests — open Runtime Test Lab
- /av testhistory — open test history
- /av runtime — open runtime test tools
- /av lab — open runtime test tools
- /av events — open Event Lab
- /av eventlab — open Event Lab
- /av payloads — open Event Lab payload recorder
- /av recorder — open Event Lab recorder
- /av addons — open Loaded Addon Runtime Inspector
- /av loaded — open Loaded Addon Runtime Inspector

Audit and debugging:
- /av audit — open Addon Audit Mode
- /av scan — open Addon Audit Mode
- /av addoncheck — open Addon Audit Mode
- /av auditmode — open Addon Audit Mode
- /av devapi — open Public Developer API panel
- /av debugbridge — open Developer Debug Bridge
- /av addondebug — open Developer Debug panel
- /av reports — open reports/debug panel
- /av bugadvisor — open Bug Advisor
- /av bugs — open Bug Advisor
- /av externalerrors — open External Error Bridge
- /av errorbridge — open External Error Bridge
- /av dashboard — open Developer Debug Dashboard
- /av debugdashboard — open Developer Debug Dashboard
- /av timeline — open debug timeline
- /av debugtimeline — open debug timeline

Build/release/status:
- /av diff — open Build Diff panel
- /av builddiff — open Build Diff panel
- /av manifest — open Build Manifest panel
- /av stable — open stable release status
- /av about — open stable release/about panel
- /av release — open release status panel

User state and exports:
- /av favorites — open Favorites panel
- /av favs — open Favorites panel
- /av recent — open Recent panel
- /av history — open Recent/search history
- /av export — open Export panel
- /av checklist — open checklist/export panel
- /av checklists — open checklist/export panel
- /av polish — open Developer Actions/polish panel
- /av todo — open TODO/polish panel
- /av actions — open Developer Actions panel
- /av compact — toggle compact UI mode

Layout:
- /av layout — show UI stability status
- /av uistability — show UI stability status
- /av clamp — clamp managed windows to screen
- /av windows — show managed window status

Documentation:
- /av docs — open this in-game documentation panel
- /av documentation — open this in-game documentation panel
- /av manual — open this in-game documentation panel
- /av help — open this in-game documentation panel

Companion test addon, if installed:
- /avdt — ApiVaultDebugTest help
- /avdt run — send sample bridge records to ApiVault
- /avdt error — send a synthetic error to Bug Advisor
- /avdt report — print/export test report summary
]=],
    },
    {
        key = "troubleshooting",
        title = "26. Troubleshooting",
        body = [=[
If ApiVault fails to load:
1. Capture the first Lua error only.
2. Check the file and line number.
3. If the error is in Data/*.lua, it is likely a generated shard issue.
4. If the error is in UI/*.lua, it is likely a panel/layout issue.
5. If the error is in Runtime/*.lua, it is likely a runtime tool issue.

Useful diagnostic commands:
- /av stats
- /av layout
- /av stable
- /av search
- /av bugadvisor

Report:
- exact ApiVault version
- first error stack
- screenshot if UI layout is involved
- client build/interface number
- whether ApiVaultDebugTest is installed
]=],
    },
    {
        key = "limitations",
        title = "27. Known Limitations",
        body = [=[
Known limitations:
- ApiVault has not been live-validated in this environment.
- Source usage reference is static metadata, not live behavior.
- Runtime globals are session-specific.
- Bug Advisor suggestions are advisory.
- Build diff requires another generated manifest for true build-to-build comparison.
- BugGrabber internals are not assumed unless source/API is provided.
- Bundled Interface reference redistribution status remains UNCERTAIN and should be reviewed before public distribution.

Use ApiVault as a developer reference, not as a replacement for live testing.
]=],
    },

    {
        key = "musthave-tools",
        title = "28. Must-Have Developer Tools",
        body = [=[
ApiVault includes an integrated developer toolbox for the workflows that WoW addon developers use most often.

Open it with:
/av devtools
/av musthave
/av toolbox

Included tools:
1. Error Inbox + Explain This Error
2. SavedVariables Schema Inspector
3. Taint / Combat Safety Assistant
4. Addon Package Validator
5. Performance Audit Assistant
6. API Compatibility Matrix
7. Snippet Library with Safe Patterns
8. Complete Developer Session Export

Individual commands:
/av errors
/av errorinbox
/av explain
/av sv
/av savedvariables
/av schema
/av taint
/av combat
/av combatsafety
/av package
/av packagecheck
/av releasecheck
/av perf
/av performance
/av perfcheck
/av apimatrix
/av compatmatrix
/av compatibilitymatrix
/av snippets
/av patterns
/av safepatterns
/av sessionexport
/av fullexport
/av debugexport

These tools are advisory and data-oriented. They do not add protected execution, do not weaken SafeRunner, do not runtime-read source files and do not execute external addon-provided code.
]=],
    },

    {
        key = "bugsack-bridge",
        title = "29. BugSack / BugGrabber Bridge",
        body = [=[
ApiVault can mirror future Lua errors into Error Inbox and Bug Advisor while still forwarding the error to the previous WoW error handler.

Commands:
/av bugsack
/av buggrabber
/av errormirror
/av errorhandler

How it works:
- ApiVault installs a chained error handler.
- ApiVault captures the error as data.
- ApiVault sends it to Error Inbox / Bug Advisor.
- ApiVault then calls the previous handler, so BugSack/BugGrabber can still receive the error.

Limitations:
- Existing BugSack history is not imported.
- BugSack/BugGrabber internals are not assumed.
- A specific history-import adapter requires supplied BugSack/BugGrabber API/source.
]=],
    },

    {
        key = "loaded-addon-control-center",
        title = "29. Loaded Addon Control Center",
        body = [=[
Commands:
/av addoncenter
/av addoncontrol
/av loadedaddons
/av requestreport

The Loaded Addon Control Center lists runtime addon metadata and shows whether an addon has opted in to ApiVault's Public Developer API.

For a selected addon, ApiVault can show:
- runtime addon metadata
- loaded/enabled/loadable state where available
- Version, Author, Interface
- Dependencies and OptionalDeps
- SavedVariables and SavedVariablesPerCharacter metadata where available
- Public Developer API registration state
- Error Inbox matches
- Bug Advisor matches
- API traces, event traces, secure risks, SavedVariables reports and sessions for integrated addons

Request buttons create pending opt-in requests only. ApiVault does not execute arbitrary addon code.

Integrated addons can respond by polling:

local AV = ApiVault and ApiVault.GetPublicAPI and ApiVault:GetPublicAPI("MyAddon", 1)
if AV then
    for _, request in ipairs(AV:GetPendingRequests()) do
        if request.requestType == "savedvariables-status" then
            AV:ReportSavedVariables({ name = "MyAddonDB", initialized = type(MyAddonDB) == "table" })
            AV:AckRequest(request.id)
        end
    end
end

Unsupported force-report behavior is opt-in only.
]=],
    },
}

function Docs:GetSections()
    return self.sections or {}
end

function Docs:GetSection(index)
    return (self.sections or {})[tonumber(index or 1) or 1]
end

function Docs:Find(query)
    query = string.lower(tostring(query or ""))
    local results = {}
    for index, section in ipairs(self.sections or {}) do
        local haystack = string.lower(tostring(section.title or "") .. "\n" .. tostring(section.body or ""))
        if query == "" or string.find(haystack, query, 1, true) then
            table.insert(results, { index = index, section = section })
        end
    end
    return results
end

function Docs:GetFullManual()
    local lines = {}
    table.insert(lines, "ApiVault Full User and Developer Manual")
    table.insert(lines, "Version: " .. tostring(self.version or "unknown"))
    table.insert(lines, "")
    for _, section in ipairs(self.sections or {}) do
        table.insert(lines, "## " .. tostring(section.title or "Untitled"))
        table.insert(lines, tostring(section.body or ""))
        table.insert(lines, "")
    end
    return table.concat(lines, "\n")
end

function Docs:GetStats()
    return #(self.sections or {}), self.version or "unknown"
end
