/// <reference lib="dom" />
import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const fixture = readFileSync(new URL("../../apps/web/test/fixtures/disk-images/demo.dmg", import.meta.url));
function image(name: string) {
  const trailer = Buffer.from(fixture.subarray(-512));
  const offset = Number(trailer.readBigUInt64BE(216));
  const length = Number(trailer.readBigUInt64BE(224));
  const plist = Buffer.from(fixture.subarray(offset, offset + length).toString().replaceAll("disk image (Apple_HFS : 4)", name));
  trailer.writeBigUInt64BE(BigInt(plist.length), 224);
  return Buffer.concat([fixture.subarray(0, offset), plist, trailer]);
}
const cases = [
  ["original.dmg", "disk image (Apple_HFS : 4)"],
  ["chatgpt.dmg", "ChatGPT 10 (Apple_HFS : 4)"],
  ["usb-driver.dmg", "USB Driver (Apple_HFS : 4)"],
  ["os-patches.dmg", "OS Patches (Apple_HFS : 4)"],
  ["apfs-guide.dmg", "Apple_APFS Guide (Apple_HFS : 4)"],
  ["real-apfs.dmg", "Container (Apple_APFS : 2)"],
  ["metadata.dmg", "Protective Master Boot Record (MBR : 0)"],
];
test("HFS+ partition labels do not classify the partition type", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Disk image samples", Object.fromEntries(cases.map(([file, name]) => [file!, image(name!)])));
  const thread = await t3.thread({project, title: "Inspect disk images", messages: ["Start"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("button", "Maximize panel", {exact:true}).tap();
  const results: string[] = [];
  for (const [file] of cases) {
    await screen.getByRole("treeitem", file!).tap();
    await screen.getByText(/^(Demo 1\.0|Previews support disk images with an HFS\+ volume\.|This disk image uses APFS, which cannot be previewed yet\.)$/).waitFor({timeout: 60_000});
    const result = await browser.evaluate(() => {
      const text = document.body.innerText;
      if (text.includes("This disk image uses APFS")) return "apfs";
      if (text.includes("Previews support disk images with an HFS+ volume")) return "unsupported";
      if (text.includes("Demo 1.0") && text.includes("Demo.app")) return "hfs";
      return "unexpected";
    });
    results.push(result!);
    await app.screenshot(file!.replace(".dmg", ""));
  }
  expect(results).toEqual(["hfs", "hfs", "hfs", "hfs", "hfs", "apfs", "unsupported"]);
});
