// tools/suggest-tooling/build-tool-catalog.ts — SPEC-050 S2
// Build tool recommendations for suggest_tooling based on detected build tool.
// C4: new JS/TS project → recommend Vite 7
// C5: Vite 5/6 detected → recommend migration to Vite 7
// C6: Webpack 4 or CRA detected → recommend webpack-to-vite migration
import { readFile } from 'node:fs/promises';
import { getNpmVersion } from '../../config/version-defaults.js';
// ---------------------------------------------------------------------------
// Cache
// ---------------------------------------------------------------------------
let catalogCache = null;
/** Reset in-memory cache (for testing). */
export function resetBuildToolCatalogCache() {
    catalogCache = null;
}
const FALLBACK_CATALOG = {
    recommendations: {
        'new-project': {
            tool: 'vite',
            version: `>=${getNpmVersion('vite')}`,
            justification: 'Vite 7 — fastest HMR and zero-config TypeScript support.',
            alternatives: [],
        },
    },
    migrations: {
        'webpack-to-vite': {
            description: 'Migrate Webpack to Vite',
            phases: [],
            configEquivalences: {},
            postMigrationChecklist: [],
        },
        'vite6-to-vite7': {
            description: 'Migrate Vite 6 to Vite 7',
            breakingChanges: [],
            viteConfigDiff: { before: '', after: '' },
            rollbackStrategy: '',
            incompatiblePlugins: [],
        },
    },
};
function isValidBuildToolsCatalog(obj) {
    if (typeof obj !== 'object' || obj === null) {
        return false;
    }
    const candidate = obj;
    if (typeof candidate.recommendations !== 'object' || candidate.recommendations === null) {
        return false;
    }
    const recs = candidate.recommendations;
    return typeof recs['new-project'] === 'object' && recs['new-project'] !== null;
}
async function loadBuildToolsCatalog() {
    if (catalogCache) {
        return catalogCache;
    }
    try {
        const configPath = new URL('../../config/build-tools-catalog.json', import.meta.url);
        const content = await readFile(configPath, 'utf-8');
        const parsed = JSON.parse(content);
        if (!isValidBuildToolsCatalog(parsed)) {
            return FALLBACK_CATALOG;
        }
        catalogCache = parsed;
        return catalogCache;
    }
    catch {
        return FALLBACK_CATALOG;
    }
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function isJsTsProject(knowledge) {
    const lang = knowledge.language.toLowerCase();
    return lang === 'typescript' || lang === 'javascript';
}
function parseVersionMajor(version) {
    if (!version) {
        return null;
    }
    const cleaned = version.replace(/^[^0-9]*/, '');
    const match = /^(\d+)/.exec(cleaned);
    return match !== null ? parseInt(match[1] ?? '0', 10) : null;
}
function isCraDetected(knowledge) {
    const stack = knowledge.stack.map((s) => s.toLowerCase());
    const conventions = JSON.stringify(knowledge.conventions).toLowerCase();
    return (stack.some((s) => s.includes('create-react-app') || s.includes('react-scripts')) ||
        conventions.includes('create-react-app') ||
        conventions.includes('react-scripts'));
}
// ---------------------------------------------------------------------------
// C4: New JS/TS project — recommend Vite 7
// ---------------------------------------------------------------------------
function buildC4Lines(rec) {
    const lines = [
        '',
        '## Build Tool Recommendation',
        '',
        `**Recommended:** ${rec.tool} ${rec.version}`,
        '',
        rec.justification,
        '',
    ];
    if (rec.alternatives.length > 0) {
        lines.push('**Alternatives:**', '');
        for (const alt of rec.alternatives) {
            lines.push(`- **${alt.tool}**: ${alt.when}`);
        }
        lines.push('');
    }
    return lines;
}
// ---------------------------------------------------------------------------
// C5: Vite 5/6 — recommend migration to Vite 7
// ---------------------------------------------------------------------------
function buildC5Lines(versionKey, rec) {
    return [
        '',
        '## Build Tool Migration Recommended',
        '',
        `**Priority:** ${rec.priority.toUpperCase()}`,
        '',
        rec.message,
        '',
        `Run: \`migrate_tech --action vite${versionKey === 'vite6' ? '6' : '5'}-to-vite7\` for step-by-step migration plan.`,
        '',
    ];
}
// ---------------------------------------------------------------------------
// C6: Webpack 4 / CRA — recommend webpack-to-vite migration
// ---------------------------------------------------------------------------
function buildC6Lines(migration) {
    const lines = ['', '## Migrate to Vite — Checklist', '', migration.description, ''];
    for (const phase of migration.phases) {
        lines.push(`### Phase ${phase.phase}: ${phase.title}`, '');
        for (const step of phase.steps) {
            lines.push(`- ${step}`);
        }
        lines.push('');
    }
    if (migration.postMigrationChecklist.length > 0) {
        lines.push('**Post-Migration Checklist:**', '');
        for (const item of migration.postMigrationChecklist) {
            lines.push(`- [ ] ${item}`);
        }
        lines.push('');
    }
    lines.push('Run: `migrate_tech --action webpack-to-vite` for a detailed structured migration plan.', '');
    return lines;
}
// ---------------------------------------------------------------------------
// Main export
// ---------------------------------------------------------------------------
/**
 * Build build-tool-specific recommendation lines for suggest_tooling.
 * - C4: no build tool on JS/TS → recommend Vite 7
 * - C5: Vite 5 or 6 detected → recommend migration to Vite 7
 * - C6: Webpack 4 or CRA detected → recommend webpack-to-vite checklist
 */
export async function buildBuildToolSuggestionLines(knowledge) {
    if (!isJsTsProject(knowledge)) {
        return [];
    }
    const catalog = await loadBuildToolsCatalog();
    const buildTool = knowledge.buildTool;
    // C4: No build tool detected (or unknown) — recommend Vite 7
    if (!buildTool || buildTool.buildTool === 'unknown') {
        return buildC4Lines(catalog.recommendations['new-project']);
    }
    // C5: Vite 5 or 6 — recommend migration to Vite 7
    if (buildTool.buildTool === 'vite') {
        const major = parseVersionMajor(buildTool.version);
        if (major !== null && major <= 6) {
            const versionKey = major <= 5 ? 'vite5' : 'vite6';
            const rec = catalog.recommendations[versionKey];
            if (rec !== undefined) {
                const migrateRec = rec;
                return buildC5Lines(versionKey, migrateRec);
            }
        }
    }
    // C6: Webpack 4 or CRA detected
    if (buildTool.buildTool === 'webpack') {
        const major = parseVersionMajor(buildTool.version);
        const isWebpack4 = major !== null && major < 5;
        if (isWebpack4 || isCraDetected(knowledge)) {
            return buildC6Lines(catalog.migrations['webpack-to-vite']);
        }
    }
    // CRA detection independent of webpack version
    if (isCraDetected(knowledge)) {
        return buildC6Lines(catalog.migrations['webpack-to-vite']);
    }
    return [];
}
//# sourceMappingURL=build-tool-catalog.js.map