/**
 * ADR Frontmatter Validation (ADR-017)
 *
 * Validates all ADR markdown files against schemas/adr-frontmatter.schema.json.
 *
 * @task T4792
 */
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { default as AjvImport } from 'ajv';
// Handle ESM/CJS interop for Ajv
const ajvMod = AjvImport;
const Ajv = (typeof ajvMod.default === 'function' ? ajvMod.default : AjvImport);
import { parseAdrFile } from './parse.js';
/** Validate all ADRs in .cleo/adrs/ against the schema */
export async function validateAllAdrs(projectRoot) {
    const adrsDir = join(projectRoot, '.cleo', 'adrs');
    const schemaPath = join(projectRoot, 'schemas', 'adr-frontmatter.schema.json');
    if (!existsSync(schemaPath)) {
        return {
            valid: false,
            errors: [
                {
                    file: 'schemas/adr-frontmatter.schema.json',
                    field: 'schema',
                    message: 'Schema file not found',
                },
            ],
            checked: 0,
        };
    }
    if (!existsSync(adrsDir)) {
        return { valid: true, errors: [], checked: 0 };
    }
    const schema = JSON.parse(readFileSync(schemaPath, 'utf-8'));
    const ajv = new Ajv({ allErrors: true });
    const validate = ajv.compile(schema);
    const files = readdirSync(adrsDir)
        .filter((f) => f.endsWith('.md') && f.startsWith('ADR-'))
        .map((f) => join(adrsDir, f));
    const errors = [];
    for (const filePath of files) {
        const record = parseAdrFile(filePath, projectRoot);
        const valid = validate(record.frontmatter);
        if (!valid && validate.errors) {
            for (const err of validate.errors) {
                errors.push({
                    file: filePath.replace(projectRoot + '/', ''),
                    field: err.instancePath ? err.instancePath.replace('/', '') : 'root',
                    message: err.message ?? 'Validation error',
                });
            }
        }
    }
    return { valid: errors.length === 0, errors, checked: files.length };
}
//# sourceMappingURL=validate.js.map