"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var system_commands_exports = {};
__export(system_commands_exports, {
  systemCommands: () => systemCommands
});
module.exports = __toCommonJS(system_commands_exports);
var import_command_parser = require("../command-parser.js");
var import_format_output = require("../utils/format-output.js");
var import_command_output = require("../utils/command-output.js");
const validLevels = [
  "error",
  "warn",
  "info",
  "debug",
  "silly"
];
const validLevelSet = new Set(validLevels);
const isLogLevel = (value) => validLevelSet.has(value);
const systemCommands = [
  {
    name: "log",
    description: "View or change log level interactively",
    usage: "/log [level]",
    category: "System",
    aliases: [],
    handler: async (args, agent, ctx) => {
      try {
        const level = args[0];
        if (!level) {
          const currentLevel = agent.logger.getLevel();
          const logFile = agent.logger.getLogFilePath();
          const styledData = {
            currentLevel,
            logFile,
            availableLevels: [...validLevels]
          };
          const fallbackLines = [
            "Logging Configuration:",
            `  Current level: ${currentLevel}`,
            logFile ? `  Log file: ${logFile}` : "",
            `  Available levels: ${validLevels.join(", ")}`,
            "  Use /log <level> to change level"
          ].filter(Boolean);
          return import_command_output.CommandOutputHelper.styled(
            "log-config",
            styledData,
            fallbackLines.join("\n")
          );
        }
        if (isLogLevel(level)) {
          await agent.setLogLevel(
            level,
            ctx.sessionId ? { sessionId: ctx.sessionId } : void 0
          );
          return (0, import_format_output.formatForInkCli)(`\u2705 Log level set to ${level}`);
        }
        const errorMsg = `\u274C Invalid log level: ${level}
Valid levels: ${validLevels.join(
          ", "
        )}`;
        return (0, import_format_output.formatForInkCli)(errorMsg);
      } catch (error) {
        const errorMsg = `Failed to update log level: ${error instanceof Error ? error.message : String(error)}`;
        agent.logger.error(errorMsg);
        return (0, import_format_output.formatForInkCli)(`\u274C ${errorMsg}`);
      }
    }
  },
  {
    name: "config",
    description: "Show current configuration",
    usage: "/config",
    category: "System",
    handler: async (_args, agent, ctx) => {
      try {
        const config = agent.getEffectiveConfig();
        const servers = Object.keys(config.mcpServers || {});
        const hooksEnabled = agent.services.hookManager.getHookNames();
        const configFilePath = ctx.configFilePath ?? null;
        const styledData = {
          configFilePath,
          provider: config.llm.provider,
          model: config.llm.model,
          maxTokens: config.llm.maxOutputTokens ?? null,
          temperature: config.llm.temperature ?? null,
          permissionsMode: config.permissions.mode,
          maxSessions: config.sessions?.maxSessions?.toString() || "Default",
          sessionTTL: config.sessions?.sessionTTL ? `${config.sessions.sessionTTL / 1e3}s` : "Default",
          mcpServers: servers,
          promptsCount: config.prompts?.length || 0,
          hooksEnabled
        };
        const fallbackLines = [
          "Configuration:",
          configFilePath ? `  Config: ${configFilePath}` : "",
          `  LLM: ${config.llm.provider} / ${config.llm.model}`,
          `  Permissions: ${styledData.permissionsMode}`,
          `  Sessions: max=${styledData.maxSessions}, ttl=${styledData.sessionTTL}`,
          `  MCP Servers: ${servers.length > 0 ? servers.join(", ") : "none"}`,
          `  Prompts: ${styledData.promptsCount}`,
          `  Hooks: ${hooksEnabled.length > 0 ? hooksEnabled.join(", ") : "none"}`
        ].filter(Boolean);
        return import_command_output.CommandOutputHelper.styled("config", styledData, fallbackLines.join("\n"));
      } catch (error) {
        const errorMsg = `Failed to get configuration: ${error instanceof Error ? error.message : String(error)}`;
        agent.logger.error(errorMsg);
        return (0, import_format_output.formatForInkCli)(`\u274C ${errorMsg}`);
      }
    }
  },
  {
    name: "stats",
    description: "Show system statistics",
    usage: "/stats",
    category: "System",
    handler: async (_args, agent, ctx) => {
      try {
        const sessionStats = await agent.sessionManager.getSessionStats();
        const connectedServers = agent.getMcpClients().size;
        const failedConnections = Object.keys(agent.getMcpFailedConnections()).length;
        let toolCount = 0;
        try {
          const tools = await agent.getAllMcpTools();
          toolCount = Object.keys(tools).length;
        } catch {
        }
        let tokenUsage;
        let estimatedCost;
        if (ctx.sessionId) {
          const sessionMetadata = await agent.sessionManager.getSessionMetadata(
            ctx.sessionId
          );
          if (sessionMetadata?.tokenUsage) {
            tokenUsage = sessionMetadata.tokenUsage;
          }
          estimatedCost = sessionMetadata?.estimatedCost;
        }
        const styledData = {
          sessions: {
            total: sessionStats.totalSessions,
            inMemory: sessionStats.inMemorySessions,
            maxAllowed: sessionStats.maxSessions
          },
          mcp: {
            connected: connectedServers,
            failed: failedConnections,
            toolCount
          },
          ...tokenUsage && { tokenUsage },
          ...estimatedCost !== void 0 && { estimatedCost }
        };
        const fallbackLines = [
          "System Statistics:",
          `  Sessions: ${sessionStats.totalSessions} total, ${sessionStats.inMemorySessions} in memory`,
          `  MCP: ${connectedServers} connected, ${toolCount} tools`
        ];
        if (failedConnections > 0) {
          fallbackLines.push(`  Failed connections: ${failedConnections}`);
        }
        if (tokenUsage) {
          fallbackLines.push(
            `  Tokens: ${tokenUsage.totalTokens} total (${tokenUsage.inputTokens} in, ${tokenUsage.outputTokens} out)`
          );
        }
        return import_command_output.CommandOutputHelper.styled("stats", styledData, fallbackLines.join("\n"));
      } catch (error) {
        const errorMsg = `Failed to get statistics: ${error instanceof Error ? error.message : String(error)}`;
        agent.logger.error(errorMsg);
        return (0, import_format_output.formatForInkCli)(`\u274C ${errorMsg}`);
      }
    }
  },
  {
    name: "stream",
    description: "Toggle streaming mode for LLM responses",
    usage: "/stream",
    category: "System",
    handler: async (_args, _agent, _ctx) => {
      return true;
    }
  },
  {
    name: "reasoning",
    description: "Configure reasoning display and budget tokens",
    usage: "/reasoning",
    category: "Model",
    handler: import_command_parser.overlayOnlyHandler
  },
  {
    name: "sounds",
    description: "Configure sound notifications",
    usage: "/sounds",
    category: "System",
    handler: import_command_parser.overlayOnlyHandler
  }
];
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  systemCommands
});
