"use strict";
/**
 * @author NovaStepStudios
 * @alias StepnickaSantiago
 * @license Apache-2.0
 * @link https://www.apache.org/licenses/LICENSE-2.0
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadLoggingXml = downloadLoggingXml;
const https_1 = __importDefault(require("https"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const VERSION_MANIFEST_URL = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json";
async function download(url, timeout = 15000) {
    return new Promise((resolve, reject) => {
        const req = https_1.default.get(url, (res) => {
            if (res.statusCode !== 200) {
                reject(new Error(`Failed to download ${url}, status code: ${res.statusCode}`));
                res.resume();
                return;
            }
            const data = [];
            res.on("data", (chunk) => data.push(chunk));
            res.on("end", () => resolve(Buffer.concat(data)));
        });
        req.on("error", reject);
        req.setTimeout(timeout, () => {
            req.destroy(new Error(`Request timeout after ${timeout}ms for ${url}`));
        });
    });
}
async function downloadLoggingXml(versionId, root, outputFolder) {
    if (!root)
        throw new Error("Se debe pasar el parámetro root");
    try {
        console.log(`Descargando manifiesto de versiones...`);
        const manifestData = await download(VERSION_MANIFEST_URL);
        const manifest = JSON.parse(manifestData.toString());
        const manifestCachePath = path_1.default.join(root, "cache", "json");
        fs_1.default.mkdirSync(manifestCachePath, { recursive: true });
        const manifestFile = path_1.default.join(manifestCachePath, "manifest_v2.json");
        fs_1.default.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2));
        console.log(`Manifest guardado en: ${manifestFile}`);
        const versionInfo = manifest.versions.find((v) => v.id === versionId);
        if (!versionInfo)
            throw new Error(`Versión ${versionId} no encontrada en el manifiesto`);
        console.log(`Descargando JSON de la versión ${versionId}...`);
        const versionJsonData = await download(versionInfo.url);
        const versionJson = JSON.parse(versionJsonData.toString());
        if (!versionJson.logging?.client?.file) {
            console.log(`Versión ${versionId} no tiene logging XML. Saltando...`);
            return null;
        }
        const { url: xmlUrl, id: xmlName, size: xmlSize } = versionJson.logging.client.file;
        outputFolder = outputFolder || path_1.default.join(root, "logging");
        fs_1.default.mkdirSync(outputFolder, { recursive: true });
        console.log(`Directorio creado: ${outputFolder}`);
        console.log(`Descargando archivo XML de logging: ${xmlName} desde ${xmlUrl}...`);
        const xmlData = await download(xmlUrl);
        if (xmlData.length !== xmlSize) {
            console.log(`Tamaño del XML inesperado. Recibido: ${xmlData.length}, Esperado: ${xmlSize}. Saltando...`);
            return null;
        }
        const outputPath = path_1.default.join(outputFolder, xmlName);
        fs_1.default.writeFileSync(outputPath, xmlData);
        console.log(`Archivo XML guardado en: ${outputPath}`);
        return outputPath;
    }
    catch (error) {
        console.log(`Error al descargar logging XML para ${versionId}: ${error.message}`);
        console.log(`Continuando sin el archivo XML...`);
        return null;
    }
}
