/**
 * Agent State Module
 *
 * Manages the state of the agent including mode, cost tracking,
 * session management, and configuration.
 * Extracted from CodeBuddyAgent for better modularity and testability.
 */
import { EventEmitter } from "events";
import { getCostTracker } from "../utils/cost-tracker.js";
import { getAgentModeManager } from "./agent-mode.js";
import { getSandboxManager } from "../security/sandbox.js";
import { createContextManager } from "../context/context-manager-v2.js";
import { getSessionStore } from "../persistence/session-store.js";
/**
 * Default agent configuration
 */
export const DEFAULT_AGENT_CONFIG = {
    maxToolRounds: 50,
    sessionCostLimit: 10,
    yoloMode: false,
    parallelToolExecution: false,
    ragToolSelection: false,
    selfHealing: true,
};
/**
 * YOLO mode configuration
 */
export const YOLO_CONFIG = {
    maxToolRounds: 400,
    sessionCostLimit: Infinity,
    yoloMode: true,
};
/**
 * AgentState manages all state-related concerns for the agent.
 */
export class AgentState extends EventEmitter {
    // Configuration
    config;
    // Cost tracking
    sessionCost = 0;
    costTracker;
    // Managers
    modeManager;
    sandboxManager;
    contextManager;
    sessionStore;
    // Tool selection state
    lastToolSelection = null;
    // Abort controller for cancellation
    abortController = null;
    constructor(options = {}) {
        super();
        // Merge config with defaults
        this.config = { ...DEFAULT_AGENT_CONFIG, ...options };
        // Apply YOLO mode if set in environment or options
        if (process.env.YOLO_MODE === "true" || options.yoloMode) {
            this.config = { ...this.config, ...YOLO_CONFIG };
        }
        // Apply MAX_COST from environment
        if (process.env.MAX_COST) {
            const maxCost = parseFloat(process.env.MAX_COST);
            if (!isNaN(maxCost) && maxCost > 0) {
                this.config.sessionCostLimit = maxCost;
            }
        }
        // Initialize managers - use existing singleton instances
        this.costTracker = getCostTracker();
        this.modeManager = getAgentModeManager();
        this.sandboxManager = getSandboxManager();
        this.contextManager = createContextManager("grok-3-latest");
        this.sessionStore = getSessionStore();
    }
    // ============ Configuration Methods ============
    /**
     * Get current configuration
     */
    getConfig() {
        return { ...this.config };
    }
    /**
     * Update configuration
     */
    updateConfig(updates) {
        const oldConfig = { ...this.config };
        this.config = { ...this.config, ...updates };
        this.emit("config:updated", { old: oldConfig, new: this.config });
    }
    /**
     * Get max tool rounds
     */
    getMaxToolRounds() {
        return this.config.maxToolRounds;
    }
    /**
     * Set max tool rounds
     */
    setMaxToolRounds(rounds) {
        this.config.maxToolRounds = rounds;
    }
    // ============ YOLO Mode Methods ============
    /**
     * Enable or disable YOLO mode
     */
    setYoloMode(enabled) {
        if (enabled) {
            this.updateConfig(YOLO_CONFIG);
        }
        else {
            this.updateConfig({
                maxToolRounds: DEFAULT_AGENT_CONFIG.maxToolRounds,
                sessionCostLimit: DEFAULT_AGENT_CONFIG.sessionCostLimit,
                yoloMode: false,
            });
        }
        this.emit("yolo:changed", enabled);
    }
    /**
     * Check if YOLO mode is enabled
     */
    isYoloModeEnabled() {
        return this.config.yoloMode;
    }
    // ============ Cost Tracking Methods ============
    /**
     * Get current session cost
     */
    getSessionCost() {
        return this.sessionCost;
    }
    /**
     * Get session cost limit
     */
    getSessionCostLimit() {
        return this.config.sessionCostLimit;
    }
    /**
     * Set session cost limit
     */
    setSessionCostLimit(limit) {
        this.config.sessionCostLimit = limit;
        this.emit("costLimit:changed", limit);
    }
    /**
     * Check if session cost limit has been reached
     */
    isSessionCostLimitReached() {
        return this.sessionCost >= this.config.sessionCostLimit;
    }
    /**
     * Record cost for current request
     */
    recordSessionCost(inputTokens, outputTokens, model) {
        const cost = this.costTracker.calculateCost(inputTokens, outputTokens, model);
        this.sessionCost += cost;
        this.costTracker.recordUsage(inputTokens, outputTokens, model);
        this.emit("cost:recorded", { cost, total: this.sessionCost });
        if (this.isSessionCostLimitReached()) {
            this.emit("cost:limitReached", this.sessionCost);
        }
    }
    /**
     * Format cost status for display
     */
    formatCostStatus() {
        const limitStr = this.config.sessionCostLimit === Infinity
            ? "unlimited"
            : `$${this.config.sessionCostLimit.toFixed(2)}`;
        const modeStr = this.config.yoloMode ? "YOLO" : "Safe";
        return `${modeStr} | Session: $${this.sessionCost.toFixed(4)} / ${limitStr} | Rounds: ${this.config.maxToolRounds} max`;
    }
    /**
     * Get the cost tracker
     */
    getCostTracker() {
        return this.costTracker;
    }
    // ============ Mode Methods ============
    /**
     * Get current mode
     */
    getMode() {
        return this.modeManager.getMode();
    }
    /**
     * Set mode
     */
    setMode(mode) {
        this.modeManager.setMode(mode);
        this.emit("mode:changed", mode);
    }
    /**
     * Get mode status
     */
    getModeStatus() {
        return this.modeManager.formatModeStatus();
    }
    /**
     * Check if tool is allowed in current mode
     */
    isToolAllowedInCurrentMode(toolName) {
        return this.modeManager.isToolAllowed(toolName);
    }
    /**
     * Get the mode manager
     */
    getModeManager() {
        return this.modeManager;
    }
    // ============ Sandbox Methods ============
    /**
     * Get sandbox status
     */
    getSandboxStatus() {
        return this.sandboxManager.formatStatus();
    }
    /**
     * Validate a command in sandbox
     */
    validateCommand(command) {
        return this.sandboxManager.validateCommand(command);
    }
    /**
     * Get the sandbox manager
     */
    getSandboxManager() {
        return this.sandboxManager;
    }
    // ============ Context Methods ============
    /**
     * Get context statistics
     */
    getContextStats(messages) {
        // Cast to expected type - context manager expects CodeBuddyMessage[]
        return this.contextManager.getStats(messages);
    }
    /**
     * Format context stats as a readable string
     */
    formatContextStats(messages) {
        const stats = this.contextManager.getStats(messages);
        const status = stats.isCritical
            ? "Critical"
            : stats.isNearLimit
                ? "Warning"
                : "Normal";
        return `Context: ${stats.totalTokens}/${stats.maxTokens} tokens (${stats.usagePercent.toFixed(1)}%) ${status} | Messages: ${stats.messageCount} | Summaries: ${stats.summarizedSessions}`;
    }
    /**
     * Update context manager configuration
     */
    updateContextConfig(config) {
        this.contextManager.updateConfig(config);
    }
    /**
     * Get the context manager
     */
    getContextManager() {
        return this.contextManager;
    }
    // ============ Session Methods ============
    /**
     * Save current session
     */
    saveCurrentSession(chatHistory) {
        return this.sessionStore.updateCurrentSession(chatHistory);
    }
    /**
     * Get session list
     */
    getSessionList() {
        return this.sessionStore.formatSessionList();
    }
    /**
     * Export current session
     */
    exportCurrentSession(outputPath) {
        const currentId = this.sessionStore.getCurrentSessionId();
        if (!currentId)
            return null;
        return this.sessionStore.exportSessionToFile(currentId, outputPath);
    }
    /**
     * Get the session store
     */
    getSessionStore() {
        return this.sessionStore;
    }
    // ============ Parallel Execution Methods ============
    /**
     * Enable or disable parallel tool execution
     */
    setParallelToolExecution(enabled) {
        this.config.parallelToolExecution = enabled;
        this.emit("parallel:changed", enabled);
    }
    /**
     * Check if parallel tool execution is enabled
     */
    isParallelToolExecutionEnabled() {
        return this.config.parallelToolExecution;
    }
    // ============ RAG Tool Selection Methods ============
    /**
     * Enable or disable RAG tool selection
     */
    setRAGToolSelection(enabled) {
        this.config.ragToolSelection = enabled;
        this.emit("rag:changed", enabled);
    }
    /**
     * Check if RAG tool selection is enabled
     */
    isRAGToolSelectionEnabled() {
        return this.config.ragToolSelection;
    }
    /**
     * Set the last tool selection result
     */
    setLastToolSelection(selection) {
        this.lastToolSelection = selection;
    }
    /**
     * Get the last tool selection result
     */
    getLastToolSelection() {
        return this.lastToolSelection;
    }
    // ============ Abort Control Methods ============
    /**
     * Create a new abort controller
     */
    createAbortController() {
        this.abortController = new AbortController();
        return this.abortController;
    }
    /**
     * Get the current abort controller
     */
    getAbortController() {
        return this.abortController;
    }
    /**
     * Abort the current operation
     */
    abortCurrentOperation() {
        if (this.abortController) {
            this.abortController.abort();
            this.emit("operation:aborted");
        }
    }
    /**
     * Clear the abort controller
     */
    clearAbortController() {
        this.abortController = null;
    }
    /**
     * Check if operation was aborted
     */
    isAborted() {
        return this.abortController?.signal.aborted ?? false;
    }
    // ============ Cleanup Methods ============
    /**
     * Dispose all resources
     */
    dispose() {
        // Abort any ongoing operations
        this.abortCurrentOperation();
        this.abortController = null;
        // Clean up context manager
        this.contextManager.dispose();
        // Clear state
        this.sessionCost = 0;
        this.lastToolSelection = null;
        this.emit("disposed");
    }
}
//# sourceMappingURL=agent-state.js.map