// tools/code-impact-handler.ts — Handler for Code Change → Spec Impact Analyzer (SPEC-366)
import { listSpecs } from '../storage/spec-store.js';
import { hashProjectPath } from '../storage/base-store.js';
import { analyzeCodeImpact, checkCodeChangeCompliance, suggestSpecUpdates, runGitDiffImpact, } from '../engine/code-impact-analyzer.js';
import { execSync } from 'node:child_process';
function getCommitDiff(commitHash, projectPath) {
    try {
        return execSync(`git show ${commitHash}`, {
            cwd: projectPath,
            encoding: 'utf-8',
            stdio: ['pipe', 'pipe', 'pipe'],
        });
    }
    catch {
        return '';
    }
}
export async function handleAnalyzeCodeImpact(input) {
    const { projectPath, filePath, diffText } = input;
    try {
        const projectId = hashProjectPath(projectPath);
        const specs = await listSpecs(projectId);
        const result = analyzeCodeImpact(specs, filePath, diffText);
        if (result.affectedSpecs.length === 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `No specs found related to the provided ${filePath !== undefined ? `file "${filePath}"` : 'diff'}. ` +
                            `Checked ${String(result.totalSpecs)} specs in project.`,
                    },
                ],
            };
        }
        const lines = result.affectedSpecs.map((s) => `- ${s.specId} "${s.title}" (${s.relation}, status: ${s.status})`);
        return {
            content: [
                {
                    type: 'text',
                    text: `Found ${String(result.affectedSpecs.length)} related spec(s) ` +
                        `(from ${String(result.totalSpecs)} total):\n${lines.join('\n')}`,
                },
            ],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Failed to analyze code impact: ${message}` }],
            isError: true,
        };
    }
}
export async function handleCodeChangeCompliance(input) {
    const { projectPath, filePath, commitHash } = input;
    try {
        const projectId = hashProjectPath(projectPath);
        const specs = await listSpecs(projectId);
        const commitDiff = commitHash !== undefined ? getCommitDiff(commitHash, projectPath) : undefined;
        const result = checkCodeChangeCompliance(specs, filePath, commitDiff);
        const justifyingLines = result.justifyingSpecs.map((s) => `  - ${s.specId} "${s.title}" (${s.relation})`);
        const unjustifiedLines = result.unjustifiedChanges.map((u) => `  - ${u.filePath}: ${u.reason}`);
        const parts = [
            `Compliance score: ${String(result.complianceScore)}%`,
            `Summary: ${result.summary}`,
        ];
        if (justifyingLines.length > 0) {
            parts.push(`Justifying specs:\n${justifyingLines.join('\n')}`);
        }
        if (unjustifiedLines.length > 0) {
            parts.push(`Unjustified changes:\n${unjustifiedLines.join('\n')}`);
        }
        return {
            content: [{ type: 'text', text: parts.join('\n\n') }],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Failed to check code change compliance: ${message}` }],
            isError: true,
        };
    }
}
export async function handleSuggestSpecUpdate(input) {
    const { projectPath, filePath } = input;
    try {
        const projectId = hashProjectPath(projectPath);
        const specs = await listSpecs(projectId);
        const result = suggestSpecUpdates(specs, filePath);
        if (result.suggestions.length === 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `No spec update suggestions for "${filePath}".`,
                    },
                ],
            };
        }
        const lines = result.suggestions.map((s) => {
            const prefix = s.type === 'create' ? '[CREATE]' : `[UPDATE ${s.specId ?? ''}]`;
            const title = s.title !== undefined ? ` "${s.title}"` : '';
            return `- ${prefix}${title}: ${s.reason}`;
        });
        return {
            content: [
                {
                    type: 'text',
                    text: `Spec update suggestions for "${filePath}" (${String(result.suggestions.length)}):\n` +
                        lines.join('\n'),
                },
            ],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Failed to suggest spec updates: ${message}` }],
            isError: true,
        };
    }
}
export async function handleGitDiffToSpecImpact(input) {
    const { projectPath } = input;
    try {
        const projectId = hashProjectPath(projectPath);
        const specs = await listSpecs(projectId);
        const result = runGitDiffImpact(specs, projectPath);
        if (result.affectedSpecs.length === 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `No specs related to current git diff. Checked ${String(result.totalSpecs)} specs.`,
                    },
                ],
            };
        }
        const lines = result.affectedSpecs.map((s) => `- ${s.specId} "${s.title}" (${s.relation}, status: ${s.status})`);
        return {
            content: [
                {
                    type: 'text',
                    text: `Git diff impacts ${String(result.affectedSpecs.length)} spec(s):\n${lines.join('\n')}`,
                },
            ],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Failed to run git diff spec impact: ${message}` }],
            isError: true,
        };
    }
}
//# sourceMappingURL=code-impact-handler.js.map