import { randomUUID } from "node:crypto";
import { PiboSessionRouter } from "../core/session-router.js";
import { createDefaultPiboPluginRegistry } from "../plugins/builtin.js";
import { getDefaultPiboWorkspace } from "../core/workspace.js";
import { InMemoryPiboSessionStore, } from "../sessions/store.js";
export const LOCAL_TUI_CHANNEL_NAME = "local-tui";
export class LocalRoutedTuiClient {
    router;
    piboSession;
    capabilities;
    unsubscribe;
    eventListeners = new Set();
    closed = false;
    constructor(router, piboSession, capabilities) {
        this.router = router;
        this.piboSession = piboSession;
        this.capabilities = capabilities;
        this.unsubscribe = router.subscribe((event) => {
            if (event.piboSessionId !== this.piboSession.id)
                return;
            for (const listener of this.eventListeners) {
                listener(event);
            }
        });
    }
    onEvent(listener) {
        this.eventListeners.add(listener);
        return () => this.eventListeners.delete(listener);
    }
    sendMessage(text) {
        return this.router.emit({
            type: "message",
            piboSessionId: this.piboSession.id,
            id: randomUUID(),
            text,
            source: "ui",
        });
    }
    sendExecution(action, params) {
        const event = params === undefined
            ? { type: "execution", piboSessionId: this.piboSession.id, id: randomUUID(), action }
            : { type: "execution", piboSessionId: this.piboSession.id, id: randomUUID(), action, params };
        return this.router.emit(event);
    }
    async close() {
        if (this.closed)
            return;
        this.closed = true;
        this.unsubscribe();
        this.eventListeners.clear();
        await this.router.disposeAll();
    }
}
export function createLocalRoutedTuiClient(options = {}) {
    const registry = options.pluginRegistry ?? createDefaultPiboPluginRegistry();
    const profileName = registry.resolveProfileName(options.profile ?? "pibo-minimal");
    const profile = registry.createProfile(profileName);
    const sessionName = options.sessionName ?? "default";
    const workspace = options.cwd ?? getDefaultPiboWorkspace();
    const sessionStore = new InMemoryPiboSessionStore();
    const piboSession = sessionStore.create({
        channel: LOCAL_TUI_CHANNEL_NAME,
        kind: "local",
        profile: profileName,
        title: sessionName,
        workspace,
    });
    const router = new PiboSessionRouter({
        cwd: workspace,
        persistSession: options.persistSession,
        thinkingLevel: options.thinkingLevel,
        pluginRegistry: registry,
        profile,
        sessionStore,
    });
    return new LocalRoutedTuiClient(router, piboSession, { actions: registry.getGatewayActionInfos() });
}
