// tools/auto-update-spec.ts — auto_update_spec handler (SPEC-170)
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { specStore } from '../storage/index.js';
import { autoUpdateSpecFromCode } from '../engine/living-spec/auto-updater.js';
import { stripFrontmatter } from '../engine/frontmatter-parser.js';
import { readSpecContent as readRawSpecContent } from '../engine/spec-reader.js';
import { jsonResult, errJson } from './response-helpers.js';
const execFileAsync = promisify(execFile);
/**
 * Compute git diff for the current working directory.
 * Returns empty string when git is unavailable or produces no diff.
 * Uses async execFile to avoid blocking the event loop during the git call.
 */
async function computeGitDiff() {
    try {
        const { stdout } = await execFileAsync('git', ['diff', 'HEAD'], {
            encoding: 'utf-8',
            timeout: 10_000,
        });
        return stdout;
    }
    catch {
        return '';
    }
}
export async function handleAutoUpdateSpec(args) {
    const { projectId, specId, codeDiff, autoApply = false } = args;
    // 1. Load spec metadata
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return errJson({ message: `Spec ${specId} not found in project ${projectId}` });
    }
    // 2. Resolve diff — use provided diff or fall back to git diff
    const resolvedDiff = codeDiff ?? (await computeGitDiff());
    // 3. Read spec file content for AC extraction (strip YAML frontmatter)
    const raw = await readRawSpecContent(spec.specPath);
    const specContent = raw !== null ? stripFrontmatter(raw) : '';
    // 4. Run auto-updater
    const result = autoUpdateSpecFromCode(specId, resolvedDiff, specContent, autoApply);
    return jsonResult({ ...result, message: result.summary });
}
//# sourceMappingURL=auto-update-spec.js.map