"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readPackageInfo = readPackageInfo;
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
function isRecord(v) {
    return typeof v === 'object' && v !== null && !Array.isArray(v);
}
async function readPackageInfo(params) {
    const fallback = {
        packageName: null,
        packageVersion: null,
        manifestRelPath: '.minds/app.yaml',
    };
    const pkgJsonAbs = path_1.default.resolve(params.packageRootAbs, 'package.json');
    let raw;
    try {
        raw = await promises_1.default.readFile(pkgJsonAbs, 'utf-8');
    }
    catch (err) {
        const isEnoent = typeof err === 'object' &&
            err !== null &&
            'code' in err &&
            err.code === 'ENOENT';
        if (isEnoent)
            return fallback;
        throw err;
    }
    let parsed;
    try {
        parsed = JSON.parse(raw);
    }
    catch {
        return fallback;
    }
    if (!isRecord(parsed))
        return fallback;
    const name = typeof parsed['name'] === 'string' ? parsed['name'].trim() : '';
    const version = typeof parsed['version'] === 'string' ? parsed['version'].trim() : '';
    let manifestRelPath = '.minds/app.yaml';
    const dominds = parsed['dominds'];
    if (isRecord(dominds)) {
        const mr = typeof dominds['appManifest'] === 'string' ? dominds['appManifest'].trim() : '';
        if (mr !== '')
            manifestRelPath = mr;
    }
    return {
        packageName: name !== '' ? name : null,
        packageVersion: version !== '' ? version : null,
        manifestRelPath,
    };
}
