// The check collector: a PASS/FAIL line protocol.  Each check prints
// immediately, failures carry their detail, and the counts are read at the end.

import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import type { Cdp } from "./cdp.js";

export interface ScenarioContext {
	cdp: Cdp;
	baseUrl: string;
	checks: Checks;
}

export interface Scenario {
	// The short name used in run output and for selecting scenarios from the CLI.
	name: string;
	run(ctx: ScenarioContext): Promise<void>;
}

export class Checks {
	private readonly results: { name: string; ok: boolean }[] = [];

	check(name: string, cond: boolean, detail = ""): void {
		this.results.push({ name, ok: cond });
		console.log((cond ? "PASS " : "FAIL ") + name + (detail !== "" && !cond ? `  ${detail}` : ""));
	}

	get passed(): number {
		return this.results.filter((r) => r.ok).length;
	}

	get total(): number {
		return this.results.length;
	}

	get failed(): number {
		return this.total - this.passed;
	}
}

// A screenshot for a human to look at later, never an assertion:
// writes only when YUKEY_E2E_SHOTS_DIR names a destination, and no-ops otherwise.
export async function shot(cdp: Cdp, name: string): Promise<void> {
	const dir = process.env.YUKEY_E2E_SHOTS_DIR;
	if (dir === undefined || dir === "") return;
	mkdirSync(dir, { recursive: true });
	writeFileSync(join(dir, name), await cdp.screenshot());
}
