/**
 * commands/design-validate.mjs — `apt-tools design-validate [path]` (C2).
 *
 * Validates a DESIGN.md file against the canonical frontmatter schema
 * (`design/frontmatter-schema.mjs`). Default path is `./DESIGN.md` in the
 * current working directory.
 *
 * Usage:
 *
 *   apt-tools design-validate                  # validates ./DESIGN.md
 *   apt-tools design-validate path/to/DESIGN.md
 *   apt-tools design-validate --warnings-as-errors
 *
 * Output envelope (stdout):
 *
 *   {
 *     status: 'ok' | 'error',
 *     command: 'design-validate',
 *     path: '<abs path>',
 *     errors: [string, ...],
 *     warnings: [string, ...]
 *   }
 *
 * Exit code is 1 when `errors.length > 0`, or when `warnings.length > 0` and
 * `--warnings-as-errors` was passed.
 */
import { existsSync, readFileSync } from 'node:fs';
import { resolve as resolvePath } from 'node:path';
import { validateDesignMarkdown } from '../design/validate.mjs';
import { parseFlags } from '../util/args.mjs';
import { err, exitWith, ok } from '../util/result.mjs';
/**
 * @param {string | undefined} pathArg — positional arg from the CLI, may be a flag
 * @param {string[] | undefined} extraArgs
 */
export function cmdDesignValidate(pathArg, extraArgs) {
    // The first positional may actually be a flag — parseFlags folds all of
    // args back together and we take the first non-flag as the path.
    const all = pathArg === undefined ? [] : [pathArg, ...(extraArgs ?? [])];
    const flags = parseFlags(all);
    const positional = all.filter((a) => !a.startsWith('--') && a !== 'true' && a !== 'false');
    const targetArg = positional[0];
    const warningsAsErrors = flags.get('warnings-as-errors') === true || flags.get('warnings-as-errors') === 'true';
    const resolved = resolvePath(process.cwd(), targetArg && targetArg.length > 0 ? targetArg : 'DESIGN.md');
    if (!existsSync(resolved)) {
        return err(`DESIGN.md not found at ${resolved}. Run \`/apt:design --new\` first, or pass an explicit path: apt-tools design-validate path/to/DESIGN.md`);
    }
    let text;
    try {
        text = readFileSync(resolved, 'utf8');
    }
    catch (e) {
        const msg = e instanceof Error ? e.message : String(e);
        return err(`failed to read ${resolved}: ${msg}`);
    }
    const result = validateDesignMarkdown(text);
    const hasErrors = result.errors.length > 0;
    const hasWarnings = result.warnings.length > 0;
    const treatAsFailure = hasErrors || (warningsAsErrors && hasWarnings);
    const envelope = {
        status: treatAsFailure ? 'error' : 'ok',
        command: 'design-validate',
        path: resolved,
        errors: result.errors,
        warnings: result.warnings,
    };
    return treatAsFailure ? exitWith(envelope, 1) : ok(envelope);
}
//# sourceMappingURL=design-validate.mjs.map