// 无头验收脚本：控制台零报错 + 标题→Day1 流程 + Debug 面板侵蚀矩阵 + 四结局
// 运行：node tools/e2e.mjs [--full]
import { chromium } from "playwright";
import { createServer } from "vite";
import { mkdirSync } from "fs";

const SHOT_DIR = process.env.SHOT_DIR || "/tmp/mtc-shots";
mkdirSync(SHOT_DIR, { recursive: true });

const server = await createServer({ server: { port: 5199 } });
await server.listen();

const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });
const errors = [];
page.on("console", (msg) => { if (msg.type() === "error") errors.push(msg.text()); });
page.on("pageerror", (err) => errors.push("PAGEERROR: " + err.message));

const shot = (name) => page.screenshot({ path: `${SHOT_DIR}/${name}.png` });
const sleep = (ms) => page.waitForTimeout(ms);

await page.goto("http://localhost:5199/");
await sleep(2500);
await shot("01_title");

// 输入名字并开始
await page.fill("#name-input", "测试员");
await page.press("#name-input", "Enter");
await sleep(2000);
await shot("02_day1_house");

// 走出小屋：向下走
await page.keyboard.down("s"); await sleep(1400); await page.keyboard.up("s");
await sleep(1200);
await shot("03_plaza");

// Debug 面板：侵蚀矩阵五档
await page.keyboard.press("`");
await sleep(300);
await shot("04_debug_open");
for (const h of [10, 40, 70, 90, 100]) {
  await page.fill("#dbg-h", String(h));
  await page.click("#dbg-h-set");
  await sleep(700);
  await shot(`05_stage_h${h}`);
}
// 传送遍历全部场景
for (const s of ["bakery", "store", "clinic", "lake", "field", "well", "fogwall", "white_corridor", "white_ward", "plaza", "house"]) {
  await page.click(`[data-tp="${s}"]`);
  await sleep(900);
  await shot(`06_scene_${s}`);
}
// 四结局强制触发
for (const e of ["E1", "E4", "E2", "E3"]) {
  await page.click(`[data-end="${e}"]`);
  await sleep(e === "E3" ? 14000 : 6000);
  await shot(`07_ending_${e}`);
  // 回到游戏继续测试（reload 后需重进）
  if (e !== "E3") {
    await page.reload();
    await sleep(2200);
    await page.fill("#name-input", "测试员");
    await page.press("#name-input", "Enter");
    await sleep(1800);
    await page.keyboard.press("`");
    await sleep(300);
  }
}

console.log("CONSOLE ERRORS:", errors.length);
errors.slice(0, 20).forEach(e => console.log("  -", e));
await browser.close();
await server.close();
process.exit(errors.length ? 1 : 0);
