import { describe, expect, it } from "vitest";

import {
  COURSEWARE_SERVICE_DEFAULTS,
  getCoursewareServiceBaseUrl,
  getCoursewareServices,
  normalizeCoursewareRuntimeConfig,
  resolveCoursewareServiceAddress,
  resolveCoursewareServiceUrl,
} from "~/lib/courseware-runtime";

describe("courseware service runtime config", () => {
  it("rewrites loopback service defaults to the current hostname", () => {
    const services = getCoursewareServices(undefined, "student-lab.example");

    expect(services["open-webui"]).toBe("http://student-lab.example:8080/");
    expect(services["promptfoo"]).toBe("http://student-lab.example:15500/");
    expect(services["chunkviz"]).toBe("http://student-lab.example:3000/");
    expect(services["embedding-atlas"]).toBe("http://student-lab.example:5055/");
    expect(services["unsloth"]).toBe("http://student-lab.example:8888/");
    expect(services["ssh"]).toBe("ssh://student-lab.example:22");
  });

  it("preserves explicit public service URLs without rewriting them", () => {
    const services = getCoursewareServices(
      {
        "open-webui": "https://labs.example/openwebui",
        "promptfoo": "https://eval.example/promptfoo",
        "ssh": "ssh://bastion.example:2222",
      },
      "student-lab.example",
    );

    expect(services["open-webui"]).toBe("https://labs.example/openwebui");
    expect(services["promptfoo"]).toBe("https://eval.example/promptfoo");
    expect(services["ssh"]).toBe("ssh://bastion.example:2222");
  });

  it("resolves service URLs with appended paths and address-only displays", () => {
    const runtimeConfig = normalizeCoursewareRuntimeConfig(
      {
        services: {
          "open-webui": "https://labs.example/openwebui",
          "ssh": "ssh://bastion.example:2222",
        },
      },
      "student-lab.example",
    );

    expect(resolveCoursewareServiceUrl(runtimeConfig, "open-webui")).toBe(
      "https://labs.example/openwebui",
    );
    expect(resolveCoursewareServiceUrl(runtimeConfig, "open-webui", "/api")).toBe(
      "https://labs.example/openwebui/api",
    );
    expect(resolveCoursewareServiceAddress(runtimeConfig, "ssh")).toBe(
      "bastion.example:2222",
    );
  });

  it("falls back to the default service map when a service is omitted", () => {
    expect(getCoursewareServiceBaseUrl("open-webui", undefined, "localhost")).toBe(
      "http://localhost:8080/",
    );
    expect(COURSEWARE_SERVICE_DEFAULTS["ssh"]).toBe("ssh://127.0.0.1:22");
  });
});
