"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.runFromMetadata = runFromMetadata;
const api_adapter_1 = require("../adapters/api/api-adapter");
const api_1 = require("../steps/api");
const ui_1 = require("../steps/ui");
const assert_1 = require("../steps/assert");
const util_1 = require("../steps/util");
const test_1 = require("../steps/test");
const resource_store_1 = require("../core/resource-store");
const step_registry_1 = require("../core/step-registry");
const spec_registry_1 = require("../core/spec-registry");
const testing_engine_1 = require("../core/testing-engine");
const scenario_filter_1 = require("./scenario-filter");
const lifecycle_1 = require("./lifecycle");
const console_reporter_1 = require("../reporter/console-reporter");
function buildTestDataIndex(data) {
    const index = {};
    if (!Array.isArray(data))
        return index;
    for (const record of data) {
        if (!record?.modelUserKey || !record?.recUserKeyValue)
            continue;
        if (!index[record.modelUserKey]) {
            index[record.modelUserKey] = {};
        }
        index[record.modelUserKey][record.recUserKeyValue] = record.data ?? {};
    }
    return index;
}
async function runFromMetadata(opts) {
    const startedAt = Date.now();
    const registry = new step_registry_1.StepRegistry();
    (0, api_1.registerApiSteps)(registry);
    (0, ui_1.registerUiSteps)(registry);
    (0, assert_1.registerAssertSteps)(registry);
    (0, util_1.registerUtilSteps)(registry);
    (0, test_1.registerTestSteps)(registry);
    const engine = new testing_engine_1.TestingEngine(registry, opts.defaults);
    const scenarios = (0, scenario_filter_1.filterScenarios)(opts.metadata.testing.scenarios, {
        scenarioIds: opts.scenarioIds,
        includeTags: opts.includeTags,
        skipScenarioIds: opts.skipScenarioIds,
    });
    const specRegistry = new spec_registry_1.SpecRegistry();
    const testData = buildTestDataIndex(opts.metadata.testing?.data);
    if (opts.specs) {
        opts.specs(specRegistry);
    }
    const resources = new resource_store_1.SimpleResourceStore();
    const reporter = opts.reporter ?? new console_reporter_1.ConsoleReporter();
    const api = new api_adapter_1.ApiAdapter(opts.api);
    const { PlaywrightAdapter } = await Promise.resolve().then(() => __importStar(require("../adapters/ui/playwright-adapter")));
    const ui = new PlaywrightAdapter(opts.ui);
    const ctxBase = { resources, reporter, api, ui, specRegistry, testData, options: opts.options };
    const uiStarted = { value: false };
    let passed = 0;
    let failed = 0;
    let runError;
    try {
        for (const scenario of scenarios) {
            if ((0, lifecycle_1.scenarioNeedsUi)(scenario)) {
                await (0, lifecycle_1.ensureUiStarted)(ctxBase, uiStarted);
            }
            try {
                await engine.runScenario(scenario, ctxBase);
                passed += 1;
            }
            catch (error) {
                failed += 1;
                runError = error;
                throw error;
            }
        }
    }
    finally {
        reporter.onRunEnd?.({
            ok: !runError,
            total: scenarios.length,
            passed,
            failed,
            durationMs: Date.now() - startedAt,
        });
        if (uiStarted.value) {
            await ui.stop();
        }
    }
}
//# sourceMappingURL=run-from-metadata.js.map