import { mkdirSync } from "node:fs";
import { resolve } from "node:path";

import { expect, test } from "@playwright/test";
import { createServer, type ViteDevServer } from "vite";

let vite: ViteDevServer;
let webUrl: string;

test.beforeAll(async () => {
  vite = await createServer({ configFile: false, root: process.cwd(), server: { host: "127.0.0.1", port: 0 } });
  await vite.listen();
  const address = vite.httpServer?.address();
  if (!address || typeof address === "string") throw new Error("Vite did not expose a test port.");
  webUrl = `http://127.0.0.1:${address.port}`;
});

test.afterAll(async () => vite.close());

test("TDD-WP0-STO-001 and STO-003 render the exact full action matrix", async ({ page }) => {
  await page.goto(`${webUrl}/tests/e2e/fixtures/storage-capacity.html`);
  await expect(page.getByRole("heading", { name: "本机存储容量" })).toBeVisible();
  await expect(page.locator("[data-status]")).toHaveText("full");
  await expect(page.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "5368709120");
  await expect(page.locator("table").first().getByRole("row").filter({ hasText: "binary_write" })).toContainText("reject_capacity");
  await expect(page.locator("table").first().getByRole("row").filter({ hasText: "project_json_write" })).toContainText("allow");
  await expect(page.getByRole("heading", { name: "存储不可用" })).toBeVisible();
  await expect(page.locator("[data-unavailable] tr").filter({ hasText: "explicit_cleanup" })).toContainText("reject_uncommitted");
  const directory = process.env.DADA_EVIDENCE_DIR_STO_001;
  if (directory) {
    mkdirSync(resolve(directory, "screenshots"), { recursive: true });
    await page.screenshot({ path: resolve(directory, "screenshots", "capacity-bar.png") });
  }
  const unavailableDirectory = process.env.DADA_EVIDENCE_DIR_STO_003_UNAVAILABLE;
  if (unavailableDirectory) {
    mkdirSync(resolve(unavailableDirectory, "screenshots"), { recursive: true });
    await page.screenshot({ path: resolve(unavailableDirectory, "screenshots", "unavailable.png"), fullPage: true });
  }
});
