import { expect } from "e2e";
import { spawn } from "node:child_process";
import { mkdir, writeFile, readFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Failed daemon shutdown keeps agent device access enabled and reports failure", WEB, async ({ t3, app, screen, browser }) => {
  const install = join(T3_HOME, "tools/agent-device/0.21.36");
  const state = join(T3_HOME, "userdata/device/agent-device");
  await mkdir(join(install, "node_modules/agent-device/bin"), { recursive: true });
  await mkdir(state, { recursive: true });
  await writeFile(join(install, ".install-complete"), "0.21.36");
  await writeFile(join(install, "node_modules/agent-device/bin/agent-device.mjs"), `import { appendFileSync } from 'node:fs';
appendFileSync(${JSON.stringify(join(state, "calls.jsonl"))}, JSON.stringify(process.argv.slice(2)) + '\\n');
if (process.argv[2] === 'daemon' && process.argv[3] === 'stop') { console.error('Synthetic daemon stop failure'); process.exit(1); }
console.log(JSON.stringify({success:true,data:{devices:[]}}));
`);
  const daemon = spawn(process.execPath, ["-e", "setInterval(() => {}, 60000)"], { stdio: "ignore" });
  const record = JSON.stringify({ httpPort: 19999, token: "synthetic-token", pid: daemon.pid, version: "0.21.36" });
  await writeFile(join(state, "daemon.json"), record);
  try {
    await t3.project("Device shutdown proof");
    await t3.open();
    await screen.getByText("Device shutdown proof", { exact: true }).first().waitFor({ state: "visible" });
    await app.open("/settings/devices");
    const access = screen.getByRole("switch", "Agent device access");
    // Wait for the real configure request to finish before capturing either outcome.
    await access.tap();
    await expect(access).toBeEnabled();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1200)));
    await app.screenshot("daemon-stop-failed");
    process.kill(daemon.pid!, 0);
    const settings = JSON.parse(await readFile(join(T3_HOME, "userdata/settings.json"), "utf8"));
    const calls = await readFile(join(state, "calls.jsonl"), "utf8");
    const summary = {
      daemonStillAlive: true,
      daemonRecordUnchanged: (await readFile(join(state, "daemon.json"), "utf8")) === record,
      savedAgentAccessEnabled: settings.enableAgentDeviceAccess === true,
      daemonStopCalled: calls.includes('"daemon","stop","--state-dir"'),
      stubStopExitCode: 1,
    };
    await writeFile(join(process.env.PROOF_OUTPUT_DIR ?? T3_HOME, `runtime-${Date.now()}.json`), JSON.stringify(summary, null, 2));
    await expect(access).toBeChecked();
    await expect(screen.getByText("Device settings not saved on all environments")).toBeVisible();
  } finally {
    daemon.kill();
  }
});
