import { expect } from "e2e";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts";

async function seed(home: string, origin: string, title: string, all: boolean) {
  const fixtureHome = join(process.env.T3_PROOF_ROOT!, home.endsWith("second-environment") ? "fixture-secondary" : "fixture-primary");
  const cwd = join(fixtureHome, "projects", title);
  await mkdir(cwd, { recursive: true });
  await writeFile(join(cwd, "README.md"), "Synthetic session import evidence\n");
  await runPromise(run("git", ["init", "--quiet", "--initial-branch=main"], { cwd }));
  const homes = { claudeAgent: join(home, "claude-history"), codex: join(home, "codex-history"), pi: join(home, "pi-history") };
  const save = async (file: string, rows: unknown[]) => {
    await mkdir(join(file, ".."), { recursive: true });
    await writeFile(file, rows.map(row => JSON.stringify(row)).join("\n") + "\n");
  };
  for (const dir of Object.values(homes)) await mkdir(dir, { recursive: true });
  const timestamp = "2026-11-18T12:00:00.000Z";
  await save(join(homes.claudeAgent, "projects", "synthetic", "11111111-1111-4111-8111-111111111111.jsonl"), [
    { type: "user", uuid: "c1", sessionId: "11111111-1111-4111-8111-111111111111", cwd, timestamp, message: { role: "user", content: "Claude history: implement the build endpoint" } },
    { type: "assistant", uuid: "c2", parentUuid: "c1", sessionId: "11111111-1111-4111-8111-111111111111", timestamp, message: { role: "assistant", content: [{ type: "text", text: "Claude history imported successfully." }] } },
  ]);
  if (all) {
    await save(join(homes.codex, "sessions", "2026", "11", "18", "rollout-22222222-2222-4222-8222-222222222222.jsonl"), [
      { type: "session_meta", timestamp, payload: { id: "22222222-2222-4222-8222-222222222222", cwd } },
      { type: "event_msg", timestamp, payload: { type: "user_message", message: "Codex history: validate the build endpoint" } },
      { type: "response_item", timestamp, payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: "Codex history imported successfully." }] } },
    ]);
    await save(join(homes.pi, "sessions", "--synthetic--", "33333333-3333-4333-8333-333333333333.jsonl"), [
      { type: "session", version: 3, id: "33333333-3333-4333-8333-333333333333", cwd, timestamp },
      { type: "message", id: "p1", parentId: null, timestamp, message: { role: "user", content: "Pi history: document the build endpoint" } },
      { type: "message", id: "p2", parentId: "p1", timestamp, message: { role: "assistant", content: [{ type: "text", text: "Pi history imported successfully." }] } },
    ]);
  }
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    const current = yield* client["server.getSettings"]({});
    yield* client["server.updateSettings"]({ patch: { providerInstances: { ...current.providerInstances,
      claudeAgent: { driver: "claudeAgent", enabled: true, config: { homePath: homes.claudeAgent } },
      codex: { driver: "codex", enabled: true, config: { homePath: homes.codex } },
      pi: { driver: "pi", enabled: true, environment: [{ name: "PI_CODING_AGENT_DIR", value: homes.pi, sensitive: false }], config: {} },
    } } });
  }).pipe(Effect.scoped));
}

test("Connected environment history is reachable by query and menu and imports all three sources", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Current work");
  await seed(T3_HOME, app.baseUrl ?? "", "primary-notes", false);
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await seed(SECOND_HOME, host, "build-api", true);
    const id = await runPromise(environmentId(host));
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    const actions = screen.getByRole("button", "More actions for History server");
    await actions.waitFor({ timeout: 60_000 });
    await screen.getByText(/ · Connected$/).waitFor({ timeout: 60_000 });
    await actions.press("Enter");
    await app.screenshot("connected-environment-menu");
    await browser.keyboard.press("Escape");
    await app.open("/settings/about");
    await screen.getByRole("link", "Open", { exact: true }).tap();
    await screen.getByRole("button", /Review all/).tap();
    await app.screenshot("about-primary-history");
    await app.open(`/welcome#agents:${id}`);
    await screen.getByRole("button", /Review all/).tap();
    await app.screenshot("hash-secondary-history");
    await app.open(`/welcome?environmentId=${encodeURIComponent(id)}`);
    await screen.getByRole("button", /Review all/).tap();
    await app.screenshot("typed-query-history");
    await expect(screen.getByText("Setting up History server.", { exact: false })).toBeVisible();
    await expect(screen.getByText("build-api", { exact: true }).first()).toBeVisible();
    await app.open("/settings/connections");
    await screen.getByText(/ · Connected$/).waitFor({ timeout: 60_000 });
    await actions.press("Enter");
    await screen.getByRole("menuitem", /^Import sessions/).press("Enter");
    await screen.getByRole("heading", "Welcome to T3 Code").waitFor();
    await screen.getByRole("button", /Review all/).tap();
    await app.screenshot("menu-history-three-sources");
    await screen.getByRole("button", "Import 1 project and start", { exact: true }).tap();
    await screen.getByRole("heading", "Welcome to T3 Code").waitFor({ state: "hidden", timeout: 60_000 });
    for (const [provider, session, answer] of [["claudeAgent", "11111111-1111-4111-8111-111111111111", "Claude"], ["codex", "22222222-2222-4222-8222-222222222222", "Codex"], ["pi", "33333333-3333-4333-8333-333333333333", "Pi"]]) {
      await app.open(`/${id}/import:${provider}:${session}`);
      await expect(screen.getByText(`${answer} history imported successfully.`, { exact: true })).toBeVisible();
      await screen.getByRole("button", /^Dismiss .* provider (error|warning)$/).tap();
      await screen.getByText(`${answer} history imported successfully.`, { exact: true }).scrollIntoView();
      await new Promise((resolve) => setTimeout(resolve, 500));
      await app.screenshot(`imported-${answer}-transcript`);
    }
  } finally { await server.stop(); }
});
