"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleAskInput = handleAskInput;
const config_1 = require("./config");
const markdown_1 = require("./markdown");
const terminal_1 = require("./terminal");
function muteConsoleLogs() {
    const originalLog = console.log;
    const originalInfo = console.info;
    const originalDebug = console.debug;
    const originalWarn = console.warn;
    const noop = () => { };
    console.log = noop;
    console.info = noop;
    console.debug = noop;
    console.warn = noop;
    return () => {
        console.log = originalLog;
        console.info = originalInfo;
        console.debug = originalDebug;
        console.warn = originalWarn;
    };
}
async function askTransactionConfirmation(rl, writer) {
    while (true) {
        const answer = (await rl.question((0, terminal_1.colorize)("Approve this transaction? [Y/n] ", terminal_1.ansi.yellow, terminal_1.ansi.bold)))
            .trim()
            .toLowerCase();
        if (answer.length === 0 || answer === "y" || answer === "yes") {
            return true;
        }
        if (answer === "n" || answer === "no") {
            return false;
        }
        (0, terminal_1.logLine)("warn", "Please answer with y or n.", writer);
    }
}
async function handleAskInput(sdk, state, userInput, rl) {
    const metadata = (0, config_1.profileToMetadata)(state.profile);
    const startedAt = Date.now();
    const rawWrite = console.log.bind(console);
    const writer = (line) => {
        rawWrite(line);
    };
    (0, terminal_1.logLine)("info", "Processing request...", writer);
    let stepCount = 0;
    const restoreConsole = state.debug ? () => { } : muteConsoleLogs();
    try {
        const result = await sdk.ask({
            userQuery: userInput,
            sessionId: state.sessionId,
            metadata,
            transactionConfirmationMode: state.confirmTransactions ? "on" : "off",
            onTransactionConfirmation: async (request) => {
                (0, terminal_1.printTransactionConfirmationCard)(request, writer);
                const approved = await askTransactionConfirmation(rl, writer);
                if (approved) {
                    (0, terminal_1.logLine)("ok", "Transaction approved by user.", writer);
                }
                else {
                    (0, terminal_1.logLine)("warn", "Transaction rejected by user.", writer);
                }
                return approved;
            },
            onStep: (step) => {
                if (!(0, terminal_1.shouldShowToolStep)(step, state.debug)) {
                    return;
                }
                stepCount += 1;
                if (stepCount === 1) {
                    (0, terminal_1.logLine)("info", "Tool activity:", writer);
                }
                (0, terminal_1.printToolStep)(step, stepCount, { debug: state.debug }, writer);
            },
        });
        restoreConsole();
        state.sessionId = result.sessionId;
        const elapsedSeconds = ((Date.now() - startedAt) / 1000).toFixed(1);
        (0, terminal_1.logLine)("ok", `Response ready in ${elapsedSeconds}s.`, writer);
        console.log((0, markdown_1.renderMarkdownForTerminal)(result.finalText));
        console.log("");
    }
    catch (error) {
        restoreConsole();
        throw error;
    }
}
