"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPIF = createPIF;
exports.spawnSortProcess = spawnSortProcess;
exports.getOutputFilename = getOutputFilename;
exports.waitForProcessClose = waitForProcessClose;
const child_process_1 = require("child_process");
const path_1 = __importDefault(require("path"));
const cigar_utils_1 = require("./cigar-utils");
const file_utils_1 = require("./file-utils");
async function createPIF(filename, stream) {
    const rl1 = filename ? (0, file_utils_1.getReadline)(filename) : (0, file_utils_1.getStdReadline)();
    const writeWithBackpressure = (0, file_utils_1.createWriteWithBackpressure)(stream);
    // Process the file line by line with backpressure handling
    try {
        for await (const line of rl1) {
            const [c1, l1, s1, e1, strand, c2, l2, s2, e2, ...rest] = line.split('\t');
            // Write the first line and handle backpressure
            await writeWithBackpressure(`${[`t${c2}`, l2, s2, e2, strand, c1, l1, s1, e1, ...rest].join('\t')}\n`);
            const cigarIdx = rest.findIndex(f => f.startsWith('cg:Z'));
            const CIGAR = rest[cigarIdx];
            if (CIGAR) {
                rest[cigarIdx] = `cg:Z:${strand === '-'
                    ? (0, cigar_utils_1.flipCigar)((0, cigar_utils_1.parseCigar)(CIGAR.slice(5))).join('')
                    : (0, cigar_utils_1.swapIndelCigar)(CIGAR.slice(5))}`;
            }
            // Write the second line and handle backpressure
            await writeWithBackpressure(`${[`q${c1}`, l1, s1, e1, strand, c2, l2, s2, e2, ...rest].join('\t')}\n`);
        }
    }
    catch (error) {
        console.error('Error processing PAF file:', error);
        throw error;
    }
    finally {
        rl1.close();
    }
}
function spawnSortProcess(outputFile, useCsi) {
    // Use a more portable approach to avoid E2BIG errors
    const sortCmd = `sort -t"\`printf '\\t'\`" -k1,1 -k3,3n`;
    const bgzipCommand = `bgzip > "${outputFile}"`;
    const tabixCommand = `tabix ${useCsi ? '-C ' : ''}-s1 -b3 -e4 -0 "${outputFile}"`;
    const fullCommand = `${sortCmd} | ${bgzipCommand}; ${tabixCommand}`;
    const minimalEnv = {
        ...process.env,
        LC_ALL: 'C',
    };
    return (0, child_process_1.spawn)('sh', ['-c', fullCommand], {
        env: minimalEnv,
        stdio: ['pipe', process.stdout, process.stderr],
    });
}
function getOutputFilename(file, out) {
    return out || `${path_1.default.basename(file || 'output', '.paf')}.pif.gz`;
}
async function waitForProcessClose(child) {
    return new Promise(resolve => {
        child.on('close', resolve);
    });
}
