import { buildEmberSystemPrompt } from '../../../../modules/ember-chat/services/emberSystemPrompt.js';
class AnswerRelay {
    target = null;
    bufferedChunks = [];
    terminal = null;
    attach(subscriber) {
        this.target = subscriber;
        subscriber.onStatus('working');
        for (const chunk of this.bufferedChunks) {
            subscriber.onChunk(chunk);
        }
        this.bufferedChunks.length = 0;
        if (this.terminal !== null) {
            this.flushTerminal(this.terminal);
        }
    }
    onChunk(text) {
        if (this.target === null) {
            this.bufferedChunks.push(text);
            return;
        }
        this.target.onChunk(text);
    }
    onDone() {
        const terminal = { kind: 'done' };
        if (this.target === null) {
            this.terminal = terminal;
            return;
        }
        this.flushTerminal(terminal);
    }
    onError(message) {
        const terminal = { kind: 'error', message };
        if (this.target === null) {
            this.terminal = terminal;
            return;
        }
        this.flushTerminal(terminal);
    }
    flushTerminal(terminal) {
        if (this.target === null) {
            return;
        }
        if (terminal.kind === 'done') {
            this.target.onStatus('idle');
            this.target.onDone();
            return;
        }
        this.target.onStatus('error');
        this.target.onError(terminal.message);
    }
}
export async function askEmber(message, dependencies) {
    if (dependencies.environment.hasAnthropicApiKey()) {
        return { status: 'billing-regression-prevented' };
    }
    const { readData, projectPath, transport } = dependencies;
    const systemPrompt = buildEmberSystemPrompt({
        reviewScores: await readData.reviewScores(projectPath),
        insights: await readData.insights(projectPath),
        jobHistory: await readData.jobHistory(projectPath),
        worktrees: await readData.worktrees(),
    });
    const relay = new AnswerRelay();
    const started = transport.start({ question: message.question, systemPrompt, projectPath }, relay);
    if (started.status === 'failed') {
        return { status: 'unavailable', reason: started.reason };
    }
    return {
        status: 'streaming',
        subscribe: (subscriber) => relay.attach(subscriber),
        cancel: () => started.run.cancel(),
    };
}
//# sourceMappingURL=askEmber.usecase.js.map