import { hashProjectPath } from '../storage/base-store.js';
import { listSpecs } from '../storage/spec-store.js';
import { loadSessionState } from '../storage/session-state-store.js';
import { buildHandoffText, fetchPendingCriteria } from '../engine/session-handoff-generator.js';
import { execFile as execFileCb } from 'node:child_process';
import { promisify } from 'node:util';
const execFile = promisify(execFileCb);
async function getGitInfo(projectPath) {
    try {
        const [statusResult, branchResult] = await Promise.all([
            execFile('git', ['status', '--short'], { cwd: projectPath }),
            execFile('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: projectPath }),
        ]);
        const lines = statusResult.stdout.trim().split('\n').filter(Boolean);
        const staged = lines.filter((l) => {
            const ch = l[0];
            return ch !== ' ' && ch !== '?';
        }).length;
        const modified = lines.filter((l) => {
            const ch = l[1];
            return ch !== ' ' && ch !== '?';
        }).length;
        return { branch: branchResult.stdout.trim(), staged, modified };
    }
    catch {
        return { branch: null, staged: 0, modified: 0 };
    }
}
export async function handleSessionHandoff(args) {
    const projectId = args.projectId ?? hashProjectPath(args.projectPath);
    const [specs, sessionState, gitInfo] = await Promise.all([
        /* v8 ignore next */ listSpecs(projectId).catch(() => []),
        /* v8 ignore next */ loadSessionState(args.projectPath).catch(() => null),
        getGitInfo(args.projectPath),
    ]);
    const activeSpec = specs.find((s) => s.status === 'implementing' || s.status === 'review') ?? null;
    const nextSpec = specs.find((s) => s.status === 'approved') ?? null;
    const pendingCriteria = activeSpec !== null ? await fetchPendingCriteria(args.projectPath, activeSpec.id, 3) : [];
    const data = {
        activeSpec: activeSpec !== null ? { id: activeSpec.id, title: activeSpec.title } : null,
        nextSpec: nextSpec !== null ? { id: nextSpec.id, title: nextSpec.title } : null,
        pendingCriteria,
        gitBranch: gitInfo.branch,
        gitStaged: gitInfo.staged,
        gitModified: gitInfo.modified,
        nextStep: sessionState?.nextSteps[0] ?? null,
    };
    const text = buildHandoffText(data);
    return { content: [{ type: 'text', text }] };
}
//# sourceMappingURL=session-handoff.js.map