/// <reference lib="dom" />
import { expect } from "e2e";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("A reloaded draft can reattach the same file after switching machines", WEB, async ({ t3, app, browser, screen }) => {
  const repo = { ".git/config": '[remote "origin"]\n\turl = https://github.com/scenario/demo.git\n' };
  await t3.project("demo-project", repo);
  const second = makeState(SECOND_HOME);
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await second.state.project("demo-project", repo);
    await t3.open("/settings/connections");
    await screen.getByRole("button", "List", { exact: true }).tap();
    const rename = async (label: string) => {
      await screen.getByRole("button", "More actions for Scenario", { exact: true }).tap();
      await screen.getByRole("menuitem", "Rename…", { exact: true }).tap();
      const dialog = screen.getByRole("dialog", "Rename environment");
      await dialog.getByRole("textbox", "Label", { exact: true }).fill(label);
      await dialog.getByRole("button", "Save", { exact: true }).tap();
      await screen.getByRole("button", `More actions for ${label}`, { exact: true }).waitFor();
    };
    await screen.getByRole("button", "Add environment", { exact: true }).tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment", { exact: true }).tap();
    await screen.getByRole("button", "More actions for Scenario", { exact: true }).waitFor({ timeout: 60_000 });
    await rename("Machine B");
    await app.open("/");
    const runOn = screen.getByRole("combobox", "Run on", { exact: true });
    const switchTo = async (label: string) => {
      await runOn.tap();
      await screen.getByRole("option", label, { exact: true }).tap();
      await runOn.getByText(label, { exact: true }).waitFor();
    };
    if (!(await runOn.textContent())?.includes("Scenario")) await switchTo("Scenario");
    const composer = browser.locator("[data-chat-composer-form]");
    const chip = browser.locator('[data-chat-composer-form] [aria-label^="File attachment, report.pdf,"]');
    const readyChip = browser.locator('[data-chat-composer-form] [aria-label="File attachment, report.pdf, 4 KB"]');
    const submit = browser.locator('[data-chat-composer-form] button[type="submit"]');
    const prompt = "Summarize the attached report.";
    await composer.getByRole("textbox").fill(prompt);
    const pickFile = async () => {
      await screen.getByRole("button", "Attach files", { exact: true }).tap();
      await browser.evaluate(() => {
        const picker = document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
        const files = new DataTransfer();
        files.items.add(new File(["%PDF-1.4\n% Synthetic report for attachment routing proof.\n".padEnd(4096, " ")], "report.pdf", { type: "application/pdf", lastModified: 1700000000000 }));
        picker.files = files.files;
        picker.dispatchEvent(new Event("change", { bubbles: true }));
        return null;
      });
    };
    const upload = browser.waitForResponse(/\/api\/.*attachments/);
    await pickFile();
    await upload;
    await readyChip.waitFor();
    await app.screenshot("01-uploaded-on-machine-a");

    // No reload yet: the original File is still present, so it can upload to the new machine.
    const uploadB = browser.waitForResponse(/\/api\/.*attachments/);
    await switchTo("Machine B");
    await uploadB;
    await readyChip.waitFor();
    await app.screenshot("02-local-bytes-upload-on-machine-b");
    const uploadA = browser.waitForResponse(/\/api\/.*attachments/);
    await switchTo("Scenario");
    await uploadA;
    await readyChip.waitFor();
    await browser.reload();
    await readyChip.waitFor();
    await app.screenshot("03-reloaded-file-on-machine-a");
    // Local bytes are gone after reload. A same-machine context change must keep the upload reference.
    await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
    await screen.getByRole("option", "New worktree", { exact: true }).tap();
    await readyChip.waitFor();
    await app.screenshot("04-same-machine-context-after-reload-keeps-file");
    await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
    await screen.getByRole("option", "Current checkout", { exact: true }).tap();

    await switchTo("Machine B");
    await browser.locator('[data-chat-composer-form] [aria-label^="File attachment, report.pdf,"][aria-label$="attach again"], [data-chat-composer-form] [aria-label^="File attachment, report.pdf,"][aria-label$="upload failed"]').waitFor();
    const neededReattach = (await chip.getAttribute("aria-label"))?.includes("attach again") ?? false;
    const sendBlocked = !(await submit.isEnabled());
    await app.screenshot("05-reloaded-file-after-machine-switch");

    // Always perform the same selection, even on base where it is incorrectly discarded.
    await pickFile();
    if (neededReattach) await readyChip.waitFor();
    await app.screenshot("06-reselect-same-report");
    const reselectedFileReady = (await chip.getAttribute("aria-label")) === "File attachment, report.pdf, 4 KB";
    await submit.tap();
    let sent = false;
    if (reselectedFileReady) {
      await screen.getByRole("region", "Conversation", { exact: true }).getByRole("button", "File attachment, report.pdf, 4 KB", { exact: true }).waitFor();
      await screen.getByRole("heading", "Done", { exact: true }).waitFor();
      await screen.getByRole("button", /^Worked for /).waitFor();
      await browser.evaluate(() => {
        document.querySelector('[aria-label="Conversation"] [aria-label="File attachment, report.pdf, 4 KB"]')?.scrollIntoView({ block: "center", behavior: "instant" });
        return null;
      });
      sent = true;
    } else {
      await screen.getByText("Attachment 'report.pdf' failed to upload.", { exact: true }).waitFor();
    }
    await app.screenshot("07-send-after-reselect");
    expect({ neededReattach, sendBlocked, reselectedFileReady, sent }).toEqual({ neededReattach: true, sendBlocked: true, reselectedFileReady: true, sent: true });
  } finally {
    await server.stop();
  }
});
