"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cucumber_1 = require("@cucumber/cucumber");
const promises_1 = __importDefault(require("node:fs/promises"));
const browser_1 = require("../runtime/browser");
const resources_1 = require("../runtime/resources");
const failure_screenshots_1 = require("./failure-screenshots");
(0, cucumber_1.Before)(async function (scenario) {
    (0, cucumber_1.setDefaultTimeout)(this.config.timeout);
    this.featureUri = scenario.pickle.uri;
    this.featureName = (0, resources_1.deriveFeatureResourceName)(this.featureUri);
    this.browser = await (0, browser_1.launchBrowser)(this.config);
    this.context = await this.browser.newContext({
        viewport: this.config.viewport
    });
    if (this.config.trace) {
        await this.context.tracing.start({ screenshots: true, snapshots: true });
    }
    this.page = await this.context.newPage();
    this.page.setDefaultTimeout(this.config.timeout);
});
(0, cucumber_1.AfterStep)(async function (step) {
    if ((0, failure_screenshots_1.shouldCaptureFailureScreenshot)(step.result?.status, this.config.screenshotOnFailure)) {
        await (0, failure_screenshots_1.attachFailureScreenshot)(this);
    }
});
(0, cucumber_1.After)(async function (scenario) {
    if (this.context && this.config.trace) {
        const tracePath = `reports/traces/${sanitizeFileName(scenario.pickle.name)}.zip`;
        await promises_1.default.mkdir('reports/traces', { recursive: true });
        await this.context.tracing.stop({ path: tracePath });
        await this.attach(`Trace: ${tracePath}`, 'text/plain');
    }
    await this.context?.close();
    await this.browser?.close();
});
function sanitizeFileName(value) {
    return value.replace(/[^a-z0-9-_]+/gi, '-').replace(/^-|-$/g, '').toLowerCase();
}
