/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { IsoDateTime, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const PROMPT = "Show me an indented code block";
const REPLY = "    const x = 1;\n    const y = 2;\n    return x + y;";

test("Imported Claude transcript retains its indented code block", WEB, async ({ t3, app, screen, browser }) => {
  const seed = await t3.project("seed");
  const root = process.env.CLAUDE_CONFIG_DIR!;
  const run = await fs.mkdtemp(path.join(path.dirname(root), "run-"));
  const home = path.join(run, "claude");
  const project = path.join(run, "indent-demo");
  await fs.cp(seed, project, { recursive: true });
  const folder = path.join(home, "projects", project.replace(/[^a-zA-Z0-9]/g, "-"));
  await fs.mkdir(folder, { recursive: true });
  const sessionId = "019aa111-2222-4333-8444-555555555555";
  const timestamp = new Date().toISOString();
  await fs.writeFile(path.join(folder, `${sessionId}.jsonl`), [
    { type: "user", sessionId, cwd: project, uuid: "019aa111-2222-4333-8444-555555555556", timestamp, message: { role: "user", content: PROMPT } },
    { type: "assistant", sessionId, cwd: project, uuid: "019aa111-2222-4333-8444-555555555557", timestamp, message: { role: "assistant", content: [{ type: "text", text: REPLY }] } },
  ].map(row => JSON.stringify(row)).join("\n") + "\n");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("claudeAgent"),
      instance: { driver: ProviderDriverKind.make("claudeAgent"), enabled: true, config: { homePath: home } },
    } });
  }).pipe(Effect.scoped));
  await t3.open("/welcome");
  await screen.getByRole("button", /Review all/).tap({ timeout: 60_000 });
  const all = screen.getByRole("button", "Select all", { exact: true });
  if (await all.isEnabled()) await all.tap();
  await screen.getByRole("button", /Import.*start/).tap();
  await screen.getByRole("heading", "Welcome to T3 Code", { exact: true }).waitFor({ state: "hidden", timeout: 60_000 });
  const imported = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* client["orchestration.getOlderSettledThreads"]({ before: { settledAt: IsoDateTime.make(new Date(Date.now() + 86_400_000).toISOString()) }, limit: 50 });
  }).pipe(Effect.scoped));
  const thread = imported.threads.find(thread => thread.title === PROMPT);
  if (!thread) throw new Error("Imported thread missing from settled list");
  await t3.open({ threadId: thread.id });
  await screen.getByText(/const x = 1;/).waitFor({ timeout: 60_000 });
  await screen.getByText("Claude is unauthenticated", { exact: true }).waitFor();
  await screen.getByRole("button", "Dismiss Claude provider error", { exact: true }).tap();
  await screen.getByText("Claude is unauthenticated", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("imported-indented-code");
  expect(await browser.evaluate(() => [...document.querySelectorAll("pre")].some(pre => pre.textContent?.includes("const x = 1;") && pre.textContent?.includes("return x + y;")))).toBe(true);
});
