// engine/migration/stack-analyzer.ts — Analyze source stack for migration (SPEC-028a)
// Handles: analyze, implicit contract detection, component dependency graph
// --- Internal helpers ---
const HOT_COMPLEXITY_THRESHOLD = 15;
const WARM_COMPLEXITY_THRESHOLD = 7;
function classifyTemperature(complexity, coupling) {
    if (complexity >= HOT_COMPLEXITY_THRESHOLD || coupling >= 8) {
        return 'hot';
    }
    if (complexity >= WARM_COMPLEXITY_THRESHOLD || coupling >= 4) {
        return 'warm';
    }
    return 'cold';
}
function detectImplicitContracts(components) {
    return components.flatMap((c) => {
        const contracts = [];
        if (c.type === 'handler') {
            contracts.push({
                component: c.name,
                type: 'error-format',
                description: 'HTTP error response format must match origin exactly',
                mustPreserve: true,
            });
            contracts.push({
                component: c.name,
                type: 'http-header',
                description: 'Response headers (Content-Type, CORS, etc.) must be preserved',
                mustPreserve: true,
            });
        }
        if (c.temperature === 'hot') {
            contracts.push({
                component: c.name,
                type: 'side-effect',
                description: `High-complexity component — document all side effects before migrating`,
                mustPreserve: true,
            });
        }
        return contracts;
    });
}
function detectArchitecturalPatterns(components) {
    const patterns = [];
    const names = components.map((c) => c.name.toLowerCase());
    const hasDomainLayer = names.some((n) => n.includes('domain') || n.includes('entity')) &&
        names.some((n) => n.includes('repo') || n.includes('store'));
    if (hasDomainLayer) {
        patterns.push({
            name: 'Domain-Driven Design',
            confidence: 0.7,
            indicators: ['domain/ layer', 'repository pattern'],
        });
    }
    const hasControllerService = names.some((n) => n.includes('controller') || n.includes('handler')) &&
        names.some((n) => n.includes('service'));
    if (hasControllerService) {
        patterns.push({
            name: 'MVC / Controller-Service',
            confidence: 0.8,
            indicators: ['controller layer', 'service layer'],
        });
    }
    if (patterns.length === 0) {
        patterns.push({
            name: 'Unknown / Flat',
            confidence: 0.5,
            indicators: ['no clear layering detected'],
        });
    }
    return patterns;
}
// --- Public API ---
export function buildStackAnalysis(params) {
    const { language, framework, components, entryPoints, externalIntegrations, migratableComponents, hasTests, testCoverage, } = params;
    const architecturalPatterns = detectArchitecturalPatterns(migratableComponents);
    const implicitContracts = detectImplicitContracts(migratableComponents);
    const riskFlags = [];
    if (!hasTests) {
        riskFlags.push('CRITICAL: No tests detected — write behavioral tests before migrating to reduce regression risk');
    }
    const hotComponents = migratableComponents.filter((c) => c.temperature === 'hot');
    if (hotComponents.length > 0) {
        riskFlags.push(`${hotComponents.length} hot component(s) detected: ${hotComponents.map((c) => c.name).join(', ')} — prioritize deep analysis`);
    }
    const circularRisk = migratableComponents.some((c) => c.dependsOn.some((dep) => migratableComponents.find((m) => m.id === dep)?.dependsOn.includes(c.id)));
    if (circularRisk) {
        riskFlags.push('Potential circular dependencies detected — run plan action to resolve');
    }
    return {
        language,
        framework,
        components,
        architecturalPatterns,
        entryPoints,
        externalIntegrations,
        migratableComponents,
        implicitContracts,
        hasTests,
        testCoverage,
        riskFlags,
        analyzedAt: new Date().toISOString(),
    };
}
export function scoreMigratableComponents(components) {
    return components.map((c) => ({
        ...c,
        temperature: classifyTemperature(c.cyclomaticComplexity, c.couplingScore),
    }));
}
//# sourceMappingURL=stack-analyzer.js.map