"use strict";
/**
 * Migration: Migrate Kava analytics types to Application Events bucket types
 *
 * Renames enums/types and adds the required `bucket: AnalyticsBucket.ApplicationEvents`
 * field to all report() calls.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const ts_morph_1 = require("ts-morph");
const RENAMES = {
    KavaEventTypes: 'ApplicationEventTypes',
    KavaButtonsTypes: 'ApplicationButtonTypes',
    KavaPageTypes: 'ApplicationPageTypes',
    KavaBaseTypePayload: 'ApplicationEventsBasePayload',
    KavaButtonTypePayload: 'ApplicationButtonPayload',
    KavaPageTypePayload: 'ApplicationPagePayload',
    KavaRequestPayloadByType: 'AnalyticsPayloadByBucket',
};
async function update(tree) {
    devkit_1.logger.info('🔄 Migrating Kava analytics types to Application Events bucket types...');
    const scanDirs = ['unisphere/runtimes', 'unisphere/packages'];
    const existingDirs = scanDirs.filter((dir) => tree.exists(dir));
    if (existingDirs.length === 0) {
        devkit_1.logger.info('ℹ️ No runtimes or packages directory found');
        return;
    }
    const project = new ts_morph_1.Project({
        manipulationSettings: { quoteKind: ts_morph_1.QuoteKind.Single },
    });
    let updatedCount = 0;
    const processFile = (filePath) => {
        if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx'))
            return;
        const content = tree.read(filePath, 'utf-8');
        if (!content)
            return;
        const hasOldTypes = Object.keys(RENAMES).some((old) => content.includes(old));
        if (!hasOldTypes)
            return;
        const sourceFile = project.createSourceFile(filePath, content, {
            overwrite: true,
        });
        let hasChanges = false;
        // Step 1: Add `bucket: AnalyticsBucket.ApplicationEvents` to any object literal
        // containing an `eventType: KavaEventTypes.*` property (covers direct .report() calls
        // and indirect patterns like wrapper functions).
        const objectLiterals = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
        for (const objLiteral of objectLiterals) {
            if (objLiteral.getProperty('bucket'))
                continue;
            const eventTypeProp = objLiteral.getProperty('eventType');
            if (!eventTypeProp)
                continue;
            const eventTypeText = eventTypeProp.getText();
            if (!eventTypeText.includes('KavaEventTypes.') &&
                !eventTypeText.includes('ApplicationEventTypes.'))
                continue;
            objLiteral.insertPropertyAssignment(0, {
                name: 'bucket',
                initializer: 'AnalyticsBucket.ApplicationEvents',
            });
            hasChanges = true;
        }
        // Step 2: Rename all old type/enum references
        let updatedText = sourceFile.getFullText();
        for (const [oldName, newName] of Object.entries(RENAMES)) {
            const regex = new RegExp(`\\b${oldName}\\b`, 'g');
            if (regex.test(updatedText)) {
                updatedText = updatedText.replace(regex, newName);
                hasChanges = true;
            }
        }
        // Step 3: Add AnalyticsBucket to imports from @unisphere/runtime
        if (hasChanges) {
            if (updatedText.includes('AnalyticsBucket') &&
                !updatedText.match(/import\s*\{[^}]*AnalyticsBucket[^}]*\}\s*from\s*['"]@unisphere\/runtime['"]/)) {
                updatedText = updatedText.replace(/(import\s*\{)([^}]*)(}\s*from\s*['"]@unisphere\/runtime['"])/, (_match, start, imports, end) => {
                    const importList = imports
                        .split(',')
                        .map((s) => s.trim())
                        .filter(Boolean);
                    if (!importList.includes('AnalyticsBucket')) {
                        importList.push('AnalyticsBucket');
                        importList.sort();
                    }
                    return `${start}\n  ${importList.join(',\n  ')},\n${end}`;
                });
            }
            tree.write(filePath, updatedText);
            updatedCount++;
            devkit_1.logger.info(`  ✅ Updated ${filePath}`);
        }
    };
    for (const dir of existingDirs) {
        (0, devkit_1.visitNotIgnoredFiles)(tree, dir, processFile);
    }
    if (updatedCount === 0) {
        devkit_1.logger.info('ℹ️ No files needed analytics type migration');
    }
    else {
        await (0, devkit_1.formatFiles)(tree);
        devkit_1.logger.info(`✅ Migrated analytics types in ${updatedCount} file(s)`);
    }
}
