"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enrichValidationResult = enrichValidationResult;
function enrichValidationResult(args) {
    const { result, jsonSteps, testType, suggestions, examples } = args;
    return {
        ...result,
        errors: result.errors.map((error) => enrichIssue({ issue: error, jsonSteps, testType, suggestions, examples })),
        warnings: result.warnings.map((warning) => enrichIssue({ issue: warning, jsonSteps, testType, suggestions, examples })),
    };
}
function enrichIssue(args) {
    const { issue, jsonSteps, suggestions, examples } = args;
    if (issue.suggestion !== undefined || issue.example !== undefined) {
        return issue;
    }
    const entry = suggestions[issue.code];
    if (entry) {
        return {
            ...issue,
            suggestion: entry.suggestion,
            ...(entry.example !== undefined && { example: entry.example }),
        };
    }
    const stepTypeName = resolveStepTypeName(issue.path, jsonSteps);
    if (issue.code.startsWith('zod.') && stepTypeName) {
        const schemaUri = `mabl-schema://step/${stepTypeName}`;
        const fieldRef = formatFieldPath(issue.path);
        const lead = issue.code === 'zod.invalid_union'
            ? `The field ${fieldRef} accepts multiple shapes and none matched. Fetch ${schemaUri} to see the valid variants for ${stepTypeName} and pick the one that matches the data.`
            : `Check the schema for ${stepTypeName} (${schemaUri}) — the field at ${fieldRef} doesn't match the expected shape.`;
        const example = findExampleByStepType(examples, stepTypeName);
        if (example) {
            return {
                ...issue,
                suggestion: `${lead} The example "${example.id}" shows a working ${stepTypeName} step.`,
                example: `examples://${example.id}`,
            };
        }
        return { ...issue, suggestion: lead };
    }
    return issue;
}
function formatFieldPath(path) {
    const rest = path[0] === 'steps' && typeof path[1] === 'number' ? path.slice(2) : path;
    if (rest.length === 0)
        return '(root)';
    return `\`${rest.join('.')}\``;
}
function resolveStepTypeName(path, jsonSteps) {
    if (path[0] !== 'steps' || typeof path[1] !== 'number')
        return undefined;
    const stepIndex = path[1];
    const steps = jsonSteps?.steps;
    if (!Array.isArray(steps))
        return undefined;
    const step = steps[stepIndex];
    if (typeof step !== 'object' || step === null)
        return undefined;
    const keys = Object.keys(step);
    if (keys.length !== 1)
        return undefined;
    return keys[0];
}
function findExampleByStepType(examples, stepTypeName) {
    for (const example of Object.values(examples)) {
        if (example.validatedAgainst === `mabl-schema://step/${stepTypeName}`) {
            return example;
        }
    }
    return undefined;
}
