// engine/errors/recovery-registry.ts — SPEC-902: Load and match error recovery rules
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
function isRecoveryConfig(x) {
    if (x === null || typeof x !== 'object') {
        return false;
    }
    const obj = x;
    return typeof obj.schemaVersion === 'number' && Array.isArray(obj.rules);
}
export class RecoveryRegistry {
    rules = [];
    rulesPath;
    constructor(deps) {
        this.rulesPath = deps.rulesPath;
    }
    async load() {
        if (!existsSync(this.rulesPath)) {
            console.warn(`[Planu] Error recovery registry not found: ${this.rulesPath}`);
            return;
        }
        try {
            const raw = await readFile(this.rulesPath, 'utf-8');
            const parsed = JSON.parse(raw);
            if (!isRecoveryConfig(parsed)) {
                console.warn('[Planu] Error recovery registry has invalid structure');
                return;
            }
            this.rules = parsed.rules;
        }
        catch (err) {
            console.warn('[Planu] Failed to load error recovery registry:', err);
        }
    }
    match(err) {
        if (this.rules.length === 0) {
            return null;
        }
        const code = extractCode(err);
        const message = extractMessage(err);
        for (const rule of this.rules) {
            if (rule.match.code && rule.match.code === code) {
                return rule;
            }
            if (rule.match.messagePattern) {
                try {
                    const pattern = new RegExp(rule.match.messagePattern, 'i');
                    if (pattern.test(message)) {
                        return rule;
                    }
                }
                catch {
                    // Invalid regex — skip this rule
                }
            }
        }
        return null;
    }
    get rulesLoaded() {
        return this.rules.length > 0;
    }
    static resolvePath(projectPath) {
        return join(projectPath, 'src', 'config', 'registries', 'error-recovery.json');
    }
}
function extractCode(err) {
    if (err === null || err === undefined) {
        return undefined;
    }
    if (typeof err === 'object') {
        const obj = err;
        if (typeof obj.code === 'string') {
            return obj.code;
        }
    }
    return undefined;
}
function extractMessage(err) {
    if (err instanceof Error) {
        return err.message;
    }
    if (typeof err === 'string') {
        return err;
    }
    if (err === null || err === undefined) {
        return '';
    }
    try {
        return JSON.stringify(err);
    }
    catch {
        return '';
    }
}
//# sourceMappingURL=recovery-registry.js.map