"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getReadline = getReadline;
exports.getStdReadline = getStdReadline;
exports.createWriteWithBackpressure = createWriteWithBackpressure;
const fs_1 = __importDefault(require("fs"));
const readline_1 = __importDefault(require("readline"));
const zlib_1 = require("zlib");
function getReadline(filename) {
    const stream = fs_1.default.createReadStream(filename);
    return readline_1.default.createInterface({
        input: /.b?gz$/.exec(filename) ? stream.pipe((0, zlib_1.createGunzip)()) : stream,
    });
}
function getStdReadline() {
    return readline_1.default.createInterface({
        input: process.stdin,
    });
}
function createWriteWithBackpressure(stream) {
    return (data) => {
        // If the stream buffer is full (write returns false), we need to wait for drain
        if (!stream.write(data)) {
            return new Promise(resolve => {
                const drainHandler = () => {
                    stream.removeListener?.('drain', drainHandler);
                    resolve();
                };
                stream.once?.('drain', drainHandler);
            });
        }
        // If write returns true, the buffer is not full, so we can continue immediately
        return Promise.resolve();
    };
}
