export function createDoctorFixPlan(dryRun) {
    return {
        operations: [],
        changed: false,
        dryRun,
        backups: [],
        manualActions: [],
    };
}
export function addDoctorFixOperation(ctx, operation) {
    ctx.plan.operations.push(operation);
    if (operation.status === "applied")
        ctx.plan.changed = true;
    if (operation.backupPath && !ctx.plan.backups.includes(operation.backupPath)) {
        ctx.plan.backups.push(operation.backupPath);
    }
    if ((operation.status === "blocked" || operation.status === "failed") && operation.reason) {
        ctx.plan.manualActions.push(operation.reason);
    }
}
export function recordDoctorFix(ctx, operation) {
    const requestedStatus = operation.status ?? "applied";
    const status = ctx.dryRun && requestedStatus === "applied" ? "planned" : requestedStatus;
    addDoctorFixOperation(ctx, {
        severity: operation.severity ?? "info",
        safetyTier: operation.safetyTier ?? ctx.fixLevel,
        ...operation,
        status,
    });
}
function operationToAction(operation) {
    if (operation.status !== "applied" && operation.status !== "planned")
        return null;
    return operation.reason ?? `${operation.id} ${operation.status}`;
}
function operationToSkipped(operation) {
    if (operation.status !== "skipped" && operation.status !== "blocked" && operation.status !== "failed")
        return null;
    return operation.reason ?? `${operation.id} ${operation.status}`;
}
export function createDoctorFixReport(ctx, mcp, globalSync) {
    const actions = ctx.plan.operations
        .map(operationToAction)
        .filter((message) => typeof message === "string");
    const skipped = ctx.plan.operations
        .map(operationToSkipped)
        .filter((message) => typeof message === "string");
    return {
        changed: ctx.plan.changed,
        actions,
        skipped,
        mcp,
        globalSync,
        backups: ctx.plan.backups,
        dryRun: ctx.dryRun,
        fixPlan: ctx.plan,
    };
}
export function summarizeDoctorChecks(results) {
    return {
        warnings: results.filter((r) => r.status === "warn").length,
        errors: results.filter((r) => r.status === "fail").length,
    };
}
export function buildDoctorPostFixCheck(beforeResults, afterResults, plan) {
    const before = summarizeDoctorChecks(beforeResults);
    const after = summarizeDoctorChecks(afterResults);
    const beforeTotal = before.warnings + before.errors;
    const afterTotal = after.warnings + after.errors;
    return {
        before,
        after,
        fixed: Math.max(0, beforeTotal - afterTotal),
        remainingWarnings: after.warnings,
        remainingErrors: after.errors,
        requiresManualAction: plan.manualActions.length > 0 || after.errors > 0,
    };
}
