"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
async function update(tree) {
    devkit_1.logger.info('🔄 Removing React overrides from package.json...');
    const packageJsonPath = 'package.json';
    if (!tree.exists(packageJsonPath)) {
        devkit_1.logger.warn('⚠️ package.json not found');
        throw new Error('package.json not found');
    }
    try {
        (0, devkit_1.updateJson)(tree, packageJsonPath, (packageJson) => {
            let overridesRemoved = 0;
            if (packageJson.overrides) {
                // Find overrides that contain React-related dependencies
                const overridesToRemove = Object.keys(packageJson.overrides).filter(key => {
                    const override = packageJson.overrides[key];
                    // Check if the override contains React-related dependencies
                    if (typeof override === 'object' && override !== null) {
                        return Object.entries(override).some(([dep, version]) => (dep === 'react' ||
                            dep.startsWith('react-') ||
                            dep.startsWith('@types/react')) && (typeof version === 'string' && (version.startsWith('18') || version.startsWith('^18'))));
                    }
                    // Check if the key itself is React-related
                    return key === 'react' ||
                        key.startsWith('react-') ||
                        key.startsWith('@types/react');
                });
                // Remove the identified overrides
                overridesToRemove.forEach(key => {
                    delete packageJson.overrides[key];
                    overridesRemoved++;
                });
                // If overrides object is now empty, remove it entirely
                if (Object.keys(packageJson.overrides).length === 0) {
                    delete packageJson.overrides;
                    devkit_1.logger.info('📦 Removed empty overrides object');
                }
                if (overridesRemoved > 0) {
                    devkit_1.logger.info(`📦 Removed ${overridesRemoved} React-related overrides from package.json`);
                }
                else {
                    devkit_1.logger.info('ℹ️ No React-related overrides found to remove');
                }
            }
            else {
                devkit_1.logger.info('ℹ️ No overrides section found in package.json');
            }
            return packageJson;
        });
        devkit_1.logger.info('✅ Successfully processed React overrides removal');
    }
    catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        devkit_1.logger.error(`❌ Could not update package.json: ${errorMessage}`);
        throw new Error(`Could not update package.json: ${errorMessage}`);
    }
}
