"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEPENDENCY_MAP = void 0;
exports.validateGitToken = validateGitToken;
exports.validateReactNaming = validateReactNaming;
exports.installSelectedDependencies = installSelectedDependencies;
const devkit_1 = require("@nx/devkit");
const child_process_1 = require("child_process");
const utils_1 = require("./utils");
/**
 * Dependency version mappings with default versions from workspace
 */
exports.DEPENDENCY_MAP = {
    react: {
        packages: ['react', 'react-dom'],
        defaultVersions: {
            'react': '^19.0.0',
            'react-dom': '^19.0.0',
        },
    },
    ds: {
        packages: [
            '@kaltura/ds-react-bits',
            '@kaltura/ds-react-icons',
            '@kaltura/ds-react-theme',
            '@kaltura/ds-react-utils',
            '@mui/material',
            '@mui/icons-material',
            '@emotion/react',
            '@emotion/styled',
        ],
        defaultVersions: {
            '@kaltura/ds-react-bits': '^12.2.0',
            '@kaltura/ds-react-icons': '^12.2.0',
            '@kaltura/ds-react-theme': '^12.2.0',
            '@kaltura/ds-react-utils': '^12.2.0',
            '@mui/material': '^7.3.4',
            '@mui/icons-material': '^7.3.4',
            '@emotion/react': '11.14.0',
            '@emotion/styled': '11.14.1',
        },
    },
    mui: {
        packages: ['@mui/material', '@mui/icons-material', '@emotion/react', '@emotion/styled'],
        defaultVersions: {
            '@mui/material': '^7.3.4',
            '@mui/icons-material': '^7.3.4',
            '@emotion/react': '11.14.0',
            '@emotion/styled': '11.14.1',
        },
    },
    'react-hook-form': {
        packages: ['react-hook-form', 'react', 'react-dom'],
        defaultVersions: {
            'react-hook-form': '^7.52.0',
            'react': '^19.0.0',
            'react-dom': '^19.0.0',
        },
    },
};
// TODO: change it to validate as --jfrogToken??
/**
 * Validates that GIT_TOKEN environment variable exists when Kaltura DS is selected
 * @throws Error if GIT_TOKEN is not found
 */
function validateGitToken(selectedDependencies) {
    if (selectedDependencies.includes('ds')) {
        const gitToken = process.env.GIT_TOKEN;
        if (!gitToken) {
            devkit_1.logger.error('');
            devkit_1.logger.error('❌ Error: Kaltura DS requires GIT_TOKEN environment variable');
            devkit_1.logger.error('');
            devkit_1.logger.error('Please set up your GitHub token to access Kaltura packages.');
            devkit_1.logger.error('Documentation: https://unisphere.kaltura.com/docs/create/overview');
            devkit_1.logger.error('');
            throw new Error('GIT_TOKEN environment variable is required for Kaltura DS');
        }
    }
}
/**
 * Validates and auto-corrects package/runtime name to include -react suffix
 * when React or Kaltura DS dependencies are selected
 */
function validateReactNaming(name, selectedDependencies) {
    const needsReactSuffix = selectedDependencies.includes('react') ||
        selectedDependencies.includes('ds');
    if (needsReactSuffix && !name.endsWith('-react')) {
        const suggestedName = `${name}-react`;
        devkit_1.logger.warn('');
        devkit_1.logger.warn(`⚠️  Package/Runtime name should end with '-react' when using React or Kaltura DS`);
        devkit_1.logger.info(`   Renaming to: ${suggestedName}`);
        devkit_1.logger.warn('');
        return suggestedName;
    }
    return name;
}
/**
 * Installs selected dependencies, skipping those already installed
 */
function installSelectedDependencies(tree, selectedDependencies) {
    if (!selectedDependencies || selectedDependencies.length === 0) {
        return;
    }
    // Track processed packages to avoid duplicates (e.g., 'ds' and 'mui' both include @mui/material)
    const processedPackages = new Set();
    let hasPackagesToInstall = false;
    // First pass: check if there's anything to install
    for (const dep of selectedDependencies) {
        const depConfig = exports.DEPENDENCY_MAP[dep];
        if (!depConfig)
            continue;
        for (const packageName of depConfig.packages) {
            if (processedPackages.has(packageName))
                continue;
            processedPackages.add(packageName);
            if (!(0, utils_1.isPackageInstalled)(tree, packageName)) {
                hasPackagesToInstall = true;
                break;
            }
        }
        if (hasPackagesToInstall)
            break;
    }
    // If nothing to install, return silently
    if (!hasPackagesToInstall) {
        return;
    }
    // Reset for second pass
    processedPackages.clear();
    devkit_1.logger.info('');
    devkit_1.logger.info('📦 Installing selected dependencies...');
    for (const dep of selectedDependencies) {
        const depConfig = exports.DEPENDENCY_MAP[dep];
        if (!depConfig) {
            devkit_1.logger.warn(`⚠️  Unknown dependency: ${dep}`);
            continue;
        }
        for (const packageName of depConfig.packages) {
            // Skip if already processed (avoid duplicates)
            if (processedPackages.has(packageName)) {
                continue;
            }
            processedPackages.add(packageName);
            const installedVersion = (0, utils_1.isPackageInstalled)(tree, packageName);
            if (installedVersion) {
                // Already installed, skip silently
                continue;
            }
            const version = depConfig.defaultVersions?.[packageName] || '^1.0.0';
            const installCommand = `npm install ${packageName}@${version}`;
            devkit_1.logger.info(`   Installing ${packageName}@${version}...`);
            try {
                (0, child_process_1.execSync)(installCommand, {
                    cwd: process.cwd(),
                    stdio: 'inherit',
                });
                devkit_1.logger.info(`✅ ${packageName}@${version} installed successfully`);
            }
            catch (error) {
                devkit_1.logger.error(`❌ Failed to install ${packageName}: ${error}`);
            }
        }
    }
    devkit_1.logger.info('');
}
