/// <reference lib="dom" />
import { readFile, mkdir, cp, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { CommandId, ProviderDriverKind, ProviderInstanceId, type ProjectSnapshot } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Deleting and re-importing real Claude history restores the current transcript", WEB,
  async ({ t3, app, browser, screen }) => {
    const seededProject = await t3.project("Claude import demo");
    const call = <A, E>(f: (client: Effect.Success<ReturnType<typeof rpcClient>>) => Effect.Effect<A, E>) => runPromise(
      Effect.gen(function* () { return yield* f(yield* rpcClient(T3_HOME, app.baseUrl ?? "")); }).pipe(Effect.scoped),
    );
    const token = (await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]))).stdout.trim();
    const snapshot = await (await fetch(`${app.baseUrl}/api/projects`, { headers: { authorization: `Bearer ${token}` } })).json() as ProjectSnapshot;
    const projectRow = snapshot.projects.find((p) => p.workspaceRoot === seededProject)!;
    // Session discovery deliberately excludes projects inside the server's own data directory.
    const project = join(process.env.T3_PROOF_SCRATCH_DIR!, `project-${crypto.randomUUID()}`, "Claude import demo");
    await cp(seededProject, project, { recursive: true });
    await call((client) => client["projects.mutate"]({ type: "project.update", commandId: CommandId.make(crypto.randomUUID()), projectId: projectRow.id, workspaceRoot: project }));
    const claudeHome = join(T3_HOME, "claude-import-history");
    await mkdir(claudeHome, { recursive: true });
    const hostSettings = JSON.parse(await readFile(join(homedir(), ".claude/settings.json"), "utf8")) as { env?: Record<string, string> };
    const cliEnv: NodeJS.ProcessEnv = { ...process.env, CLAUDE_CONFIG_DIR: claudeHome };
    for (const key of ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "NODE_EXTRA_CA_CERTS"]) {
      if (hostSettings.env?.[key]) cliEnv[key] = hostSettings.env[key];
    }
    await writeFile(join(claudeHome, "settings.json"), JSON.stringify({ env: Object.fromEntries(
      ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "NODE_EXTRA_CA_CERTS"].filter((key) => cliEnv[key]).map((key) => [key, cliEnv[key]]),
    ) }), { mode: 0o600 });
    const claude = (...args: string[]) => runPromise(run("claude", ["-p", "--model", "haiku", "--name", "Pong", "--output-format", "json", ...args], { cwd: project, env: cliEnv }));
    const first = JSON.parse((await claude("Reply with the single word: pong")).stdout);
    if (first.is_error || first.result.trim() !== "pong") throw new Error("The real Claude CLI did not return pong");
    const imported = { threadId: `import:claudeAgent:${first.session_id}` };
    await call((client) => client["server.updateSettings"]({
      patch: {}, providerInstanceMutation: {
        operation: "upsert", instanceId: ProviderInstanceId.make("claudeAgent"),
        instance: { driver: ProviderDriverKind.make("claudeAgent"), enabled: true, config: { homePath: claudeHome } },
      },
    }));
    const scan = await call((client) => client["agentSessions.scan"]({}));
    const candidate = scan.candidates.find((item) => item.path === project);
    if (!candidate?.projectId) throw new Error("Real Claude transcript was not discovered for the project: " + JSON.stringify(scan));
    const importHistory = () => call((client) => client["agentSessions.import"]({ projectId: candidate.projectId, expectedWorkspaceRoot: project }));
    await importHistory();
    await browser.setViewport({ width: 1280, height: 800 });
    await t3.open(imported);
    await screen.getByText("pong", { exact: true }).waitFor();
    const next = JSON.parse((await claude("--resume", first.session_id, "Reply with the single word: ping")).stdout);
    if (next.is_error || next.result.trim() !== "ping") throw new Error("The real Claude CLI did not return ping");
    await screen.getByRole("button", /^Thread actions for /).tap();
    await screen.getByRole("menuitem", "Delete", { exact: true }).tap();
    await screen.getByRole("alertdialog").getByRole("button", "Confirm", { exact: true }).tap();
    await screen.getByRole("button", /^Thread actions for /).waitFor({ state: "hidden" });
    await app.screenshot("deleted-import");
    await importHistory();
    await t3.open(imported);
    // Opening the same link shows the current transcript on head and the empty project on base.
    await screen.getByText("Claude import demo", { exact: true }).first().waitFor();
    await app.screenshot("after-reimport");
    expect(await screen.getByText("ping", { exact: true }).isVisible(), "Re-import restores the deleted session with its current ping exchange").toBe(true);
  },
);
