import { mkdirSync, writeFileSync } 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 () => {
  await vite.close();
});

test("TDD-WP0-DATA-002 keeps the fixed local-data warning visible without transfer entry points", async ({ page }) => {
  await page.goto(`${webUrl}/tests/e2e/fixtures/local-data-boundary.html`);
  const fixedCopy = "测试数据仅保存在本机，不自动备份，也不会迁移到正式系统。";
  await expect(page.getByRole("heading", { name: "本机数据" })).toBeVisible();
  await expect(page.getByText(fixedCopy, { exact: true })).toBeVisible();
  await expect(page.getByText("当前 Windows 用户的 Dada 本机数据目录", { exact: true })).toBeVisible();
  await expect(page.getByText(/不提供 Dada 应用层加密或云备份/)).toBeVisible();
  await expect(page.getByText(/机器损坏、重装或删除本机数据目录后不可恢复/)).toBeVisible();
  await expect(page.getByText(/主动下载需要保留的原始生成图或 JPG\/PNG 成品/)).toBeVisible();
  await expect(page.getByRole("button")).toHaveCount(0);
  await expect(page.getByRole("link")).toHaveCount(0);
  const text = await page.locator("body").innerText();
  expect(text).not.toMatch(/[A-Za-z]:\\/);

  await page.reload();
  await expect(page.getByText(fixedCopy, { exact: true })).toBeVisible();
  expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);

  const evidenceDirectory = process.env.DADA_EVIDENCE_DIR_NO_TRANSFER;
  if (evidenceDirectory) {
    mkdirSync(resolve(evidenceDirectory, "screenshots"), { recursive: true });
    await page.screenshot({ path: resolve(evidenceDirectory, "screenshots", "fixed-copy.png") });
    writeFileSync(resolve(evidenceDirectory, "package-scan.json"), `${JSON.stringify({
      absolute_path_exposed: false,
      automatic_backup_entry: false,
      business_import_entry: false,
      editable_project_archive_entry: false,
      migration_entry: false,
      recovery_entry: false,
      status: "passed",
    }, null, 2)}\n`);
  }

  await page.setViewportSize({ height: 844, width: 390 });
  await expect(page.getByText(fixedCopy, { exact: true })).toBeVisible();
  expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
});
