const { test, expect } = require("@playwright/test");

test("play-classic loads and exposes debug bridge", async ({ page }) => {
    await page.goto("/play-classic?seed=42");
    await page.waitForFunction(() => typeof window.__FERROUS_DEBUG__ === "object");

    const seed = await page.evaluate(() => window.__FERROUS_DEBUG__.seed());
    expect(seed).toBe(42);

    const legalMoves = await page.evaluate(() => window.__FERROUS_DEBUG__.legalMoves());
    expect(Array.isArray(legalMoves)).toBeTruthy();
});

test("keyboard parity: Space draws and U undoes", async ({ page }) => {
    await page.goto("/play-classic?seed=42");
    await page.waitForFunction(
        () =>
            typeof window.__FERROUS_DEBUG__ === "object" &&
            window.__FERROUS_DEBUG__.seed() !== null
    );

    const baselineHistoryLen = await page.evaluate(
        () => window.__FERROUS_DEBUG__.moveHistory().length
    );

    await page.keyboard.press("Space");
    await expect
        .poll(async () => await page.evaluate(() => window.__FERROUS_DEBUG__.moveHistory().length))
        .toBe(baselineHistoryLen + 1);

    await page.keyboard.press("KeyU");
    await expect
        .poll(async () => await page.evaluate(() => window.__FERROUS_DEBUG__.moveHistory().length))
        .toBe(baselineHistoryLen);
});

test("debug failure report contains replay diagnostics", async ({ page }) => {
    await page.goto("/play-classic?seed=42");
    await page.waitForFunction(() => typeof window.__FERROUS_DEBUG__ === "object");

    const report = await page.evaluate(() => window.__FERROUS_DEBUG__.failureReport());
    expect(report).not.toBeNull();
    expect(typeof report.seed).toBe("number");
    expect(Array.isArray(report.moveHistory)).toBeTruthy();
    expect(Array.isArray(report.legalMoves)).toBeTruthy();
    expect(report.currentState).toBeTruthy();
    expect(report.invariants).toBeTruthy();
});

test("replay payload builder exports schema-v2 moves", async ({ page }) => {
    await page.goto("/play-classic?seed=42");
    await page.waitForFunction(() => typeof window.__FERROUS_DEBUG__ === "object");

    await page.keyboard.press("Space");

    await expect
        .poll(async () => await page.evaluate(() => window.__FERROUS_DEBUG__.replayPayload() !== null))
        .toBe(true);
    const payload = await page.evaluate(() => window.__FERROUS_DEBUG__.replayPayload());
    expect(payload.schema_version).toBe(2);
    expect(payload.draw_mode).toMatch(/Draw(One|Three)/);
    expect(payload.mode).toBe("Classic");
    expect(Array.isArray(payload.moves)).toBeTruthy();
    expect(payload.moves.length).toBeGreaterThan(0);
    expect(payload.win_move_index).toBe(payload.moves.length - 1);
});
