import { createRequire } from "node:module";
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const require = createRequire(import.meta.url);
function resolveFromSameServerPackage() {
    const managerDir = path.dirname(fileURLToPath(import.meta.url));
    const serverDist = path.resolve(managerDir, "..");
    const distEntry = path.join(serverDist, "scripts/supervisor-entrypoint.js");
    if (existsSync(distEntry)) {
        return distEntry;
    }
    return null;
}
function resolveFromInstalledServer() {
    try {
        const serverPackageJson = require.resolve("@kong-link/server/package.json");
        const serverRoot = path.dirname(serverPackageJson);
        const distEntry = path.join(serverRoot, "dist/scripts/supervisor-entrypoint.js");
        if (existsSync(distEntry)) {
            return distEntry;
        }
    }
    catch {
        // @kong-link/server not installed
    }
    return null;
}
function resolveFromMonorepo() {
    const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
    const monorepoRoot = path.resolve(packageRoot, "../..");
    const distEntry = path.join(monorepoRoot, "packages/server/dist/scripts/supervisor-entrypoint.js");
    if (existsSync(distEntry)) {
        return distEntry;
    }
    const srcEntry = path.join(monorepoRoot, "packages/server/scripts/supervisor-entrypoint.ts");
    if (existsSync(srcEntry)) {
        return srcEntry;
    }
    return null;
}
export function resolveSupervisorInvocation() {
    const samePackage = resolveFromSameServerPackage();
    if (samePackage) {
        return { command: process.execPath, args: [samePackage] };
    }
    const installed = resolveFromInstalledServer();
    if (installed) {
        return { command: process.execPath, args: [installed] };
    }
    const monorepoDist = resolveFromMonorepo();
    if (monorepoDist?.endsWith(".js")) {
        return { command: process.execPath, args: [monorepoDist] };
    }
    if (monorepoDist?.endsWith(".ts")) {
        return { command: process.execPath, args: ["--import", "tsx", monorepoDist] };
    }
    throw new Error("@kong-link/server is not installed. Install it with: npm install -g @kong-link/server");
}
