"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveLocalAppPackageRootAbs = resolveLocalAppPackageRootAbs;
const promises_1 = __importDefault(require("node:fs/promises"));
const node_path_1 = __importDefault(require("node:path"));
const app_id_1 = require("./app-id");
async function dirExists(dirPathAbs) {
    try {
        const stat = await promises_1.default.stat(dirPathAbs);
        return stat.isDirectory();
    }
    catch (err) {
        const isEnoent = typeof err === 'object' &&
            err !== null &&
            'code' in err &&
            err.code === 'ENOENT';
        if (isEnoent)
            return false;
        throw err;
    }
}
async function resolveLocalAppPackageRootAbs(params) {
    const candidates = new Set();
    const trimmedAppId = params.appId.trim();
    if (trimmedAppId === '')
        return null;
    if (params.previousResolutionEntry?.source.kind === 'local') {
        candidates.add(params.previousResolutionEntry.source.pathAbs);
    }
    for (const root of params.localRoots) {
        const rootAbs = node_path_1.default.isAbsolute(root) ? root : node_path_1.default.resolve(params.rtwsRootAbs, root);
        candidates.add((0, app_id_1.resolveDomindsAppLocalPackageRootAbs)(rootAbs, trimmedAppId));
    }
    for (const candidateAbs of candidates) {
        if (await dirExists(candidateAbs))
            return candidateAbs;
    }
    return null;
}
