"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveCurrentEntrypointPath = resolveCurrentEntrypointPath;
exports.readPackageMetadataForEntrypoint = readPackageMetadataForEntrypoint;
const promises_1 = require("node:fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const zod_1 = require("zod");
const file_readers_1 = require("./file-readers");
const packageMetadataSchema = zod_1.z.object({
    name: zod_1.z.string().min(1),
    version: zod_1.z.string().min(1),
});
function resolveCurrentEntrypointPath(argv = process.argv) {
    const candidate = argv[1] ?? require.main?.filename;
    return candidate ? node_path_1.default.resolve(candidate) : null;
}
async function readPackageMetadataForEntrypoint(entrypointPath) {
    const normalizedEntrypoint = node_path_1.default.resolve(entrypointPath);
    const resolvedEntrypoint = await (0, promises_1.realpath)(normalizedEntrypoint).catch(() => normalizedEntrypoint);
    const packageRoot = await findNearestPackageRoot(node_path_1.default.dirname(resolvedEntrypoint));
    if (packageRoot === null) {
        return null;
    }
    const metadata = await readPackageJsonMetadata(node_path_1.default.join(packageRoot, "package.json"));
    if (metadata.kind !== "found") {
        return null;
    }
    return {
        packageName: metadata.metadata.name,
        packageVersion: metadata.metadata.version,
        packageRoot,
        entrypointPath: normalizedEntrypoint,
        resolvedEntrypointPath: resolvedEntrypoint,
    };
}
async function findNearestPackageRoot(startDirectory) {
    let current = node_path_1.default.resolve(startDirectory);
    while (true) {
        const packagePath = node_path_1.default.join(current, "package.json");
        const metadata = await readPackageJsonMetadata(packagePath);
        if (metadata.kind === "found") {
            return current;
        }
        if (metadata.kind === "invalid") {
            return null;
        }
        const parent = node_path_1.default.dirname(current);
        if (parent === current) {
            return null;
        }
        current = parent;
    }
}
async function readPackageJsonMetadata(packagePath) {
    const text = await (0, file_readers_1.readTextFileIfExists)(packagePath);
    if (text === null) {
        return { kind: "missing" };
    }
    try {
        const parsed = JSON.parse(text);
        const result = packageMetadataSchema.safeParse(parsed);
        return result.success
            ? { kind: "found", metadata: result.data }
            : { kind: "invalid" };
    }
    catch {
        return { kind: "invalid" };
    }
}
