import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { test, WEB } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

const runHome = join(process.env.PROOF_CODEX_HOME!, String(Date.now()));
const nativeHome = join(runHome, "native");
const sql = (query: string) => execFileSync("sqlite3", [join(T3_HOME, "userdata/statev2.sqlite"), query], { encoding: "utf8" }).trim();
const native = (cwd: string, args: string[]) => execFileSync("codex", ["exec", ...args], { cwd, env: { ...process.env, CODEX_HOME: nativeHome }, encoding: "utf8", timeout: 120000, stdio: ["ignore", "pipe", "pipe"] });

test("A partial import retry does not certify a native continuation missing from T3", WEB, async ({t3, app, screen}) => {
  const workspace = join(runHome, "Import retry demo");
  mkdirSync(workspace, {recursive: true});
  execFileSync("git", ["init", "--quiet", workspace]);
  writeFileSync(join(workspace, "README.md"), "Synthetic import retry evidence\n");
  execFileSync("git", ["add", "."], {cwd: workspace});
  execFileSync("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial"], {cwd: workspace});
  mkdirSync(nativeHome, { recursive: true });
  copyFileSync(join(homedir(), ".codex/auth.json"), join(nativeHome, "auth.json"));
  const config = readFileSync(join(homedir(), ".codex/config.toml"), "utf8");
  const endpoint = config.split("\n").find(line => line.startsWith("openai_base_url"));
  writeFileSync(join(nativeHome, "config.toml"), `${endpoint}\n`);
  const started = native(workspace, ["--skip-git-repo-check", "-m", "gpt-6-luna", "--json", "Reply exactly: Original native answer."]);
  const id = JSON.parse(started.split("\n").find(line => line.includes('"thread.started"'))!).thread_id;
  const settingsFile = join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(readFileSync(settingsFile, "utf8"));
  settings.providerInstances.codex = {driver: "codex", enabled: true, config: {binaryPath: "codex", homePath: nativeHome}};
  writeFileSync(settingsFile, JSON.stringify(settings));
  sql("CREATE TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'controlled runtime persistence failure'); END;");
  await t3.open("/welcome");
  await screen.getByRole("checkbox").first().tap();
  await screen.getByRole("button", "Import 1 project and start").tap();
  await screen.getByText("Some history was not imported", {exact: true}).waitFor({state: "visible"});
  await app.screenshot("initial-partial-import");
  sql("DROP TRIGGER fail_runtime;");
  native(workspace, ["resume", "--skip-git-repo-check", "-m", "gpt-6-luna", "--json", id, "Reply exactly: Native continuation answer."]);
  await t3.open("/welcome");
  await screen.getByRole("checkbox").first().tap();
  await screen.getByRole("button", "Import threads and start").tap();
  // The completion toast is persistent; the final capture shows the actual retry verdict.
  await screen.getByRole("button", "Importing…").waitFor({state: "hidden"});
  await screen.getByText(/^(Imported 1 thread|Some history was not imported)$/).waitFor({state: "visible"});
  await app.screenshot("retry-result");
  const count = Number(sql("SELECT count(*) FROM provider_session_runtime;"));
  const messages = JSON.parse(execFileSync("sqlite3", ["-json", join(T3_HOME, "userdata/statev2.sqlite"), "SELECT role, json_extract(payload_json, '$.text') AS text FROM orchestration_v2_projection_messages ORDER BY created_at, message_id"], {encoding: "utf8"}));
  writeFileSync(join(runHome, "observations.json"), JSON.stringify({runtimeRowsAfterRetry: count, storedMessages: messages}, null, 2));
  const threadId = sql("SELECT thread_id FROM orchestration_v2_projection_threads WHERE json_extract(payload_json, '$.historyOrigin') = 'v1_import' LIMIT 1;");
  await t3.open({threadId});
  await screen.getByText("Original native answer.", {exact: true}).waitFor({state: "visible"});
  await app.screenshot("stored-history");
  await expect(count).toBe(0);
});
