// tools/snapshot-spec-hashes.ts — Create/update hash snapshots for a spec
// Tracks file hashes and function signatures of files referenced in technical.md
import { readFile } from 'node:fs/promises';
import { specStore, knowledgeStore, hashSnapshotStore } from '../storage/index.js';
import { createFileHashEntries, extractFilePlanPaths, extractSignaturesFromFiles, diffFileHashes, diffSignatures, } from '../engine/living-spec/index.js';
import { stripFrontmatter } from '../engine/frontmatter-parser.js';
export async function handleSnapshotSpecHashes(args) {
    const { projectId, specId } = args;
    // 1. Load spec
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [{ type: 'text', text: `Spec ${specId} not found` }],
            isError: true,
        };
    }
    // 2. Load project path
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    if (!knowledge?.projectPath) {
        return {
            content: [{ type: 'text', text: 'Project not found. Run init_project first.' }],
            isError: true,
        };
    }
    const projectPath = knowledge.projectPath;
    // 3. Extract file paths from technical.md File Plan section
    let filePaths;
    try {
        const rawContent = await readFile(spec.technicalPath, 'utf-8');
        const content = stripFrontmatter(rawContent);
        filePaths = extractFilePlanPaths(content);
    }
    catch {
        return {
            content: [
                {
                    type: 'text',
                    text: `Could not read technical.md for ${specId}. Ensure it exists at ${spec.technicalPath}`,
                },
            ],
            isError: true,
        };
    }
    if (filePaths.length === 0) {
        return {
            content: [
                {
                    type: 'text',
                    text: `No file paths found in technical.md File Plan section for ${specId}. Add files in a markdown table or list.`,
                },
            ],
        };
    }
    // 4. Create hash entries and extract signatures
    const files = await createFileHashEntries(projectPath, filePaths);
    const signatures = await extractSignaturesFromFiles(projectPath, filePaths);
    // 5. Load previous snapshot for comparison
    const previousSnapshot = await hashSnapshotStore.getSnapshot(projectId, specId);
    // 6. Save new snapshot
    const newSnapshot = {
        specId,
        createdAt: new Date().toISOString(),
        files,
        signatures,
    };
    await hashSnapshotStore.saveSnapshot(projectId, specId, newSnapshot);
    // 7. Generate diff report if previous snapshot exists
    let diffReport = null;
    if (previousSnapshot) {
        const fileDiffs = await diffFileHashes(projectPath, previousSnapshot, filePaths);
        const sigChanges = diffSignatures(previousSnapshot.signatures, signatures);
        diffReport = {
            changedFiles: fileDiffs.length,
            signatureChanges: sigChanges.length,
            details: {
                files: fileDiffs,
                signatures: sigChanges,
            },
        };
    }
    return {
        content: [
            {
                type: 'text',
                text: JSON.stringify({
                    specId,
                    filesTracked: files.length,
                    signaturesTracked: signatures.length,
                    totalPathsInPlan: filePaths.length,
                    missingFiles: filePaths.length - files.length,
                    ...(diffReport ? { diff: diffReport } : {}),
                    message: previousSnapshot
                        ? `Hash snapshot updated for ${specId}. ${String(diffReport?.changedFiles ?? 0)} file(s) changed.`
                        : `Initial hash snapshot created for ${specId}.`,
                }, null, 2),
            },
        ],
    };
}
//# sourceMappingURL=snapshot-spec-hashes.js.map