"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEventsFromPuppeteerTest = exports.verifyPuppeteerTest = void 0;
const replay_1 = require("@puppeteer/replay");
const puppeteer_1 = require("puppeteer");
const fs = require("fs");
const path = require("path");
const test_1 = require("@syftdata/test");
const glob_1 = require("glob");
const utils_1 = require("@syftdata/common/lib/utils");
async function getBrowser(headless) {
    const extensionsFolder = path.join(__dirname, '../../assets/chrome-extensions/react-devtools');
    const a = await puppeteer_1.default.launch({
        headless: headless ? 'new' : false,
        devtools: true,
        args: [
            `--disable-extensions-except=${extensionsFolder}`,
            `--load-extension=${extensionsFolder}`
        ]
    });
    return a;
}
async function verifyPuppeteerTest(filePath, headless) {
    const recordingText = fs.readFileSync(filePath, 'utf8');
    const flow = (0, replay_1.parse)(JSON.parse(recordingText));
    const browser = await getBrowser(headless);
    const page = await browser.newPage();
    const extension = new test_1.SyftPuppeteerVerifyExtension(browser, page, {
        timeout: 10000
    });
    const runner = await (0, replay_1.createRunner)(flow, extension);
    await runner.run();
    await browser.close();
    const failedSteps = extension.failedEvents;
    if (failedSteps.length === 0) {
        (0, utils_1.logInfo)(`:heavy_check_mark: ${flow?.title ?? ''} completed.`);
    }
    else {
        (0, utils_1.logError)(`${flow?.title ?? 'Test'} failed with invalid instrumentation`);
        (0, utils_1.logDetail)(`You could try using syft auto instrumentation. Please sign up at https://studio.syftdata.com to get started.`);
    }
    return failedSteps.length === 0;
}
exports.verifyPuppeteerTest = verifyPuppeteerTest;
function getEventsFromPuppeteerTest(dirPath) {
    const events = [];
    const files = glob_1.glob.sync(`${dirPath}/**/*`, {
        nodir: true
    });
    files.forEach((filePath) => {
        const recordingText = fs.readFileSync(filePath, 'utf8');
        const recording = (0, replay_1.parse)(JSON.parse(recordingText));
        for (let i = 0; i < recording.steps.length; i++) {
            if (i > 0) {
                const eventName = (0, test_1.getEventNameFrom)(recording.steps[i]);
                if (eventName != null) {
                    if (!(eventName in events)) {
                        events.push(eventName);
                    }
                }
            }
        }
    });
    return events;
}
exports.getEventsFromPuppeteerTest = getEventsFromPuppeteerTest;
