import process from "node:process";
import { createStdinDriver, createStdoutRenderer, createTerminalApp, } from "@simon_he/vue-tui";
import { createGoatChainRouter, GoatChainShell } from "goatchain-cli";
import { createGoatChainBridge, resolveInitialGoatChainThread, } from "./goatchain-adapter.js";
import { createCliRuntime } from "./runtime.js";
function createCliApp(options) {
    const app = createTerminalApp({
        cols: options.cols,
        component: options.component,
        defaultStyle: options.defaultStyle,
        props: options.props,
        rows: options.rows,
    });
    options.install?.(app.app);
    app.mount();
    return {
        app: app.app,
        dispose: app.dispose,
        events: app.events,
        getImeAnchor: app.getImeAnchor,
        scheduler: app.scheduler,
        terminal: app.terminal,
    };
}
function createNoopToolRunner() {
    return async (call) => ({
        id: String(call?.id ?? "tool"),
        output: `Tool execution stays inside the best-agent runtime. "${String(call?.name ?? "tool")}" cannot be re-run locally from the TUI shell.`,
        status: "error",
    });
}
export async function runGoatChainTuiChat(options) {
    const runtime = await createCliRuntime(options);
    const initialThread = await resolveInitialGoatChainThread(runtime, options);
    const bridge = createGoatChainBridge({
        agentProfile: options.agentProfile,
        runtime,
        threadMode: options.threadMode,
    });
    const initialMessages = await bridge.hydrateThread(initialThread.id);
    const cols = Number.isFinite(process.stdout?.columns) ? process.stdout.columns : 120;
    const rows = Number.isFinite(process.stdout?.rows) ? process.stdout.rows : 32;
    const componentProps = {
        agent: bridge.agent,
        context: {
            cwd: initialThread.cwd,
            env: { ...process.env },
            system: "You are best-agent running inside an interactive terminal UI. Keep answers concise, tool-grounded, and focused on the current workspace.",
        },
        onStoreCreated: (store) => {
            bridge.attachStore(store);
            store.state.context = {
                ...store.state.context,
                cwd: initialThread.cwd,
            };
            store.state.messages = initialMessages;
            store.state.sessionId = initialThread.id;
        },
        sessions: bridge.sessions,
        toolRunner: createNoopToolRunner(),
        tools: "real",
    };
    const app = createCliApp({
        cols,
        component: GoatChainShell,
        defaultStyle: { bg: "black", fg: "whiteBright" },
        install(vueApp) {
            vueApp.use(createGoatChainRouter({ initialRoute: "chat" }));
        },
        props: componentProps,
        rows,
    });
    const renderer = createStdoutRenderer(app.terminal, {
        altScreen: true,
        defaultBg: "black",
        hideCursor: true,
        output: process.stdout,
        palette: { blackBright: "#262626" },
        trackResize: true,
    });
    const commitListener = app.terminal.on("commit", () => {
        const anchor = app.getImeAnchor();
        if (!anchor) {
            return;
        }
        renderer.setCursor(Math.floor(anchor.cellX), Math.floor(anchor.cellY));
    });
    await Promise.resolve();
    app.scheduler.flush();
    await new Promise((resolve) => {
        let cleanedUp = false;
        let driver = null;
        const cleanup = () => {
            if (cleanedUp) {
                return;
            }
            cleanedUp = true;
            process.off("SIGINT", cleanup);
            driver?.dispose();
            commitListener();
            renderer.dispose();
            app.dispose();
            resolve();
        };
        driver = createStdinDriver({
            dispatch(event) {
                return app.events.dispatch(event);
            },
            enableMouse: true,
            onExit: cleanup,
        });
        process.on("SIGINT", cleanup);
    });
}
//# sourceMappingURL=goatchain-tui.js.map