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

test("Completed OpenCode compaction hides pre-compaction context usage", WEB, async ({ t3, app, screen, browser }) => {
  const notes = Array.from({ length: 900 }, (_, i) => `Note ${i + 1}: The synthetic observatory records temperature, pressure, humidity, wind direction and calibration results. Review each measurement carefully and preserve the station identifier for the daily report.\n`).join("");
  const project = await t3.project("compaction-demo", { "notes.txt": notes });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("opencode"),
      instance: { driver: "opencode", enabled: true, config: { binaryPath: "/usr/local/bin/opencode" } },
    } });
  }).pipe(Effect.scoped));
  const launched = await runPromise(makeState(T3_HOME).cli(["thread", "start", project,
    "Read notes.txt in full using the read tool. Do not modify any files. Reply only: Finished reading notes.",
    "--title", "Compaction context proof", "--provider", "opencode", "--model", "openai/gpt-6-luna", "--wait", "--json"]));
  const thread = JSON.parse(launched.stdout);
  await t3.open({ threadId: thread.threadId });
  await browser.evaluate(() => {
    const key = "t3code:client-settings:v1";
    const settings = JSON.parse(localStorage.getItem(key) ?? "{}");
    localStorage.setItem(key, JSON.stringify({ ...settings, threadDetailsItems: { context: true, environment: false, openIn: false, scripts: false, branch: false, gitActions: false, changes: false, servers: false, automations: false, lineage: false, sideChats: false }, threadDetailsUsageEnabled: false }));
    return null;
  });
  await t3.open({ threadId: thread.threadId });
  await screen.getByText("Context", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("before-compaction");
  await screen.getByRole("textbox").fill("/compact");
  await screen.getByRole("textbox").press("Escape");
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await screen.getByRole("separator", "Context compacted", { exact: false }).waitFor({ state: "visible", timeout: 180_000 });
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 180_000 });
  await app.screenshot("completed-compaction");
  await expect(screen.getByText("Context", { exact: true })).toBeHidden();
});
