import * as fs from 'node:fs';
import { createRequire } from 'node:module';
import { GlobalConfigSchema } from '@olam/core/src/global-config/index.js';
import { globalConfigPath } from '@olam/core/src/global-config/store.js';
const _require = createRequire(import.meta.url);
const { parse: parseWithMap } = _require('json-source-map');
export function registerConfig(program) {
    const config = program.command('config').description('Manage global olam configuration');
    config
        .command('validate [path]')
        .description('Validate ~/.olam/config.json (or a custom path) against the schema')
        .action((filePath) => {
        const resolvedPath = filePath ?? globalConfigPath();
        if (!fs.existsSync(resolvedPath)) {
            process.stderr.write(`config file not found: ${resolvedPath}\n`);
            process.exit(1);
        }
        let raw;
        try {
            raw = fs.readFileSync(resolvedPath, 'utf-8');
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            process.stderr.write(`cannot read ${resolvedPath}: ${msg}\n`);
            process.exit(1);
        }
        let parsed;
        let pointers;
        try {
            const result = parseWithMap(raw);
            parsed = result.data;
            pointers = result.pointers;
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            process.stderr.write(`${resolvedPath}: invalid JSON — ${msg}\n`);
            process.exit(1);
        }
        const result = GlobalConfigSchema.safeParse(parsed);
        if (result.success) {
            process.exit(0);
        }
        for (const issue of result.error.issues) {
            const pointer = '/' + issue.path.join('/');
            const entry = pointers[pointer];
            const rawLine = entry?.value?.line ?? entry?.key?.line ?? -1;
            const lineStr = rawLine >= 0 ? `Line ${rawLine + 1}: ` : '';
            process.stderr.write(`${lineStr}${pointer}: ${issue.message}\n`);
        }
        process.exit(1);
    });
}
//# sourceMappingURL=config.js.map