"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const ts_morph_1 = require("ts-morph");
async function update(tree) {
    devkit_1.logger.info('🔄 Starting fix playground apps migration...');
    let filesUpdated = 0;
    // Create a ts-morph project
    const project = new ts_morph_1.Project({
        useInMemoryFileSystem: true,
    });
    // Find and fix settings-buttons.tsx, configuration-provider.tsx, and playground-configuration-provider.tsx files
    (0, devkit_1.visitNotIgnoredFiles)(tree, '.', (filePath) => {
        if (filePath.endsWith('settings-buttons.tsx') ||
            filePath.endsWith('configuration-provider.tsx') ||
            filePath.endsWith('playground-configuration-provider.tsx')) {
            const content = tree.read(filePath, 'utf-8');
            if (content) {
                let hasChanges = false;
                // Check if the file contains patterns we need to fix
                const buttonsContainerPattern = /export const ButtonsContainer: React\.FC<{\s*children\?\: React\.ReactChild;\s*}>/;
                const configProviderPattern = /const getPlaygroundConfigurationFromLocalStorage = \(\s*configurationKey: string\s*\)(?!\s*:)/;
                const configProviderWithTypePattern = /const getPlaygroundConfigurationFromLocalStorage = \(\s*configurationKey: string\s*\):\s*PlaygroundConfiguration(?!\s*\|)/;
                if (buttonsContainerPattern.test(content) || configProviderPattern.test(content) || configProviderWithTypePattern.test(content)) {
                    // Create a source file from the content
                    const sourceFile = project.createSourceFile(filePath, content, { overwrite: true });
                    // Replace patterns using regex
                    let updatedContent = content;
                    // Fix ButtonsContainer type definition
                    if (buttonsContainerPattern.test(content)) {
                        updatedContent = updatedContent.replace(/export const ButtonsContainer: React\.FC<{\s*children\?\: React\.ReactChild;\s*}>/, 'export const ButtonsContainer: React.FC<PropsWithChildren>');
                    }
                    // Fix getPlaygroundConfigurationFromLocalStorage return type (no return type)
                    if (configProviderPattern.test(content)) {
                        updatedContent = updatedContent.replace(/const getPlaygroundConfigurationFromLocalStorage = \(\s*configurationKey: string\s*\)(?!\s*:)/, 'const getPlaygroundConfigurationFromLocalStorage = (\n  configurationKey: string\n): PlaygroundConfiguration | null');
                    }
                    // Fix getPlaygroundConfigurationFromLocalStorage return type (PlaygroundConfiguration -> PlaygroundConfiguration | null)
                    if (configProviderWithTypePattern.test(content)) {
                        updatedContent = updatedContent.replace(/const getPlaygroundConfigurationFromLocalStorage = \(\s*configurationKey: string\s*\):\s*PlaygroundConfiguration(?!\s*\|)/, 'const getPlaygroundConfigurationFromLocalStorage = (\n  configurationKey: string\n): PlaygroundConfiguration | null');
                    }
                    // Update the source file with the new content
                    sourceFile.replaceWithText(updatedContent);
                    // Handle imports with ts-morph (only for settings-buttons.tsx)
                    if (filePath.endsWith('settings-buttons.tsx') && buttonsContainerPattern.test(content)) {
                        const reactImport = sourceFile.getImportDeclaration('react');
                        if (reactImport) {
                            // Check if PropsWithChildren is already imported
                            const namedImports = reactImport.getNamedImports();
                            const hasPropsWithChildren = namedImports.some(imp => imp.getName() === 'PropsWithChildren');
                            if (!hasPropsWithChildren) {
                                // Add PropsWithChildren to the existing React import
                                reactImport.addNamedImport('PropsWithChildren');
                                hasChanges = true;
                            }
                        }
                        else {
                            // If no React import exists, create one
                            sourceFile.addImportDeclaration({
                                defaultImport: 'React',
                                namedImports: ['PropsWithChildren'],
                                moduleSpecifier: 'react'
                            });
                            hasChanges = true;
                        }
                    }
                    // Check if any changes were made
                    if (updatedContent !== content || hasChanges) {
                        // Write the updated content back to the tree
                        const finalContent = sourceFile.getFullText();
                        tree.write(filePath, finalContent);
                        filesUpdated++;
                        devkit_1.logger.info(`✅ Updated ${filePath}`);
                    }
                }
            }
        }
    });
    if (filesUpdated > 0) {
        await (0, devkit_1.formatFiles)(tree);
        devkit_1.logger.info(`✅ Fix playground apps migration completed. Updated ${filesUpdated} files.`);
    }
    else {
        devkit_1.logger.info('ℹ️ No playground files found to migrate.');
    }
}
