import { describe, expect, it } from "vitest";
import { createTerminalApp } from "@simon_he/vue-tui";
import { nextTick } from "vue";
import { DimSdkShell, createDimSdkRouter } from "../src/dimsdk/index.ts";
import { createErrorGoatChainAgent as createErrorDimSdkAgent } from "../src/dimsdk/core/agents/error.ts";

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);
}

globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {
  cb(0);
  return 1;
}) as typeof globalThis.requestAnimationFrame;
globalThis.cancelAnimationFrame = (() => {}) as typeof globalThis.cancelAnimationFrame;

async function flushApp(app: {
  scheduler: { flush: () => void };
}) {
  await nextTick();
  await nextTick();
  app.scheduler.flush();
}

async function pressKey(
  app: {
    events: { dispatch: (event: any) => boolean | void };
    scheduler: { flush: () => void };
  },
  key: string,
  options: Readonly<{ shiftKey?: boolean; code?: string }> = {},
) {
  app.events.dispatch({ type: "keydown", key, code: options.code ?? key, ...options } as const);
  await flushApp(app);
}

async function typeText(
  app: {
    events: { dispatch: (event: any) => boolean | void };
    scheduler: { flush: () => void };
  },
  text: string,
) {
  for (const ch of text) {
    await pressKey(app, ch);
  }
}

function snapshotText(app: {
  terminal: { snapshot: () => { lines: readonly string[] } };
}): string {
  return app.terminal.snapshot().lines.join("\n");
}

describe("dimsdk chat cross-session busy", () => {
  it("blocks sending when another window is marked as running the same session", async () => {
    const previousDimcodeTest = process.env.DIMCODE_TEST;
    process.env.DIMCODE_TEST = "1";
    let storeRef: any;
    const app = createTerminalApp({
      cols: 120,
      rows: 36,
      component: DimSdkShell as never,
      props: {
        toolRunner: async () => ({
          id: "tool",
          output: "disabled",
          status: "error" as const,
        }),
        context: {
          system: "You are best-agent running in a cross-session busy test.",
          cwd: ".",
          env: { DIMCODE_VERSION: "0.0.0" },
        },
        agent: createErrorDimSdkAgent(new Error("Agent is disabled in this test.")),
        onStoreCreated: (store: any) => {
          storeRef = store;
          store.state.sessionId = "thread_remote_busy";
          store.state.sessionMeta.status = "running";
          store.state.sessionMeta.lastUpdatedAt = Date.now();
        },
      },
      defaultStyle: { bg: "black", fg: "whiteBright" },
    });

    try {
      app.app.use(createDimSdkRouter({ initialRoute: "chat", mode: "cli" }) as never);
      app.mount();
      await flushApp(app);

      await typeText(app, "hello from second window");
      await pressKey(app, "Enter", { code: "Enter" });
      await flushApp(app);

      expect(snapshotText(app)).toContain("Another window is still running this session.");
      expect(storeRef.state.messages).toEqual([]);
    } finally {
      process.env.DIMCODE_TEST = previousDimcodeTest;
      app.dispose();
    }
  });
});
