"use strict";
/**
 * Zip Archive Extractor
 * Handles extraction of zip archives using Node.js built-in modules.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractZip = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const zlib = __importStar(require("zlib"));
const platform_detector_1 = require("../binary/platform-detector");
/**
 * Extract zip archive using Node.js (simple implementation)
 */
function extractZip(archivePath, destDir, verbose = false, backend = platform_detector_1.DEFAULT_BACKEND) {
    return new Promise((resolve, reject) => {
        const execName = (0, platform_detector_1.getExecutableName)(backend);
        const archiveBinaryName = (0, platform_detector_1.getArchiveBinaryName)(backend);
        const buffer = fs.readFileSync(archivePath);
        // Find End of Central Directory record (EOCD)
        let eocdOffset = buffer.length - 22;
        while (eocdOffset >= 0) {
            if (buffer.readUInt32LE(eocdOffset) === 0x06054b50)
                break;
            eocdOffset--;
        }
        if (eocdOffset < 0) {
            reject(new Error('Invalid ZIP file: EOCD not found'));
            return;
        }
        const centralDirOffset = buffer.readUInt32LE(eocdOffset + 16);
        let offset = centralDirOffset;
        while (offset < eocdOffset) {
            const sig = buffer.readUInt32LE(offset);
            if (sig !== 0x02014b50)
                break;
            const compressionMethod = buffer.readUInt16LE(offset + 10);
            const compressedSize = buffer.readUInt32LE(offset + 20);
            const uncompressedSize = buffer.readUInt32LE(offset + 24);
            const fileNameLength = buffer.readUInt16LE(offset + 28);
            const extraFieldLength = buffer.readUInt16LE(offset + 30);
            const commentLength = buffer.readUInt16LE(offset + 32);
            const localHeaderOffset = buffer.readUInt32LE(offset + 42);
            const fileName = buffer.toString('utf8', offset + 46, offset + 46 + fileNameLength);
            const baseName = path.basename(fileName);
            if (baseName === execName ||
                baseName === archiveBinaryName ||
                baseName === 'cli-proxy-api.exe') {
                const localOffset = localHeaderOffset;
                const localSig = buffer.readUInt32LE(localOffset);
                if (localSig !== 0x04034b50) {
                    reject(new Error('Invalid local file header'));
                    return;
                }
                const localFileNameLength = buffer.readUInt16LE(localOffset + 26);
                const localExtraLength = buffer.readUInt16LE(localOffset + 28);
                const dataOffset = localOffset + 30 + localFileNameLength + localExtraLength;
                let fileData;
                if (compressionMethod === 0) {
                    fileData = buffer.subarray(dataOffset, dataOffset + compressedSize);
                }
                else if (compressionMethod === 8) {
                    const compressed = buffer.subarray(dataOffset, dataOffset + compressedSize);
                    fileData = zlib.inflateRawSync(compressed);
                }
                else {
                    reject(new Error(`Unsupported compression method: ${compressionMethod}`));
                    return;
                }
                if (fileData.length !== uncompressedSize) {
                    reject(new Error('Decompression size mismatch'));
                    return;
                }
                const destPath = path.join(destDir, execName);
                fs.writeFileSync(destPath, fileData);
                if (verbose)
                    console.error(`[cliproxy] Extracted: ${fileName} -> ${destPath}`);
                resolve();
                return;
            }
            offset += 46 + fileNameLength + extraFieldLength + commentLength;
        }
        reject(new Error(`Executable not found in archive: ${execName}`));
    });
}
exports.extractZip = extractZip;
//# sourceMappingURL=zip-extractor.js.map