import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("node:os", async () => {
    const actual = await vi.importActual("node:os");
    const mocked = {
        ...actual,
        homedir: () => process.env.AWS_TEST_HOME || actual.homedir(),
    };
    return {
        ...mocked,
        default: mocked,
    };
});
const originalEnv = { ...process.env };
const tempRoots = [];
function createRuntimeHome() {
    const root = mkdtempSync(path.join(os.tmpdir(), "aws-config-"));
    tempRoots.push(root);
    return root;
}
function useRuntimeHome(runtimeHome) {
    process.env.AWS_TEST_HOME = runtimeHome;
    process.env.HOME = runtimeHome;
    process.env.USERPROFILE = runtimeHome;
    process.env.AWS_RUNTIME_HOME_DIR = runtimeHome;
    delete process.env.AWS_RUNTIME_SCHEDULER_BASE_URL;
}
function writeBridgeConfig(runtimeHome, autoRegisterTargets) {
    const configPath = path.join(runtimeHome, ".aws-bridge", "config.json");
    mkdirSync(path.dirname(configPath), { recursive: true });
    writeFileSync(configPath, `${JSON.stringify({ connectionKey: "bridge-key", autoRegisterTargets }, null, 2)}\n`, "utf-8");
}
afterEach(() => {
    process.env = { ...originalEnv };
    vi.resetModules();
    vi.clearAllMocks();
    vi.restoreAllMocks();
    for (const root of tempRoots.splice(0)) {
        rmSync(root, { recursive: true, force: true });
    }
});
describe("scheduler base URL resolution", () => {
    it("keeps scheduler URL supplied by the server request as the highest priority", async () => {
        const runtimeHome = createRuntimeHome();
        useRuntimeHome(runtimeHome);
        process.env.AWS_RUNTIME_SCHEDULER_BASE_URL = "http://env.local:7380";
        writeBridgeConfig(runtimeHome, [{ serverUrl: "http://target.local:7380" }]);
        const { resolveSchedulerBaseUrlFrom } = await import("./config.js");
        expect(resolveSchedulerBaseUrlFrom("http://server.local:7380/api")).toEqual({
            url: "http://server.local:7380",
            source: "request",
            ambiguousTargetUrls: [],
        });
    });
    it("keeps explicit AWS_RUNTIME_SCHEDULER_BASE_URL as the highest priority", async () => {
        const runtimeHome = createRuntimeHome();
        useRuntimeHome(runtimeHome);
        process.env.AWS_RUNTIME_SCHEDULER_BASE_URL = "http://explicit.local:7380/path";
        writeBridgeConfig(runtimeHome, [{ serverUrl: "http://target.local:7380" }]);
        const { resolveSchedulerBaseUrl } = await import("./config.js");
        expect(resolveSchedulerBaseUrl()).toEqual({
            url: "http://explicit.local:7380",
            source: "env",
            ambiguousTargetUrls: [],
        });
    });
    it("uses a single auto-register target serverUrl when scheduler env is absent", async () => {
        const runtimeHome = createRuntimeHome();
        useRuntimeHome(runtimeHome);
        writeBridgeConfig(runtimeHome, [{ serverUrl: "http://127.0.0.1:7380" }]);
        const { resolveSchedulerBaseUrl } = await import("./config.js");
        expect(resolveSchedulerBaseUrl()).toEqual({
            url: "http://127.0.0.1:7380",
            source: "single-auto-register-target",
            ambiguousTargetUrls: [],
        });
    });
    it("does not silently select the first auto-register target when multiple URLs exist", async () => {
        const runtimeHome = createRuntimeHome();
        useRuntimeHome(runtimeHome);
        writeBridgeConfig(runtimeHome, [
            { serverUrl: "http://scheduler-a.local:7380" },
            { serverUrl: "http://scheduler-b.local:7380" },
        ]);
        const { DEFAULT_SCHEDULER_BASE_URL, resolveSchedulerBaseUrl } = await import("./config.js");
        expect(resolveSchedulerBaseUrl()).toEqual({
            url: DEFAULT_SCHEDULER_BASE_URL,
            source: "ambiguous-auto-register-targets",
            ambiguousTargetUrls: [
                "http://scheduler-a.local:7380",
                "http://scheduler-b.local:7380",
            ],
        });
    });
    it("falls back to the legacy localhost default when no scheduler source exists", async () => {
        const runtimeHome = createRuntimeHome();
        useRuntimeHome(runtimeHome);
        const { DEFAULT_SCHEDULER_BASE_URL, resolveSchedulerBaseUrl } = await import("./config.js");
        expect(resolveSchedulerBaseUrl()).toEqual({
            url: DEFAULT_SCHEDULER_BASE_URL,
            source: "default",
            ambiguousTargetUrls: [],
        });
    });
});
