import { PassThrough } from 'stream';
let primedStdioInput = null;
let primedStdioInputStarted = false;
let primedStdioInputReady = false;
let primedStdioInputEnded = false;
const primedStdioChunks = [];
export function primeMcpStdioInput() {
    if (primedStdioInputStarted || process.stdin.isTTY)
        return;
    primedStdioInputStarted = true;
    process.stdin.on('data', (chunk) => {
        const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
        if (primedStdioInput && primedStdioInputReady) {
            primedStdioInput.write(buffer);
            return;
        }
        primedStdioChunks.push(buffer);
    });
    process.stdin.on('end', () => {
        primedStdioInputEnded = true;
        if (primedStdioInput && primedStdioInputReady)
            primedStdioInput.end();
    });
    process.stdin.on('error', (error) => primedStdioInput?.destroy(error));
    process.stdin.resume();
}
export function getMcpStdioInput() {
    if (primedStdioInputStarted && !primedStdioInput) {
        primedStdioInput = new PassThrough();
    }
    return primedStdioInput ?? process.stdin;
}
export function flushPrimedMcpStdioInput() {
    if (!primedStdioInput)
        return;
    primedStdioInputReady = true;
    for (const chunk of primedStdioChunks.splice(0)) {
        primedStdioInput.write(chunk);
    }
    if (primedStdioInputEnded)
        primedStdioInput.end();
}
if (process.argv[2] === 'mcp') {
    primeMcpStdioInput();
}
