"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaResources = void 0;
const json_schema_1 = require("../validator/json-schema");
const step_registry_1 = require("../validator/schemas/step-registry");
const ENVELOPE_URI = 'mabl-schema://envelope';
const STEP_INDEX_URI = 'mabl-schema://step';
const STEP_PREFIX = 'mabl-schema://step/';
const ENVELOPE_SCHEMA = Object.freeze({
    $id: ENVELOPE_URI,
    $schema: 'https://json-schema.org/draft/2020-12/schema',
    type: 'object',
    required: ['steps'],
    description: 'Top-level envelope for a mabl test. The test is a list of steps; each step is a singleton map keyed by step type.',
    properties: {
        steps: {
            type: 'array',
            description: 'Each step is a singleton object: { StepType: { ...descriptor } }.',
            items: { $ref: STEP_INDEX_URI },
        },
    },
});
class SchemaResources {
    examples;
    testType;
    constructor(examples, testType = 'browser') {
        this.examples = examples;
        this.testType = testType;
    }
    resolve(uri) {
        if (uri === ENVELOPE_URI)
            return ENVELOPE_SCHEMA;
        if (uri === STEP_INDEX_URI)
            return this.buildStepIndex();
        if (uri.startsWith(STEP_PREFIX)) {
            const name = uri.slice(STEP_PREFIX.length);
            return this.buildStepSchema(name);
        }
        return undefined;
    }
    listResources() {
        const list = [
            { uri: ENVELOPE_URI, description: 'Top-level test envelope' },
            { uri: STEP_INDEX_URI, description: 'Index of all step types' },
        ];
        for (const name of (0, step_registry_1.getStepTypeNames)(this.testType)) {
            list.push({
                uri: `${STEP_PREFIX}${name}`,
                description: `Schema for the ${name} step`,
            });
        }
        return list;
    }
    buildStepIndex() {
        const oneOf = (0, step_registry_1.getStepTypeNames)(this.testType).map((name) => ({
            title: name,
            $ref: `${STEP_PREFIX}${name}`,
        }));
        return {
            $id: STEP_INDEX_URI,
            $schema: 'https://json-schema.org/draft/2020-12/schema',
            description: 'A step is a singleton map: one step-type key, one descriptor value.',
            oneOf,
        };
    }
    buildStepSchema(name) {
        const generated = (0, json_schema_1.getStepJsonSchema)(name, this.testType);
        if (!generated)
            return undefined;
        return {
            ...generated,
            $id: `${STEP_PREFIX}${name}`,
            'x-examples': this.exampleIdsForStep(name),
        };
    }
    exampleIdsForStep(stepTypeName) {
        const target = `${STEP_PREFIX}${stepTypeName}`;
        return Object.values(this.examples)
            .filter((example) => example.validatedAgainst === target)
            .map((example) => example.id);
    }
}
exports.SchemaResources = SchemaResources;
