import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

// Observation only: every invocation runs the installed real Azure CLI unchanged.
const logger = `#!/usr/bin/env python3
import os,sys,json
with open(os.environ['SCOPING_TRACE'], 'a') as out:
    out.write(json.dumps(sys.argv[1:])+'\\n')
os.execv('/usr/bin/az', ['/usr/bin/az']+sys.argv[1:])
`;

test("Azure PR reads stay scoped with an unrelated remote containing spaces", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Azure remote scoping");
  const trace = await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const env = yield* HostProcess.Environment;
    yield* fs.writeFileString(path.join(T3_HOME, "bin", "az"), logger);
    yield* fs.chmod(path.join(T3_HOME, "bin", "az"), 0o755);
    yield* fs.writeFileString(env.SCOPING_TRACE!, "");
    yield* run("git", ["fetch", env.SCOPING_SEED_REPO!, "pr44667-evidence"], {cwd: project});
    yield* run("git", ["checkout", "-B", "pr44667-evidence", "FETCH_HEAD"], {cwd: project});
    yield* run("git", ["remote", "add", "origin", "https://dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test"], {cwd: project});
    yield* run("git", ["remote", "add", "backup", path.join(T3_HOME, "My Backups", "app")], {cwd: project});
    yield* fs.writeFileString(path.join(project, "t3.json"), JSON.stringify({defaultThreadEnvMode:"local"}));
    return env.SCOPING_TRACE!;
  }));
  const thread = await t3.thread({project, title:"Inspect Azure PR", messages:["hello"]});
  await t3.open(thread);
  await screen.getByText("#510", {exact:false}).first().tap();
  await screen.getByText("Factory proof: remote URL spaces", {exact:true}).first().waitFor({timeout:60000});
  await app.screenshot("azure-pr-with-backup-remote-spaces");
  const calls = await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.readFileString(trace)));
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(trace + "." + Date.now() + ".jsonl", calls)));
  const reads = calls.split("\n").filter(Boolean).map(line => JSON.parse(line) as string[]).filter(args => args[0] === "repos" && args[1] === "pr" && args[2] === "show");
  expect(reads.length).toBeGreaterThan(0);
  expect(reads.every(args => args.includes("--organization") && args[args.indexOf("--detect")+1] === "false")).toBe(true);
});
