"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveAppOverrideFileAbs = resolveAppOverrideFileAbs;
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
function normalizeRelNoTraversal(rel) {
    if (path_1.default.isAbsolute(rel))
        return null;
    const normalized = rel.replace(/\\/g, '/').replace(/^\/+/, '');
    if (normalized.includes('..'))
        return null;
    return normalized;
}
async function isRegularFile(filePathAbs) {
    try {
        const st = await promises_1.default.stat(filePathAbs);
        return st.isFile();
    }
    catch {
        return false;
    }
}
/**
 * Resolve an app asset override file path for a given app-relative file path.
 *
 * Priority order (read-time):
 * 1) `<rtws>/.apps/override/<app-id>/<rel>`
 * 2) `<integrator-app-root>/.apps/override/<app-id>/<rel>` (in provided order)
 */
async function resolveAppOverrideFileAbs(params) {
    const normalized = normalizeRelNoTraversal(params.appRelPath);
    if (!normalized)
        return { kind: 'none' };
    const preferredAbs = path_1.default.resolve(params.rtwsRootAbs, '.apps', 'override', params.appId, normalized);
    if (await isRegularFile(preferredAbs)) {
        return {
            kind: 'found',
            filePathAbs: preferredAbs,
            source: 'rtws_override',
            ownerAppId: null,
        };
    }
    const owners = params.appOverrideOwners ?? [];
    for (const owner of owners) {
        const candidateAbs = path_1.default.resolve(owner.packageRootAbs, '.apps', 'override', params.appId, normalized);
        if (await isRegularFile(candidateAbs)) {
            return {
                kind: 'found',
                filePathAbs: candidateAbs,
                source: 'app_override',
                ownerAppId: owner.appId,
            };
        }
    }
    return { kind: 'none' };
}
