"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseSlashCommand = parseSlashCommand;
exports.handleSlashCommand = handleSlashCommand;
const logger_1 = require("../logger/logger");
const config_1 = require("./config");
const terminal_1 = require("./terminal");
const silent_1 = require("./silent");
function parseSlashCommand(line) {
    const trimmed = line.trim();
    if (!trimmed.startsWith("/")) {
        return null;
    }
    const raw = trimmed.slice(1).trim();
    if (raw.length === 0) {
        return { name: "help", rest: "" };
    }
    const splitIndex = raw.indexOf(" ");
    if (splitIndex === -1) {
        return { name: raw.toLowerCase(), rest: "" };
    }
    return {
        name: raw.slice(0, splitIndex).toLowerCase(),
        rest: raw.slice(splitIndex + 1).trim(),
    };
}
function splitFirstToken(value) {
    const trimmed = value.trim();
    if (trimmed.length === 0) {
        return ["", ""];
    }
    const splitIndex = trimmed.indexOf(" ");
    if (splitIndex === -1) {
        return [trimmed, ""];
    }
    return [trimmed.slice(0, splitIndex), trimmed.slice(splitIndex + 1).trim()];
}
function parseJsonSafely(rawJson) {
    try {
        return JSON.parse(rawJson);
    }
    catch (_a) {
        throw new Error("Invalid JSON. Example: /tool PriceTool {\"chainId\":1,\"tokenAddresses\":\"0x...\"}");
    }
}
async function handleSlashCommand(sdk, _rl, state, config, command, initializeSdk) {
    var _a;
    switch (command.name) {
        case "help":
            (0, terminal_1.printShellHelp)();
            return true;
        case "exit":
        case "quit":
            return false;
        case "tools": {
            const tools = sdk.listTools();
            tools.forEach((tool) => {
                const interactive = tool.isInteractive ? (0, terminal_1.colorize)(" [interactive]", terminal_1.ansi.yellow, terminal_1.ansi.bold) : "";
                console.log(`${(0, terminal_1.colorize)(tool.name, terminal_1.ansi.magenta, terminal_1.ansi.bold)}${interactive}`);
                if (tool.description.trim()) {
                    console.log((0, terminal_1.colorize)(`  ${tool.description}`, terminal_1.ansi.dim));
                }
            });
            return true;
        }
        case "tool": {
            const [toolName, rest] = splitFirstToken(command.rest);
            if (!toolName) {
                (0, terminal_1.logLine)("warn", "Usage: /tool <ToolName> [JSON]");
                return true;
            }
            const toolInput = rest.length > 0 ? parseJsonSafely(rest) : {};
            const result = await (0, silent_1.runSilently)(async () => sdk.executeTool(toolName, toolInput));
            (0, terminal_1.printToolResult)(result);
            return true;
        }
        case "debug": {
            const action = command.rest.trim().toLowerCase();
            if (!action || action === "show") {
                (0, terminal_1.logLine)("info", `Debug mode is ${state.debug ? "ON" : "OFF"}.`);
                return true;
            }
            if (action === "on" || action === "off") {
                state.debug = action === "on";
                logger_1.logger.level = state.debug ? "info" : "error";
                config.debug = state.debug;
                await (0, config_1.saveConfig)(config);
                (0, terminal_1.logLine)("ok", state.debug
                    ? "Debug mode enabled. Showing full internal logs and tool payloads."
                    : "Debug mode disabled. Showing concise tool activity.");
                return true;
            }
            (0, terminal_1.logLine)("warn", "Usage: /debug <on|off|show>");
            return true;
        }
        case "confirmmode": {
            const action = command.rest.trim().toLowerCase();
            if (!action || action === "show") {
                (0, terminal_1.logLine)("info", `Transaction confirmation mode is ${state.confirmTransactions ? "ON" : "OFF"}.`);
                return true;
            }
            if (action === "on" || action === "off") {
                state.confirmTransactions = action === "on";
                config.confirmTransactions = state.confirmTransactions;
                await (0, config_1.saveConfig)(config);
                (0, terminal_1.logLine)("ok", state.confirmTransactions
                    ? "Transaction confirmation mode enabled."
                    : "Transaction confirmation mode disabled.");
                return true;
            }
            (0, terminal_1.logLine)("warn", "Usage: /confirmmode <on|off|show>");
            return true;
        }
        case "profile":
            (0, terminal_1.printProfile)(state.profile, state.sessionId, state.debug, state.confirmTransactions);
            return true;
        case "set": {
            const [field, value] = splitFirstToken(command.rest);
            if (!field || !value) {
                (0, terminal_1.logLine)("warn", "Usage: /set <wallet|chain|blockchain|privatekey> <value>");
                return true;
            }
            const normalizedField = field.toLowerCase();
            if (normalizedField === "wallet") {
                state.profile.wallet = value;
            }
            else if (normalizedField === "chain") {
                state.profile.chain = value;
            }
            else if (normalizedField === "blockchain") {
                state.profile.blockchain = value;
            }
            else if (normalizedField === "privatekey" || normalizedField === "private_key") {
                state.profile.privateKey = value;
            }
            else {
                (0, terminal_1.logLine)("warn", "Supported fields: wallet, chain, blockchain, privatekey");
                return true;
            }
            config.profile = state.profile;
            await (0, config_1.saveConfig)(config);
            (0, terminal_1.logLine)("ok", `Updated ${normalizedField} and saved profile.`);
            return true;
        }
        case "session": {
            const action = command.rest.toLowerCase();
            if (!action || action === "show") {
                (0, terminal_1.logLine)("info", `Current session: ${(_a = state.sessionId) !== null && _a !== void 0 ? _a : "none"}`);
                return true;
            }
            if (action === "new") {
                state.sessionId = undefined;
                (0, terminal_1.logLine)("ok", "Started a new session context.");
                return true;
            }
            if (action === "history") {
                if (!state.sessionId) {
                    (0, terminal_1.logLine)("warn", "No active session.");
                    return true;
                }
                const history = sdk.getChatHistory(state.sessionId);
                console.log((0, terminal_1.colorize)(JSON.stringify(history, null, 2), terminal_1.ansi.dim));
                return true;
            }
            (0, terminal_1.logLine)("warn", "Usage: /session <show|new|history>");
            return true;
        }
        case "save":
            config.profile = state.profile;
            config.debug = state.debug;
            config.confirmTransactions = state.confirmTransactions;
            await (0, config_1.saveConfig)(config);
            (0, terminal_1.logLine)("ok", `Profile saved to ${config_1.CONFIG_PATH}`);
            return true;
        case "init":
            await initializeSdk(sdk);
            return true;
        case "clear":
            console.clear();
            (0, terminal_1.printBanner)();
            (0, terminal_1.printShellHelp)();
            return true;
        default:
            (0, terminal_1.logLine)("warn", `Unknown command: /${command.name}. Run /help`);
            return true;
    }
}
