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

if (!(globalThis as any).document) {
  const { Window } = await import("happy-dom");
  const window = new Window();
  (globalThis as any).window = window;
  (globalThis as any).document = window.document;
  Object.defineProperty(globalThis, "navigator", {
    configurable: true,
    value: window.navigator,
  });
  (globalThis as any).Node = window.Node;
  (globalThis as any).Element = window.Element;
  (globalThis as any).HTMLElement = window.HTMLElement;
  (globalThis as any).SVGElement = window.SVGElement;
  (globalThis as any).Event = window.Event;
  (globalThis as any).CustomEvent = window.CustomEvent;
  (globalThis as any).MouseEvent = window.MouseEvent;
  (globalThis as any).KeyboardEvent = window.KeyboardEvent;
  (globalThis as any).getComputedStyle = window.getComputedStyle.bind(window);
}

const { __test__: mcpSettingsTest } = await import("../src/dimsdk/pages/utils/settings-dialogs.ts");

describe("mcp settings json parser", () => {
  it('accepts nested "tools" wrapper under mcpServers', () => {
    const input = JSON.stringify({
      mcpServers: {
        tools: {
          google_calendar: {
            command: "python3",
            args: ["/tmp/calendar/run_server.py"],
          },
        },
      },
    });

    const parsed = mcpSettingsTest.parseMcpServersJson(input, []);
    expect(parsed).toHaveLength(1);
    expect(parsed[0]?.name).toBe("google_calendar");
    expect(parsed[0]?.transport).toBe("stdio");
    expect((parsed[0] as any)?.command).toBe("python3");
    expect((parsed[0] as any)?.args).toEqual(["/tmp/calendar/run_server.py"]);
  });

  it("returns a valid example json payload", () => {
    const example = mcpSettingsTest.getMcpServersExampleJson();
    const parsed = mcpSettingsTest.parseMcpServersJson(example, []);
    expect(parsed.length).toBeGreaterThan(0);
    expect(parsed[0]?.transport).toBe("stdio");

    const formatted = mcpSettingsTest.formatMcpServersJson(parsed);
    const roundtrip = JSON.parse(formatted) as any;
    expect(roundtrip?.mcpServers).toBeTruthy();
  });

  it("round-trips SSE servers with headers", () => {
    const input = JSON.stringify({
      mcpServers: {
        notify: {
          type: "sse",
          url: "https://example.com/mcp",
          headers: {
            Authorization: "Bearer token",
            "x-tenant": "demo",
          },
          enabled: false,
        },
      },
    });

    const parsed = mcpSettingsTest.parseMcpServersJson(input, []);
    expect(parsed).toEqual([
      expect.objectContaining({
        name: "notify",
        transport: "sse",
        url: "https://example.com/mcp",
        headers: {
          Authorization: "Bearer token",
          "x-tenant": "demo",
        },
        enabled: false,
      }),
    ]);

    const roundtrip = JSON.parse(mcpSettingsTest.formatMcpServersJson(parsed)) as any;
    expect(roundtrip.mcpServers.notify).toMatchObject({
      type: "sse",
      url: "https://example.com/mcp",
      headers: {
        Authorization: "Bearer token",
        "x-tenant": "demo",
      },
      enabled: false,
    });
  });

  it("reports lint errors with location for invalid json", () => {
    const lint = mcpSettingsTest.lintMcpJson('{\n  "mcpServers": {\n');
    expect(lint.state).toBe("error");
    expect(String(lint.message ?? "")).toContain("line");
  });

  it("reports lint success for valid json", () => {
    const lint = mcpSettingsTest.lintMcpJson('{"mcpServers":{}}');
    expect(lint.state).toBe("success");
  });
});
