import { ti } from '../i18n/index.js';
import { specStore } from '../storage/index.js';
import { readFile } from 'node:fs/promises';
/**
 * Extract a one-liner from the spec title and type.
 */
function generateOneLiner(spec) {
    const scopeLabel = spec.scope === 'trivial'
        ? 'small'
        : spec.scope === 'feature'
            ? 'standard'
            : spec.scope === 'cross-module'
                ? 'cross-module'
                : 'architectural';
    return `${spec.type} (${scopeLabel} scope, difficulty ${spec.difficulty}/5): ${spec.title}`;
}
/**
 * Extract key sections from markdown content.
 */
function extractMarkdownSections(content) {
    const sections = {};
    const lines = content.split('\n');
    let currentHeading = '';
    let currentContent = [];
    for (const line of lines) {
        const headingMatch = /^#{1,3}\s+(.+)/.exec(line);
        if (headingMatch) {
            if (currentHeading && currentContent.length > 0) {
                sections[currentHeading] = currentContent.join('\n').trim();
            }
            currentHeading = headingMatch.slice(1, 2).join('').toLowerCase();
            currentContent = [];
        }
        else {
            currentContent.push(line);
        }
    }
    if (currentHeading && currentContent.length > 0) {
        sections[currentHeading] = currentContent.join('\n').trim();
    }
    return sections;
}
/**
 * Build risk highlights from spec metadata.
 */
function buildRiskHighlights(spec) {
    const risks = [];
    if (spec.risk === 'high' || spec.risk === 'critical') {
        risks.push(`Risk level: ${spec.risk}`);
    }
    if (spec.difficulty >= 4) {
        risks.push(`High difficulty (${spec.difficulty}/5) — estimation uncertainty is higher`);
    }
    if (spec.scope === 'architectural') {
        risks.push('Architectural scope — may require migration or breaking changes');
    }
    if (spec.scope === 'cross-module') {
        risks.push('Cross-module scope — affects multiple parts of the system');
    }
    if (spec.blockedBy.length > 0) {
        risks.push(`Blocked by: ${spec.blockedBy.join(', ')}`);
    }
    if (spec.dependencies.length > 0) {
        risks.push(`Dependencies: ${spec.dependencies.join(', ')}`);
    }
    if (risks.length === 0) {
        risks.push('No significant risks identified');
    }
    return risks;
}
/**
 * Count lines in HU.md to detect trivial specs (< 30 lines).
 * Returns null if file cannot be read.
 */
async function countSpecLines(huPath) {
    try {
        const content = await readFile(huPath, 'utf-8');
        return content.split('\n').length;
    }
    catch {
        return null;
    }
}
export async function handleSummarizeSpec(params) {
    const { specId, projectId, format = 'technical', experienceLevel = 'expert' } = params;
    try {
        const spec = await specStore.getSpec(projectId, specId);
        if (!spec) {
            return {
                content: [{ type: 'text', text: ti('spec.notFound', { id: specId }) }],
                isError: true,
            };
        }
        const oneLiner = generateOneLiner(spec);
        // Detect trivial specs (< 30 lines in HU.md) — return oneliner directly
        const lineCount = await countSpecLines(spec.huPath);
        if (lineCount !== null && lineCount < 30) {
            const est = spec.estimation;
            const trivialResult = {
                format: 'oneliner',
                specId: spec.id,
                summary: oneLiner,
                status: spec.status,
                cost: `$${est.totalCostUsd}`,
                trivial: true,
                message: ti('tools.summarize_spec.success', { specId }),
            };
            return {
                content: [{ type: 'text', text: JSON.stringify(trivialResult, null, 2) }],
            };
        }
        // Try to read spec files for richer summary
        let huSections = {};
        let fichaSections = {};
        try {
            const huContent = await readFile(spec.huPath, 'utf-8');
            huSections = extractMarkdownSections(huContent);
        }
        catch {
            // HU file not available
        }
        try {
            const fichaContent = await readFile(spec.fichaTecnicaPath, 'utf-8');
            fichaSections = extractMarkdownSections(fichaContent);
        }
        catch {
            // Ficha file not available
        }
        // Extract key decisions from technical notes, ADR sections, and HU business rules
        const keyDecisions = [];
        for (const [heading, content] of Object.entries(fichaSections)) {
            if (heading.includes('decision') ||
                heading.includes('note') ||
                heading.includes('technical')) {
                const lines = content.split('\n').filter((l) => l.trim().length > 10);
                keyDecisions.push(...lines.slice(0, 3));
            }
        }
        for (const [heading, content] of Object.entries(huSections)) {
            if (heading.includes('reglas') || heading.includes('business') || heading.includes('rule')) {
                const lines = content.split('\n').filter((l) => l.trim().length > 10);
                keyDecisions.push(...lines.slice(0, 2));
            }
        }
        const riskHighlights = buildRiskHighlights(spec);
        const est = spec.estimation;
        const estimationSummary = `${est.devHours}h dev + ${est.reviewHours}h review = $${est.totalCostUsd} total (${est.recommendedModel} model, ${est.tokenOptimization.mode} mode)`;
        const affectedModules = spec.impactAnalysis?.affectedModules ?? [];
        const criticalDependencies = spec.blockedBy.length > 0 ? spec.blockedBy : spec.dependencies;
        const summary = {
            specId: spec.id,
            title: spec.title,
            oneLiner,
            keyDecisions: keyDecisions.length > 0 ? keyDecisions : ['No key decisions documented yet'],
            riskHighlights,
            estimationSummary,
            affectedModules,
            criticalDependencies,
            generatedAt: new Date().toISOString(),
        };
        // Persist summary for use by list_specs and other tools
        await specStore.saveSummary(projectId, specId, summary);
        let formattedOutput;
        if (format === 'oneliner') {
            formattedOutput = {
                specId: spec.id,
                summary: oneLiner,
                status: spec.status,
                cost: `$${est.totalCostUsd}`,
            };
        }
        else if (format === 'executive') {
            const baseExecutive = {
                specId: spec.id,
                title: spec.title,
                summary: oneLiner,
                status: spec.status,
                risk: spec.risk,
                cost: `$${est.totalCostUsd}`,
                timeline: `${est.devHours + est.reviewHours}h estimated`,
                keyRisks: riskHighlights,
                blockers: spec.blockedBy.length > 0 ? spec.blockedBy : ['None'],
                recommendation: spec.status === 'draft'
                    ? 'Ready for review'
                    : spec.status === 'approved'
                        ? 'Ready for implementation'
                        : `Currently ${spec.status}`,
            };
            if (experienceLevel === 'beginner') {
                formattedOutput = {
                    ...baseExecutive,
                    narrative: `Esta spec tiene un riesgo ${spec.risk} y estima ${est.devHours + est.reviewHours}h de trabajo. ${riskHighlights.slice(0, 1).join('')}`,
                };
            }
            else {
                formattedOutput = baseExecutive;
            }
        }
        else {
            // Technical (full)
            formattedOutput = {
                ...summary,
                spec: {
                    id: spec.id,
                    title: spec.title,
                    type: spec.type,
                    scope: spec.scope,
                    status: spec.status,
                    difficulty: spec.difficulty,
                    risk: spec.risk,
                    target: spec.target,
                    tags: spec.tags,
                    gitBranch: spec.gitBranch,
                },
                estimation: {
                    devHours: est.devHours,
                    reviewHours: est.reviewHours,
                    recommendedModel: est.recommendedModel,
                    executionMode: est.tokenOptimization.mode,
                    apiCostUsd: est.apiCostUsd,
                    humanCostUsd: est.humanCostUsd,
                    totalCostUsd: est.totalCostUsd,
                },
                files: {
                    hu: spec.huPath,
                    fichaTecnica: spec.fichaTecnicaPath,
                },
            };
        }
        const result = {
            format,
            ...formattedOutput,
            message: ti('tools.summarize_spec.success', { specId }),
        };
        return {
            content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('errors.internalError', { message }) }],
            isError: true,
        };
    }
}
//# sourceMappingURL=summarize-spec.js.map