--[[
    Commander 3.0 - Core Initialization

    Sets up the global C3 namespace that all modules attach to.
    This file MUST be loaded first in the TOC.
]]

local ADDON_NAME, C3 = ...

-- Keybind localization (must be set before Bindings.xml is processed)
_G.BINDING_HEADER_COMMANDER3 = "Commander 3"
_G.BINDING_NAME_COMMANDER3_TOGGLE = "Toggle Commander"
_G.BINDING_NAME_COMMANDER3_NEW_WINDOW = "New Commander Window"
_G.BINDING_NAME_COMMANDER3_FOCUS_LAST = "Focus Last Window"
_G.BINDING_NAME_COMMANDER3_DROP_FOCUS = "Drop Focus"
_G.BINDING_NAME_COMMANDER3_TOGGLE_FOCUS = "Toggle Focus"

-- Version info
C3.NAME = "Commander"
C3.VERSION = "3.0.0-alpha"
C3.BUILD = 1

-- Module containers (populated by other files)
C3.Version = nil        -- core/version.lua
C3.Kernel = nil         -- core/kernel.lua
C3.Pipeline = nil       -- core/pipeline.lua
C3.Lexer = nil          -- core/lexer.lua
C3.Parser = nil         -- core/parser.lua
C3.Types = nil          -- core/types.lua
C3.Registry = nil       -- commands/registry.lua
C3.SessionManager = nil -- runtime/session.lua
C3.VFS = nil            -- vfs/filesystem.lua
C3.DataSource = {}      -- datasources/*.lua

-- Command storage
C3.Commands = {}
C3.Aliases = {}

-- Feature flags (set by version.lua)
C3.Features = {}

-- Debug mode
C3.DEBUG = false

-- Global access for other addons (headless mode)
_G.Commander3 = C3
_G.C3 = C3  -- Shorthand alias

-- Initialization state
C3._initialized = false
C3._initCallbacks = {}

---Register a callback to run after full initialization
---@param callback function
function C3:OnInit(callback)
    if self._initialized then
        callback()
    else
        table.insert(self._initCallbacks, callback)
    end
end

---Mark initialization complete and run callbacks
function C3:CompleteInit()
    self._initialized = true

    -- Initialize theme font before any UI is created
    if self.UI and self.UI.Theme and self.UI.Theme.InitFont then
        self.UI.Theme:InitFont()
    end

    for _, callback in ipairs(self._initCallbacks) do
        local ok, err = pcall(callback)
        if not ok and self.DEBUG then
            local errColor = (self.UI and self.UI.Theme and self.UI.Theme:GetColor("accent.error")) or "BF616A"
            print(string.format("|cff%s[C3] Init callback error:|r", errColor), err)
        end
    end
    self._initCallbacks = {}

    -- Initialize VFS global instance
    if self.InitVFS then
        self:InitVFS()
    end

    -- Load persisted sessions and global config (must be after VFS init)
    if self.SessionManager and self.SessionManager.Load then
        self.SessionManager:Load()
    end

    -- Start Background Prefetch for Lookup (cache optimization)
    -- Delay slightly to let initial login lag settle
    if C_Timer then
        C_Timer.After(2, function()
            if self.Lookup and self.Lookup.SchedulePrefetch then
                self.Lookup:SchedulePrefetch()
            end
        end)
    end

    if self.DEBUG then
        local successColor = (self.UI and self.UI.Theme and self.UI.Theme:GetColor("accent.success")) or "A3BE8C"
        print(string.format("|cff%s[%s]|r v%s loaded", successColor, self.NAME, self.VERSION))
    end
end

---Execute a command string (main entry point)
---@param input string The command to execute
---@param session? table Optional session context
---@return any result The command result (objects, not strings)
function C3:Execute(input, session)
    if not self.Kernel then
        error("C3.Kernel not initialized")
    end
    return self.Kernel:Execute(input, session)
end

---Execute synchronously (blocking) - for headless/API use
---@param input string The command to execute
---@return any result The command result
function C3:Query(input)
    if not self.Kernel then
        error("C3.Kernel not initialized")
    end
    return self.Kernel:ExecuteSync(input)
end

-- Debug print helper
function C3:Debug(...)
    if self.DEBUG then
        local dimColor = (self.UI and self.UI.Theme and self.UI.Theme:GetColor("status.dim")) or "4C566A"
        print(string.format("|cff%s[C3]|r", dimColor), ...)
    end
end

-- Error print helper
function C3:Error(msg)
    local errColor = (self.UI and self.UI.Theme and self.UI.Theme:GetColor("accent.error")) or "BF616A"
    print(string.format("|cff%s[C3 Error]|r", errColor), msg)
end

-- Return the namespace for other files
return C3
