"use strict";
/**
 * Migration: Replace setup-local-runtimes.ts content
 *
 * Finds setup-local-runtimes.ts in each application and replaces its content
 * with the updated version that supports experience-scoped runtimes.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const path_1 = require("path");
const NEW_CONTENT = `export function setupLocalRuntimes() {
  if (!process.env.LOCAL_RUNTIMES) return;

  const runtimes: Record<string, Record<string, { token: string; baseEnvName: string }>> = {};
  process.env.LOCAL_RUNTIMES.split(',').forEach((entry) => {
    const [experience, name, port] = entry.split('@');
    if (experience && name && port) {
      if (!runtimes[experience]) {
        runtimes[experience] = {};
      }
      runtimes[experience][name] = { token: port, baseEnvName: '' };
    }
  });

  const overrides = {
    baseEnvName: '',
    mode: 'integration',
    options: { verbose: 'inherit' },
    baseEnvScope: { core: 'inherit', presets: 'inherit' },
    runtimes,
  };

  (window as any).unisphereRuntimeOverrides = btoa(JSON.stringify(overrides));
}
`;
async function update(tree) {
    devkit_1.logger.info('🔄 Replacing setup-local-runtimes.ts content in applications...');
    if (!tree.exists('.unisphere')) {
        devkit_1.logger.warn('⚠️ No .unisphere file found, skipping');
        return;
    }
    const unisphereConfig = (0, devkit_1.readJson)(tree, '.unisphere');
    const applications = unisphereConfig.elements?.applications;
    if (!applications || Object.keys(applications).length === 0) {
        devkit_1.logger.info('ℹ️ No applications found, skipping');
        return;
    }
    let updatedCount = 0;
    for (const [appName, appConfig] of Object.entries(applications)) {
        const setupFilePath = (0, path_1.join)(appConfig.sourceRoot, 'src', 'setup-local-runtimes.ts');
        if (!tree.exists(setupFilePath)) {
            devkit_1.logger.info(`ℹ️ ${appName}: setup-local-runtimes.ts not found, skipping`);
            continue;
        }
        tree.write(setupFilePath, NEW_CONTENT);
        updatedCount++;
        devkit_1.logger.info(`✅ ${appName}: Replaced setup-local-runtimes.ts content`);
    }
    await (0, devkit_1.formatFiles)(tree);
    devkit_1.logger.info(`\n✅ Done: ${updatedCount} setup-local-runtimes.ts file(s) updated`);
}
