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

test("PowerShell call-operator labels stop at statement and pipeline delimiters", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("PowerShell labels");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = {driver:"opencode", enabled:true, config:{}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const {cli} = makeState(T3_HOME);
  const prompt = "Run these four commands in order, each as a separate Bash tool call. Do not combine, modify, background, or run them in parallel. Use timeout 120000. Commands: 1. pwsh -Command '& Get-Date; Get-Location' 2. pwsh -Command '& git|Out-Null' 3. pwsh -Command '& Get-Date; Start-Sleep 40' 4. pwsh -Command '& git|Out-Null; Start-Sleep 40'. Afterward say Done. Do not use other tools.";
  let threadId: string | undefined;
  for(let i=0;i<8 && !threadId;i++) {
    const result = await runPromise(cli(["thread","start",project,prompt,"--title","PowerShell command labels","--provider","opencode","--model","openai/gpt-6-luna","--json"], [0,1]));
    if(result.stdout.includes('threadId')) threadId = JSON.parse(result.stdout).threadId;
  }
  if(!threadId) throw new Error("Could not start real provider");
  await t3.open({threadId});
  const first = screen.getByText(/^Running Get-Date/).first();
  await first.waitFor({timeout:120000});
  await app.screenshot("get-date-live-label");
  const firstText = await first.textContent();
  const second = screen.getByText(/^Running git/).first();
  await second.waitFor({timeout:120000});
  await app.screenshot("git-live-label");
  const secondText = await second.textContent();
  await expect(firstText).toBe("Running Get-Date");
  await expect(secondText).toBe("Running git");
});
