"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveStaticFilePath = resolveStaticFilePath;
exports.resolveWritableStaticFilePath = resolveWritableStaticFilePath;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const STATIC_SEGMENT = "static";
function uniquePaths(paths) {
    return [...new Set(paths)];
}
function staticDirectoryCandidates() {
    return uniquePaths([
        node_path_1.default.resolve(process.cwd(), "src", STATIC_SEGMENT),
        node_path_1.default.resolve(process.cwd(), "dist", "src", STATIC_SEGMENT),
        node_path_1.default.resolve(__dirname, "..", STATIC_SEGMENT),
    ]);
}
function isWritableDirectory(directoryPath) {
    try {
        node_fs_1.default.accessSync(directoryPath, node_fs_1.default.constants.W_OK);
        return true;
    }
    catch (_a) {
        return false;
    }
}
function resolveStaticFilePath(fileName) {
    for (const directoryPath of staticDirectoryCandidates()) {
        const candidatePath = node_path_1.default.join(directoryPath, fileName);
        if (node_fs_1.default.existsSync(candidatePath)) {
            return candidatePath;
        }
    }
    const checked = staticDirectoryCandidates().join(", ");
    throw new Error(`Unable to resolve static file "${fileName}". Checked: ${checked}`);
}
function resolveWritableStaticFilePath(fileName) {
    for (const directoryPath of staticDirectoryCandidates()) {
        if (node_fs_1.default.existsSync(directoryPath) && isWritableDirectory(directoryPath)) {
            return node_path_1.default.join(directoryPath, fileName);
        }
    }
    const fallbackDirectory = node_path_1.default.resolve(process.cwd(), "src", STATIC_SEGMENT);
    node_fs_1.default.mkdirSync(fallbackDirectory, { recursive: true });
    return node_path_1.default.join(fallbackDirectory, fileName);
}
