// tools/estimate.ts — Estimate difficulty, hours, tokens, costs for a spec
// Uses the estimator engine with historical metrics for calibration.
import { specStore, metricsStore, globalStore, knowledgeStore } from '../storage/index.js';
import { estimateSpec } from '../engine/estimator.js';
import { classifyOperation, recommendModel } from '../engine/token-tracker.js';
import { ti } from '../i18n/index.js';
import { createBasicPhaseEvent, formatByLevel } from '../engine/phase-tracker.js';
export async function handleEstimate(args) {
    const { specId, projectId } = args;
    // 1. Load spec
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [{ type: 'text', text: ti('spec.notFound', { id: specId }) }],
            isError: true,
        };
    }
    // 2. Load global config for pricing/hourly rate
    const globalConfig = await globalStore.getGlobalConfig();
    // 3. Load project knowledge for potential overrides
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    const configOverrides = {
        ...globalConfig,
        ...(knowledge?.experienceLevel === 'beginner'
            ? { hourlyRate: globalConfig.hourlyRate * 0.7 }
            : {}),
        ...(knowledge?.experienceLevel === 'expert'
            ? { hourlyRate: globalConfig.hourlyRate * 1.3 }
            : {}),
    };
    // 4. Load historical metrics for calibration
    const metricsHistory = await metricsStore.getMetricsHistory(projectId);
    // 5. Run estimation engine
    const result = estimateSpec(spec, configOverrides, metricsHistory.entries);
    // 6. Update spec with estimation data
    await specStore.updateSpec(projectId, specId, {
        estimation: result.estimation,
        difficulty: result.difficulty,
    });
    // 7. Build output
    const est = result.estimation;
    // SPEC-012: Enrich output with token optimization and model recommendation
    const tokenMode = classifyOperation('estimate');
    const suggestedModel = recommendModel('estimate');
    const output = {
        specId,
        difficulty: result.difficulty,
        confidence: result.confidence,
        estimation: {
            devHours: est.devHours,
            reviewHours: est.reviewHours,
            totalHours: Math.round((est.devHours + est.reviewHours) * 10) / 10,
            recommendedModel: est.recommendedModel,
            tokensOpus: est.tokensOpus,
            tokensSonnet: est.tokensSonnet,
            apiCostUsd: est.apiCostUsd,
            humanCostUsd: est.humanCostUsd,
            totalCostUsd: est.totalCostUsd,
            tokenOptimization: est.tokenOptimization,
        },
        tokenStrategy: {
            operationMode: tokenMode,
            suggestedAiModel: suggestedModel,
            modelRationale: `Use ${suggestedModel} for estimation — moderate reasoning, spec analysis`,
        },
        reasoning: result.reasoning,
        similarSpecs: result.similarSpecs,
        historyUsed: metricsHistory.entries.length > 0,
    };
    const level = knowledge?.experienceLevel ?? 'intermediate';
    const summary = formatByLevel(`¡Listo! El spec ${specId} tiene una estimación de ${est.devHours}h de desarrollo. El costo total sería $${est.totalCostUsd} USD.`, ti('tools.estimate.success', {
        specId,
        devHours: String(est.devHours),
        totalCostUsd: String(est.totalCostUsd),
    }), `${specId}: ${est.devHours}h dev | $${est.totalCostUsd} USD | confidence: ${result.confidence}`, level);
    return {
        phaseEvent: createBasicPhaseEvent('estimate', 'completed', 100, 'analyzing'),
        content: [
            { type: 'text', text: summary },
            { type: 'text', text: JSON.stringify(output, null, 2) },
        ],
    };
}
//# sourceMappingURL=estimate.js.map