"use strict";
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.getAppVersionFromCatalog = exports.createNanoAppJsonFile = exports.getDeviceFirmwareVersion = exports.getNanoAppCatalog = exports.isTouchDevice = exports.getSpeculosModel = void 0;
const device_core_1 = require("@ledgerhq/device-core");
const package_json_1 = require("../../package.json");
const live_env_1 = require("@ledgerhq/live-env");
const devices_1 = require("@ledgerhq/devices");
const Device_1 = require("./enum/Device");
const index_1 = require("./index");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
function getSpeculosModel() {
    const speculosDevice = process.env.SPECULOS_DEVICE;
    switch (speculosDevice) {
        case Device_1.Device.LNS.name:
            return devices_1.DeviceModelId.nanoS;
        case Device_1.Device.LNX.name:
            return devices_1.DeviceModelId.nanoX;
        case Device_1.Device.STAX.name:
            return devices_1.DeviceModelId.stax;
        case Device_1.Device.FLEX.name:
        case devices_1.DeviceModelId.europa:
            return devices_1.DeviceModelId.europa;
        case Device_1.Device.NANO_GEN_5.name:
            return devices_1.DeviceModelId.apex;
        case Device_1.Device.LNSP.name:
        default:
            return devices_1.DeviceModelId.nanoSP;
    }
}
exports.getSpeculosModel = getSpeculosModel;
function isTouchDevice() {
    const model = getSpeculosModel();
    return (model === devices_1.DeviceModelId.stax || model === devices_1.DeviceModelId.europa || model === devices_1.DeviceModelId.apex);
}
exports.isTouchDevice = isTouchDevice;
function getDeviceTargetId(device) {
    const modelToTargetIdMap = {
        [devices_1.DeviceModelId.nanoS]: Device_1.Device.LNS.targetId,
        [devices_1.DeviceModelId.nanoX]: Device_1.Device.LNX.targetId,
        [devices_1.DeviceModelId.nanoSP]: Device_1.Device.LNSP.targetId,
        [devices_1.DeviceModelId.stax]: Device_1.Device.STAX.targetId,
        [devices_1.DeviceModelId.europa]: Device_1.Device.FLEX.targetId,
        [devices_1.DeviceModelId.apex]: Device_1.Device.NANO_GEN_5.targetId,
    };
    return modelToTargetIdMap[device];
}
async function getNanoAppCatalog(device, deviceFirmware) {
    const repository = new device_core_1.HttpManagerApiRepository((0, live_env_1.getEnv)("MANAGER_API_BASE"), package_json_1.version);
    const targetId = getDeviceTargetId(device);
    return await repository.catalogForDevice({
        provider: 1,
        targetId: targetId,
        firmwareVersion: deviceFirmware,
    });
}
exports.getNanoAppCatalog = getNanoAppCatalog;
const firmwareVersionCache = new Map();
async function getDeviceFirmwareVersion(device) {
    const cached = firmwareVersionCache.get(device);
    if (cached)
        return cached;
    const providerId = 1;
    const repository = new device_core_1.HttpManagerApiRepository((0, live_env_1.getEnv)("MANAGER_API_BASE"), package_json_1.version);
    const deviceVersion = await repository.getDeviceVersion({
        targetId: getDeviceTargetId(device),
        providerId,
    });
    const firmwareIds = deviceVersion.se_firmware_final_versions;
    if (!Array.isArray(firmwareIds) || firmwareIds.length === 0) {
        throw new Error(`No firmware versions found for device  ${device}`);
    }
    const firmwares = await Promise.all(firmwareIds.map(id => repository.getFinalFirmwareById(id)));
    // Only firmwares matching providerId
    const providerFirmwares = firmwares.filter(fw => Array.isArray(fw.providers) && fw.providers.includes(providerId));
    if (providerFirmwares.length === 0) {
        throw new Error(`No firmware versions found for device version ${deviceVersion.id} for device ${device}`);
    }
    // Latest is chosen by highest numeric ID
    const latestFirmware = providerFirmwares.reduce((latest, current) => current.id > latest.id ? current : latest);
    firmwareVersionCache.set(device, latestFirmware.version);
    process.env.SPECULOS_FIRMWARE_VERSION = latestFirmware.version;
    return latestFirmware.version;
}
exports.getDeviceFirmwareVersion = getDeviceFirmwareVersion;
async function createNanoAppJsonFile(nanoAppFilePath) {
    const jsonFilePath = path.resolve(process.cwd(), nanoAppFilePath);
    try {
        if (fs.existsSync(jsonFilePath)) {
            return; // File already exists
        }
        fs.mkdirSync(path.dirname(jsonFilePath), { recursive: true });
        const device = getSpeculosModel();
        const firmware = await getDeviceFirmwareVersion(device);
        const appCatalog = await getNanoAppCatalog(device, firmware);
        fs.writeFileSync(jsonFilePath, JSON.stringify(appCatalog, null, 2), "utf8");
    }
    catch (error) {
        console.error("Unable to create app version file:", (0, index_1.sanitizeError)(error));
    }
}
exports.createNanoAppJsonFile = createNanoAppJsonFile;
async function getAppVersionFromCatalog(currency, nanoAppFilePath) {
    const jsonFilePath = path.resolve(process.cwd(), nanoAppFilePath);
    try {
        await createNanoAppJsonFile(nanoAppFilePath);
        if (!fs.existsSync(jsonFilePath)) {
            console.error(`Catalog file not found: ${jsonFilePath}`);
            return;
        }
        const raw = fs.readFileSync(jsonFilePath, "utf8");
        const catalog = JSON.parse(raw);
        const app = catalog.find(entry => entry.versionDisplayName === currency);
        return app?.version ?? "";
    }
    catch (error) {
        console.error(`Unable to get app version for ${currency} from catalog:`, error);
    }
}
exports.getAppVersionFromCatalog = getAppVersionFromCatalog;
//# sourceMappingURL=speculosAppVersion.js.map