/**
 * `olam worldspec validate <path>` — validate a worldspec YAML against the
 * v1 schema. Exits 0 on valid, 20 on schema violation, 21 on file-not-found,
 * 1 on internal error.
 *
 * Output format:
 *   - --format=human (default): location-aware error frames with hints
 *   - --format=json: structured ValidationError[] for IDE / CI consumption
 *
 * Pre-rendered errors carry attacker-controlled strings sanitised via
 * stripCtrl from @olam/core/worldspec — see error-formatter.ts header.
 */
import { existsSync, readFileSync } from 'node:fs';
import { resolve as resolvePath } from 'node:path';
import { formatValidationErrors, validateWorldspec, } from '@olam/core/src/worldspec/index.js';
import { EXIT_GENERIC_ERROR, EXIT_WORLDSPEC_FILE_NOT_FOUND, EXIT_WORLDSPEC_INVALID, } from '../../exit-codes.js';
import { printError, printSuccess } from '../../output.js';
export function registerWorldspecValidate(parent) {
    parent
        .command('validate <path>')
        .description('Validate a worldspec YAML against the v1 schema')
        .option('--format <format>', 'Output format: human | json', (value) => {
        if (value !== 'human' && value !== 'json') {
            throw new Error(`--format must be 'human' or 'json' (got '${value}')`);
        }
        return value;
    }, 'human')
        .action(async (pathArg, opts) => {
        const absPath = resolvePath(process.cwd(), pathArg);
        if (!existsSync(absPath)) {
            printError(`worldspec not found at ${absPath}`);
            process.exit(EXIT_WORLDSPEC_FILE_NOT_FOUND);
        }
        let yamlSource;
        try {
            yamlSource = readFileSync(absPath, 'utf8');
        }
        catch (err) {
            printError(`failed to read ${absPath}: ${err.message}`);
            process.exit(EXIT_GENERIC_ERROR);
        }
        const result = validateWorldspec(yamlSource);
        if (result.ok) {
            if (opts.format === 'json') {
                process.stdout.write(JSON.stringify({ ok: true }, null, 2) + '\n');
            }
            else {
                printSuccess(`${pathArg}: valid worldspec (schemaVersion: 1)`);
            }
            process.exit(0);
        }
        if (opts.format === 'json') {
            process.stdout.write(JSON.stringify({ ok: false, errors: result.errors }, null, 2) + '\n');
        }
        else {
            const formatted = formatValidationErrors(result.errors, {
                sourcePath: pathArg,
                yamlSource,
                color: process.stdout.isTTY,
            });
            process.stderr.write(formatted + '\n');
        }
        process.exit(EXIT_WORLDSPEC_INVALID);
    });
}
//# sourceMappingURL=validate.js.map