import { expect } from "e2e";
import { spawn } from "node:child_process";
import * as fs from "node:fs/promises";
import * as net from "node:net";
import * as path from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// Real release server, downloaded by the public t3@0.1.3 launcher before the run.
const scratch = process.env.T3_PROOF_SCRATCH!;
const oldBinary = `${scratch}/old-runtime/runtime/versions/0.1.3/t3`;
const values = (value: boolean) => ({defaultAutoPull:value, removeAgentCreditsOnMerge:value, reviewGuidesEnabled:value, sourceControlWritingStyle:{followChangeRequestTemplates:value}, linkedEnvironmentsEnabled:false});

test("Settings can be turned off after an older environment leaves them mixed", WEB, async ({t3,app,screen,browser}) => {
  for (const command of ["gh","glab"]) {
    await fs.writeFile(path.join(T3_HOME,"bin",command),'#!/bin/sh\nexit 1\n',{mode:0o755});
  }
  const pause = () => new Promise(resolve => setTimeout(resolve, 500));
  const capture = async (label: string) => {
    await pause();
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt = 0; attempt < 8; attempt++) {
      await pause();
      const current = await app.screenshot(attempt === 0 ? label : `${label}-settled-${attempt}`);
      if ((await fs.readFile(previous)).equals(await fs.readFile(current))) return;
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  await t3.project("Settings demo");
  const settingsPath = path.join(T3_HOME,"userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath,"utf8"));
  await fs.writeFile(settingsPath,JSON.stringify({...settings,...values(false)}));
  const oldHome = await fs.mkdtemp(`${scratch}/old-home-`);
  await fs.mkdir(`${oldHome}/userdata`);
  await fs.mkdir(`${oldHome}/bin`);
  for (const command of ["gh","glab"]) await fs.writeFile(`${oldHome}/bin/${command}`,'#!/bin/sh\nexit 1\n',{mode:0o755});
  await fs.writeFile(`${oldHome}/userdata/settings.json`,JSON.stringify(values(true)));
  await fs.writeFile(`${oldHome}/bin/hostnamectl`, '#!/bin/sh\necho "Older environment"\n',{mode:0o755});
  const port = await new Promise<number>(resolve=>{const s=net.createServer();s.listen(0,"127.0.0.1",()=>{const p=(s.address() as net.AddressInfo).port;s.close(()=>resolve(p));});});
  const child=spawn(oldBinary,["serve","--host","127.0.0.1","--port",String(port),"--base-dir",oldHome,"--dev-url",app.baseUrl??""],{env:{...process.env,PATH:`${oldHome}/bin:${process.env.PATH}`,T3CODE_DEV_SEED:"0",T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD:"0"},stdio:["ignore","pipe","pipe"]});
  const token=await new Promise<string>((resolve,reject)=>{let out="";child.stdout.on("data",chunk=>{out+=chunk;const m=/Token:\s*(\S+)/.exec(out);if(m)resolve(m[1]);});child.stderr.on("data",()=>{});child.on("exit",code=>reject(new Error(`Older server exited ${code}`)));});
  try {
    await t3.open("/settings/connections");
    await screen.getByRole("button","Add environment").tap();
    const dialog=screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(`http://127.0.0.1:${port}`);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button","Add environment").tap();
    await screen.getByRole("button","More actions for Older environment").waitFor({timeout:60000});
    await screen.getByPlaceholder("PAIRCODE").waitFor({state:"hidden"});
    await screen.getByText("Connected · 0.1.3",{exact:false}).waitFor();
    await capture("connected-older-release");
    for (const [route,names] of [["source-control",["Default automatic pull","Remove agent credits when merging","Review guides",/Follow .* request templates/]]] as const) {
      await app.open(`/settings/${route}`);
      await screen.getByText("Git",{exact:true}).first().waitFor();
      await browser.locator('[data-slot="skeleton"]').first().waitFor({state:"hidden"});
      for (const name of names) {
        let toggle=screen.getByRole("switch",name);
        if (/Follow/.test(String(name))) {
          await screen.getByRole("button","Advanced",{exact:true}).tap();
          await pause();
        }
        await browser.evaluate((label: string) => {
          const toggle = [...document.querySelectorAll('[role="switch"]')].find(el => el.getAttribute('aria-label')===label || (label.includes('Follow') && el.getAttribute('aria-label')?.startsWith('Follow ')));
          toggle?.closest('[data-slot="settings-row"]')?.scrollIntoView({block:"center"});
        },String(name));
        await capture(`${String(name).replace(/[^a-zA-Z]+/g,"-")}-initial`);
        await toggle.tap();
        await capture(`${String(name).replace(/[^a-zA-Z]+/g,"-")}-after-on`);
        await toggle.tap();
        await capture(`${String(name).replace(/[^a-zA-Z]+/g,"-")}-after-off`);
      }
    }
    await app.open("/settings/labs");
    const toggle=screen.getByRole("switch","Linked environments");
    await toggle.tap();
    await screen.getByText("Setting saved on some environments",{exact:false}).first().waitFor();
    await capture("linked-environments-after-enable");
    await toggle.tap();
    await capture("linked-environments-after-disable");
    await expect(toggle).toHaveAttribute("aria-checked","false");
  } finally {
    child.kill("SIGTERM");
    await new Promise<void>(resolve=>child.once("exit",()=>resolve()));
  }
});
