import { DatabaseSync } from "node:sqlite";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise, makeState } from "./t3.ts";

test("Imported session first immediate send shows its context handoff", WEB, async ({t3, app, screen, browser}) => {
  const seed = await t3.project("seed");
  const runDir = path.join(path.dirname(process.env.CLAUDE_CONFIG_DIR!), "runs", String(Date.now()));
  const project = path.join(runDir, "pelican-app");
  await fs.mkdir(runDir, {recursive:true});
  await fs.cp(seed, project, {recursive:true});
  const home = process.env.CLAUDE_CONFIG_DIR!;
  const dir = path.join(home, "projects", "-pelican");
  await fs.mkdir(dir, {recursive:true});
  const sessionId = "8d77ac36-c539-4910-9812-523e1b789bac";
  await fs.writeFile(path.join(dir, sessionId + ".jsonl"), [
    {type:"user", uuid:"u1", cwd:project, sessionId, timestamp:new Date().toISOString(), message:{role:"user",content:"Remember the code word PELICAN."}},
    {type:"assistant", uuid:"a1", parentUuid:"u1", cwd:project, sessionId, timestamp:new Date().toISOString(), message:{role:"assistant",model:"claude-haiku-4-5",content:[{type:"text",text:"Got it, the code word is PELICAN."}]}}
  ].map(x=>JSON.stringify(x)).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:"claudeAgent",instance:{driver:"claudeAgent",enabled:true,config:{homePath:home}}}});
    const scan = yield* client["agentSessions.scan"]({});
    const candidate = scan.candidates.find(x=>x.path===project);
    if(!candidate) throw new Error("Missing imported project candidate: " + JSON.stringify(scan));
    const projectId = crypto.randomUUID();
    yield* client["projects.mutate"]({type:"project.create",commandId:crypto.randomUUID(),projectId,title:"pelican-app",workspaceRoot:project});
    yield* client["agentSessions.import"]({projectId});
  }).pipe(Effect.scoped));
  const listed = await runPromise(makeState(T3_HOME).cli(["thread","list","--project",project,"--json"]));
  const data = JSON.parse(listed.stdout);
  const threadId = data[0].threadId;
  await browser.setViewport({width:1440,height:1200});
  await t3.open({threadId});
  await screen.getByText("Got it, the code word is PELICAN.", {exact:true}).waitFor();
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await browser.keyboard.type("Showcase");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Escape");
  await screen.getByRole("textbox").fill("What was the code word?");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("This turn is a replay.", {exact:false}).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await browser.evaluate(async () => {
    for (const element of document.querySelectorAll("*")) {
      if (element.scrollHeight > element.clientHeight) element.scrollTo({top:0,behavior:"instant"});
    }
    await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
    return null;
  });
  const db = new DatabaseSync(path.join(T3_HOME,"userdata/statev2.sqlite"), {readOnly:true});
  const summary = {
    runs: db.prepare("SELECT ordinal, provider, status, json_extract(payload_json, '$.contextHandoffId') AS contextHandoffId FROM orchestration_v2_projection_runs WHERE thread_id = ?").all(threadId),
    handoffItems: db.prepare("SELECT ordinal, payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id = ? AND type = 'handoff'").all(threadId),
    handoffs: db.prepare("SELECT payload_json FROM orchestration_v2_projection_context_handoffs WHERE thread_id = ?").all(threadId)
  };
  db.close();
  await fs.writeFile(path.join(runDir,"database-summary.json"),JSON.stringify(summary,null,2));
  await app.screenshot("imported-context-first-send");
  await expect(screen.getByText("Context handoff", {exact:true})).toBeVisible();
});
