"use strict";
/**
 * Migration: Add Unisphere Languages Support
 *
 * Migrates packages from raw i18next/react-i18next to the Unisphere
 * @unisphere/ui-i18n-react framework with createUseTranslation pattern.
 * Adds UnisphereI18NRuntimeProxy to all runtimes.
 *
 * Steps:
 * 1. For packages with existing en-US.json: move translations, create
 *    use-translation.tsx, update imports, remove LanguagesProvider
 * 2. For all runtimes: add UnisphereI18NRuntimeProxy, remove LanguagesProvider usage
 * 3. Update root package.json dependencies
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const path = tslib_1.__importStar(require("path"));
async function update(tree) {
    devkit_1.logger.info('🔄 Adding Unisphere languages support...');
    if (!tree.exists('.unisphere')) {
        devkit_1.logger.info('ℹ️ No .unisphere config found, skipping');
        return;
    }
    const config = (0, devkit_1.readJson)(tree, '.unisphere');
    const packages = config.elements?.packages || {};
    const runtimes = config.elements?.runtimes || {};
    // Step 1: Migrate packages with existing translations
    const migratedPackages = migratePackages(tree, packages);
    // Step 2: Migrate all runtimes
    migrateRuntimes(tree, runtimes, migratedPackages);
    // Step 3: Update root package.json
    updateRootPackageJson(tree);
    await (0, devkit_1.formatFiles)(tree);
    devkit_1.logger.info('✅ Unisphere languages support migration complete');
}
// =============================================================================
// Step 1: Package Migrations
// =============================================================================
function migratePackages(tree, packages) {
    const migratedPackages = [];
    for (const [name, config] of Object.entries(packages)) {
        const { sourceRoot } = config;
        if (!tree.exists(sourceRoot)) {
            devkit_1.logger.warn(`  ⚠️ Package "${name}" source root not found: ${sourceRoot}`);
            continue;
        }
        // Find existing en-US.json under this package
        const translationFile = findTranslationFile(tree, sourceRoot);
        // Read package name from package.json
        const packageJsonPath = `${sourceRoot}/package.json`;
        let packageName = `@local/${name}`;
        if (tree.exists(packageJsonPath)) {
            const pkgJson = (0, devkit_1.readJson)(tree, packageJsonPath);
            packageName = pkgJson.name || packageName;
        }
        devkit_1.logger.info(`  📦 Migrating package "${name}" (${packageName})...`);
        // 1a. Move translation file to src/languages/en-US.json or create empty one
        const targetTranslationPath = `${sourceRoot}/src/languages/en-US.json`;
        if (translationFile) {
            moveTranslationFile(tree, translationFile, targetTranslationPath);
        }
        else {
            // Create empty en-US.json if none existed
            if (!tree.exists(targetTranslationPath)) {
                tree.write(targetTranslationPath, '{}');
                devkit_1.logger.info(`    ✅ Created empty ${targetTranslationPath}`);
            }
        }
        // 1b. Create _db/.gitignore
        const dbGitignorePath = `${sourceRoot}/src/languages/_db/.gitignore`;
        if (!tree.exists(dbGitignorePath)) {
            tree.write(dbGitignorePath, '');
        }
        // 1c. Create files/.gitkeep
        const filesGitkeepPath = `${sourceRoot}/src/languages/files/.gitkeep`;
        if (!tree.exists(filesGitkeepPath)) {
            tree.write(filesGitkeepPath, '');
        }
        // 1d. Create supported-languges.ts
        const supportedLanguagesPath = `${sourceRoot}/src/languages/supported-languges.ts`;
        createSupportedLanguagesFile(tree, supportedLanguagesPath);
        // 1e. Create use-translation.tsx (if not already present)
        const useTranslationPath = `${sourceRoot}/src/lib/use-translation.tsx`;
        createUseTranslationFile(tree, useTranslationPath, packageName);
        // 1f. Create README.md in languages folder
        const readmePath = `${sourceRoot}/src/languages/README.md`;
        createLanguagesReadme(tree, readmePath);
        // 1g. Update useTranslation imports in package files
        updateUseTranslationImports(tree, sourceRoot, useTranslationPath);
        // 1h. Remove LanguagesProvider usage from package files
        removeLanguagesProviderUsage(tree, sourceRoot);
        // 1i. Delete languages-provider.tsx
        deleteLanguagesProvider(tree, sourceRoot);
        // 1j. Update barrel export
        updateBarrelExport(tree, sourceRoot);
        // 1k. Export useTranslation from barrel for runtime consumption
        exportUseTranslationFromBarrel(tree, sourceRoot);
        migratedPackages.push({
            name,
            sourceRoot,
            packageName,
            translationFilePath: targetTranslationPath,
        });
    }
    if (migratedPackages.length === 0) {
        devkit_1.logger.info('ℹ️ No packages with translations found');
    }
    else {
        devkit_1.logger.info(`  ✅ Migrated ${migratedPackages.length} package(s) with translations`);
    }
    return migratedPackages;
}
function findTranslationFile(tree, sourceRoot) {
    let found = null;
    (0, devkit_1.visitNotIgnoredFiles)(tree, sourceRoot, (filePath) => {
        if (found)
            return;
        if (filePath.endsWith('/en-US.json') && filePath.includes('/languages/')) {
            found = filePath;
        }
    });
    // Fallback: look for en-US.json anywhere under src
    if (!found) {
        (0, devkit_1.visitNotIgnoredFiles)(tree, sourceRoot, (filePath) => {
            if (found)
                return;
            if (filePath.endsWith('/en-US.json')) {
                found = filePath;
            }
        });
    }
    return found;
}
function moveTranslationFile(tree, from, to) {
    if (from === to)
        return;
    if (tree.exists(to)) {
        devkit_1.logger.info(`    ℹ️ Translation file already at target: ${to}`);
        return;
    }
    const content = tree.read(from, 'utf-8');
    if (content) {
        tree.write(to, content);
        tree.delete(from);
        devkit_1.logger.info(`    📁 Moved ${from} → ${to}`);
    }
}
function createSupportedLanguagesFile(tree, filePath) {
    if (tree.exists(filePath)) {
        devkit_1.logger.info(`    ℹ️ supported-languges.ts already exists`);
        return;
    }
    const content = `export const supportedLanguages: string[] = ['en-US'];\n`;
    tree.write(filePath, content);
    devkit_1.logger.info(`    ✅ Created ${filePath}`);
}
function createUseTranslationFile(tree, filePath, packageName) {
    if (tree.exists(filePath)) {
        devkit_1.logger.info(`    ℹ️ use-translation.tsx already exists`);
        return;
    }
    const content = `import en from '../languages/en-US.json';
import { createUseTranslation } from '@unisphere/ui-i18n-react';
import { supportedLanguages } from '../languages/supported-languges';

export const useTranslation = createUseTranslation({
  packageName: '${packageName}',
  defaultTranslations: en as any,
  supportedLanguages,
});
`;
    tree.write(filePath, content);
    devkit_1.logger.info(`    ✅ Created ${filePath}`);
}
function createLanguagesReadme(tree, filePath) {
    if (tree.exists(filePath)) {
        return;
    }
    const content = `# Languages

This folder contains the internationalization (i18n) setup for this package.

## Structure

\`\`\`
languages/
├── en-US.json              # Default English translations (source of truth)
├── supported-languges.ts   # List of supported language codes
├── files/                  # Translated language files (e.g., de-DE.json, fr-FR.json)
│   └── .gitkeep
├── _db/                    # Translation database for change tracking (git-ignored)
│   └── .gitignore
└── README.md               # This file
\`\`\`

## How It Works

- **\`en-US.json\`** — The master translation file. All keys are defined here in English.
- **\`supported-languges.ts\`** — Exports the list of supported language codes. Add new languages here when translations are available.
- **\`files/\`** — Contains translated JSON files for each supported language (excluding en-US). These are generated via the Unisphere CLI export/import workflow.
- **\`_db/\`** — Used internally by the CLI to track translation changes between exports. Do not commit.

## Adding Translations

1. Add your translation keys to \`en-US.json\`
2. Run \`npx unisphere languages export\` to generate CSV files for translators
3. After receiving translations, run \`npx unisphere languages import\` to update the \`files/\` directory
4. Add the new language code to \`supported-languges.ts\`

## Usage

Components in this package use translations via the \`useTranslation\` hook:

\`\`\`typescript
import { useTranslation } from './use-translation';

const MyComponent = () => {
  const { t } = useTranslation();
  return <span>{t('myKey')}</span>;
};
\`\`\`

## CLI Commands

\`\`\`bash
npx unisphere languages export    # Export translations to CSV for translation services
npx unisphere languages import    # Import translated CSV files back to JSON
npx unisphere languages serve     # Serve language files during local development
npx unisphere languages bundle    # Bundle language files for distribution
\`\`\`
`;
    tree.write(filePath, content);
    devkit_1.logger.info(`    ✅ Created ${filePath}`);
}
function updateUseTranslationImports(tree, sourceRoot, useTranslationPath) {
    let updatedCount = 0;
    (0, devkit_1.visitNotIgnoredFiles)(tree, sourceRoot, (filePath) => {
        if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx'))
            return;
        const content = tree.read(filePath, 'utf-8');
        if (!content)
            return;
        // Match: import { useTranslation } from 'react-i18next';
        const reactI18nextImport = /import\s*\{\s*useTranslation\s*\}\s*from\s*['"]react-i18next['"];?\s*\n?/;
        if (!reactI18nextImport.test(content))
            return;
        // Skip the languages-provider.tsx file itself (will be deleted)
        if (filePath.includes('languages-provider'))
            return;
        // Calculate relative path from this file to use-translation.tsx
        const fileDir = path.dirname(filePath);
        let relativePath = path.relative(fileDir, useTranslationPath);
        // Remove .tsx extension for import
        relativePath = relativePath.replace(/\.tsx$/, '');
        // Ensure it starts with ./
        if (!relativePath.startsWith('.')) {
            relativePath = './' + relativePath;
        }
        const updatedContent = content.replace(reactI18nextImport, `import { useTranslation } from '${relativePath}';\n`);
        if (updatedContent !== content) {
            tree.write(filePath, updatedContent);
            updatedCount++;
        }
    });
    if (updatedCount > 0) {
        devkit_1.logger.info(`    ✅ Updated useTranslation imports in ${updatedCount} file(s)`);
    }
}
function removeLanguagesProviderUsage(tree, sourceRoot) {
    let updatedCount = 0;
    (0, devkit_1.visitNotIgnoredFiles)(tree, sourceRoot, (filePath) => {
        if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx'))
            return;
        if (filePath.includes('languages-provider'))
            return;
        const content = tree.read(filePath, 'utf-8');
        if (!content)
            return;
        if (!content.includes('LanguagesProvider'))
            return;
        let updatedContent = content;
        // Remove LanguagesProvider import (handles various import patterns)
        // Pattern 1: Standalone import
        updatedContent = updatedContent.replace(/import\s*\{\s*LanguagesProvider\s*\}\s*from\s*['"][^'"]+['"];?\s*\n?/g, '');
        // Pattern 2: Part of a multi-import (e.g., import { X, LanguagesProvider, Y } from ...)
        updatedContent = updatedContent.replace(/,\s*LanguagesProvider\s*/g, '');
        updatedContent = updatedContent.replace(/LanguagesProvider\s*,\s*/g, '');
        // Remove <LanguagesProvider> wrapping (keep children)
        // Handle: <LanguagesProvider>\n...children...\n</LanguagesProvider>
        updatedContent = updatedContent.replace(/\s*<LanguagesProvider>\s*\n?/g, '');
        updatedContent = updatedContent.replace(/\s*<\/LanguagesProvider>\s*\n?/g, '');
        if (updatedContent !== content) {
            tree.write(filePath, updatedContent);
            updatedCount++;
        }
    });
    if (updatedCount > 0) {
        devkit_1.logger.info(`    ✅ Removed LanguagesProvider from ${updatedCount} file(s)`);
    }
}
function deleteLanguagesProvider(tree, sourceRoot) {
    const possiblePaths = [
        `${sourceRoot}/src/lib/providers/languages-provider.tsx`,
        `${sourceRoot}/src/lib/providers/languages-provider.ts`,
    ];
    for (const filePath of possiblePaths) {
        if (tree.exists(filePath)) {
            tree.delete(filePath);
            devkit_1.logger.info(`    🗑️ Deleted ${filePath}`);
        }
    }
}
function updateBarrelExport(tree, sourceRoot) {
    const indexPath = `${sourceRoot}/src/index.ts`;
    if (!tree.exists(indexPath))
        return;
    const content = tree.read(indexPath, 'utf-8');
    if (!content)
        return;
    // Remove export of languages-provider
    const updatedContent = content.replace(/export\s*\*\s*from\s*['"]\.\/lib\/providers\/languages-provider['"];?\s*\n?/g, '');
    if (updatedContent !== content) {
        tree.write(indexPath, updatedContent);
        devkit_1.logger.info(`    ✅ Removed LanguagesProvider from barrel export`);
    }
}
function exportUseTranslationFromBarrel(tree, sourceRoot) {
    const indexPath = `${sourceRoot}/src/index.ts`;
    if (!tree.exists(indexPath))
        return;
    const content = tree.read(indexPath, 'utf-8');
    if (!content)
        return;
    // Check if already exported
    if (content.includes('use-translation'))
        return;
    const exportLine = `export { useTranslation } from './lib/use-translation';\n`;
    const updatedContent = content + exportLine;
    tree.write(indexPath, updatedContent);
    devkit_1.logger.info(`    ✅ Added useTranslation to barrel export`);
}
// =============================================================================
// Step 2: Runtime Migrations
// =============================================================================
function migrateRuntimes(tree, runtimes, migratedPackages) {
    let updatedCount = 0;
    for (const [name, config] of Object.entries(runtimes)) {
        const { sourceRoot } = config;
        if (!tree.exists(sourceRoot)) {
            devkit_1.logger.warn(`  ⚠️ Runtime "${name}" source root not found: ${sourceRoot}`);
            continue;
        }
        const runtimeFilePath = `${sourceRoot}/src/lib/runtime.tsx`;
        if (!tree.exists(runtimeFilePath)) {
            // Try alternative patterns
            const altPath = `${sourceRoot}/src/lib/runtime.ts`;
            if (!tree.exists(altPath)) {
                devkit_1.logger.warn(`  ⚠️ Runtime "${name}" has no runtime.tsx at ${runtimeFilePath}`);
                continue;
            }
        }
        devkit_1.logger.info(`  ⚡ Migrating runtime "${name}"...`);
        // 2a. Create src/languages folder structure for runtime
        createRuntimeLanguagesFolder(tree, sourceRoot);
        // 2b. Create use-translation.tsx for runtime (uses 'self' as packageName)
        const runtimeUseTranslationPath = `${sourceRoot}/src/lib/use-translation.tsx`;
        createUseTranslationFile(tree, runtimeUseTranslationPath, 'self');
        // 2c. Add UnisphereI18NRuntimeProxy to runtime.tsx
        addRuntimeProxy(tree, runtimeFilePath);
        // 2d. Remove LanguagesProvider from runtime
        removeLanguagesProviderFromRuntime(tree, runtimeFilePath);
        // 2e. Update useTranslation imports in runtime files
        updateRuntimeUseTranslationImports(tree, sourceRoot, migratedPackages);
        updatedCount++;
    }
    if (updatedCount > 0) {
        devkit_1.logger.info(`  ✅ Migrated ${updatedCount} runtime(s)`);
    }
}
function createRuntimeLanguagesFolder(tree, sourceRoot) {
    const langDir = `${sourceRoot}/src/languages`;
    // en-US.json
    if (!tree.exists(`${langDir}/en-US.json`)) {
        tree.write(`${langDir}/en-US.json`, '{}');
    }
    // supported-languges.ts
    if (!tree.exists(`${langDir}/supported-languges.ts`)) {
        tree.write(`${langDir}/supported-languges.ts`, `export const supportedLanguages: string[] = ['en-US'];\n`);
    }
    // files/.gitkeep
    if (!tree.exists(`${langDir}/files/.gitkeep`)) {
        tree.write(`${langDir}/files/.gitkeep`, '');
    }
    // _db/.gitignore
    if (!tree.exists(`${langDir}/_db/.gitignore`)) {
        tree.write(`${langDir}/_db/.gitignore`, '');
    }
    // README.md
    if (!tree.exists(`${langDir}/README.md`)) {
        createLanguagesReadme(tree, `${langDir}/README.md`);
    }
}
function addRuntimeProxy(tree, runtimeFilePath) {
    if (!tree.exists(runtimeFilePath))
        return;
    let content = tree.read(runtimeFilePath, 'utf-8');
    if (!content)
        return;
    // Check if already has the proxy
    if (content.includes('UnisphereI18NRuntimeProxy')) {
        devkit_1.logger.info(`    ℹ️ UnisphereI18NRuntimeProxy already present`);
        return;
    }
    // Add import for UnisphereI18NRuntimeProxy
    content = addI18nProxyImport(content);
    // Add the proxy component inside each render method's ScopedUnisphereWorkspaceProvider
    content = insertProxyIntoRenderMethods(content);
    tree.write(runtimeFilePath, content);
    devkit_1.logger.info(`    ✅ Added UnisphereI18NRuntimeProxy to runtime`);
}
function addI18nProxyImport(content) {
    // Check if @unisphere/ui-i18n-react is already imported
    if (content.includes('@unisphere/ui-i18n-react')) {
        // Add UnisphereI18NRuntimeProxy to existing import
        return content.replace(/(import\s*\{[^}]*)(}\s*from\s*['"]@unisphere\/ui-i18n-react['"])/, (_, start, end) => {
            if (start.includes('UnisphereI18NRuntimeProxy'))
                return start + end;
            return `${start.trimEnd()}, UnisphereI18NRuntimeProxy ${end}`;
        });
    }
    // Add new import after existing @unisphere imports or at the top
    const unisphereImportPattern = /import\s*\{[^}]*\}\s*from\s*['"]@unisphere\/[^'"]+['"];?\s*\n/g;
    let lastMatch = null;
    let match;
    while ((match = unisphereImportPattern.exec(content)) !== null) {
        lastMatch = match;
    }
    const importStatement = `import { UnisphereI18NRuntimeProxy } from '@unisphere/ui-i18n-react';\n`;
    if (lastMatch) {
        const insertPos = lastMatch.index + lastMatch[0].length;
        return (content.slice(0, insertPos) + importStatement + content.slice(insertPos));
    }
    // Fallback: add after all imports
    const lastImportMatch = content.match(/^import\s.+from\s+['"][^'"]+['"];?\s*$/gm);
    if (lastImportMatch) {
        const lastImport = lastImportMatch[lastImportMatch.length - 1];
        const lastImportEnd = content.lastIndexOf(lastImport) + lastImport.length;
        return (content.slice(0, lastImportEnd) +
            '\n' +
            importStatement +
            content.slice(lastImportEnd));
    }
    return importStatement + content;
}
function insertProxyIntoRenderMethods(content) {
    // Strategy: Find each render method's JSX tree and insert the proxy
    // after the first <ScopedUnisphereWorkspaceProvider ...> opening tag.
    // This works whether ScopedProvider wraps ThemeProvider or is inside it.
    //
    // Pattern we're looking for:
    //   <ScopedUnisphereWorkspaceProvider
    //     runtimeLogger={...}
    //     unisphereWorkspace={...}
    //   >
    //     <-- INSERT PROXY HERE
    //
    // We find each occurrence of this multi-line opening tag and insert after it.
    const lines = content.split('\n');
    const result = [];
    let i = 0;
    while (i < lines.length) {
        result.push(lines[i]);
        // Detect start of ScopedUnisphereWorkspaceProvider opening tag
        if (lines[i].includes('<ScopedUnisphereWorkspaceProvider')) {
            // Find the closing > of this opening tag (may be on same line or subsequent lines)
            let closingLine = i;
            // Check if tag closes on same line (self-closing or inline)
            if (lines[i].includes('>') && !lines[i].includes('</')) {
                closingLine = i;
            }
            else {
                // Look forward for the closing >
                for (let j = i + 1; j < lines.length && j < i + 10; j++) {
                    result.push(lines[j]);
                    closingLine = j;
                    if (lines[j].trim() === '>' || lines[j].trimEnd().endsWith('>')) {
                        break;
                    }
                }
                i = closingLine;
            }
            // Determine indentation for the proxy (one level deeper than the closing >)
            const closingIndent = lines[closingLine].match(/^(\s*)/)?.[1] || '';
            const proxyIndent = closingIndent + '  ';
            // Insert the proxy component
            result.push(`${proxyIndent}<UnisphereI18NRuntimeProxy`);
            result.push(`${proxyIndent}  runtimeUri={this._options.runtimeDeployedPath}`);
            result.push(`${proxyIndent}/>`);
        }
        i++;
    }
    return result.join('\n');
}
function removeLanguagesProviderFromRuntime(tree, runtimeFilePath) {
    if (!tree.exists(runtimeFilePath))
        return;
    const content = tree.read(runtimeFilePath, 'utf-8');
    if (!content)
        return;
    if (!content.includes('LanguagesProvider'))
        return;
    let updatedContent = content;
    // Remove LanguagesProvider from import statement
    // Pattern: import { X, LanguagesProvider, Y } from '...'
    // Or standalone: import { LanguagesProvider } from '...'
    // Check if it's the only named import
    const standaloneImport = /import\s*\{\s*LanguagesProvider\s*\}\s*from\s*['"][^'"]+['"];?\s*\n?/g;
    if (standaloneImport.test(updatedContent)) {
        updatedContent = updatedContent.replace(standaloneImport, '');
    }
    else {
        // Part of multi-import: remove with surrounding comma
        updatedContent = updatedContent.replace(/,\s*\n?\s*LanguagesProvider/g, '');
        updatedContent = updatedContent.replace(/LanguagesProvider\s*,\s*\n?\s*/g, '');
    }
    // Remove <LanguagesProvider> and </LanguagesProvider> JSX wrapping
    updatedContent = updatedContent.replace(/(\s*)<LanguagesProvider>\s*\n?/g, '');
    updatedContent = updatedContent.replace(/(\s*)<\/LanguagesProvider>\s*\n?/g, '');
    if (updatedContent !== content) {
        tree.write(runtimeFilePath, updatedContent);
        devkit_1.logger.info(`    ✅ Removed LanguagesProvider from runtime`);
    }
}
function updateRuntimeUseTranslationImports(tree, runtimeSourceRoot, migratedPackages) {
    if (migratedPackages.length === 0)
        return;
    // Determine which package this runtime uses by checking the main runtime.tsx file
    // for imports from any of our migrated packages
    let targetPackage = null;
    const runtimeFilePath = `${runtimeSourceRoot}/src/lib/runtime.tsx`;
    if (tree.exists(runtimeFilePath)) {
        const runtimeContent = tree.read(runtimeFilePath, 'utf-8') || '';
        for (const pkg of migratedPackages) {
            if (runtimeContent.includes(pkg.packageName)) {
                targetPackage = pkg;
                break;
            }
        }
    }
    // If runtime doesn't import from any migrated package, check all source files
    if (!targetPackage) {
        (0, devkit_1.visitNotIgnoredFiles)(tree, runtimeSourceRoot, (filePath) => {
            if (targetPackage)
                return;
            if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx'))
                return;
            const content = tree.read(filePath, 'utf-8');
            if (!content)
                return;
            for (const pkg of migratedPackages) {
                if (content.includes(pkg.packageName)) {
                    targetPackage = pkg;
                    break;
                }
            }
        });
    }
    // Last resort: use first migrated package
    if (!targetPackage) {
        targetPackage = migratedPackages[0];
    }
    let updatedCount = 0;
    (0, devkit_1.visitNotIgnoredFiles)(tree, runtimeSourceRoot, (filePath) => {
        if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx'))
            return;
        const content = tree.read(filePath, 'utf-8');
        if (!content)
            return;
        const reactI18nextImport = /import\s*\{\s*useTranslation\s*\}\s*from\s*['"]react-i18next['"];?\s*\n?/;
        if (!reactI18nextImport.test(content))
            return;
        const updatedContent = content.replace(reactI18nextImport, `import { useTranslation } from '${targetPackage.packageName}';\n`);
        if (updatedContent !== content) {
            tree.write(filePath, updatedContent);
            updatedCount++;
        }
    });
    if (updatedCount > 0) {
        devkit_1.logger.info(`    ✅ Updated useTranslation imports in ${updatedCount} runtime file(s)`);
    }
}
// =============================================================================
// Step 3: Root package.json updates
// =============================================================================
function updateRootPackageJson(tree) {
    if (!tree.exists('package.json'))
        return;
    const packageJson = (0, devkit_1.readJson)(tree, 'package.json');
    const deps = packageJson.dependencies || {};
    const devDeps = packageJson.devDependencies || {};
    let changed = false;
    // Remove i18next and react-i18next
    if (deps['i18next']) {
        delete deps['i18next'];
        changed = true;
        devkit_1.logger.info('  🗑️ Removed i18next from dependencies');
    }
    if (deps['react-i18next']) {
        delete deps['react-i18next'];
        changed = true;
        devkit_1.logger.info('  🗑️ Removed react-i18next from dependencies');
    }
    if (devDeps['i18next']) {
        delete devDeps['i18next'];
        changed = true;
    }
    if (devDeps['react-i18next']) {
        delete devDeps['react-i18next'];
        changed = true;
    }
    if (changed) {
        packageJson.dependencies = deps;
        packageJson.devDependencies = devDeps;
        (0, devkit_1.writeJson)(tree, 'package.json', packageJson);
        devkit_1.logger.info('  ✅ Updated root package.json dependencies');
    }
}
