"use strict";
/**
 * Migration: Add getWorkspace() call before getService in runtime files
 *
 * Transforms this._options.getService to this._options.getWorkspace().getService
 * in runtime project files.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
async function update(tree) {
    devkit_1.logger.info('🔄 Adding getWorkspace() before getService calls in runtime projects...');
    const runtimesDir = 'unisphere/runtimes';
    if (!tree.exists(runtimesDir)) {
        devkit_1.logger.info('ℹ️ No runtimes directory found');
        return;
    }
    let updatedCount = 0;
    (0, devkit_1.visitNotIgnoredFiles)(tree, runtimesDir, (filePath) => {
        if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx'))
            return;
        const content = tree.read(filePath, 'utf-8');
        if (!content)
            return;
        if (!content.includes('_options') || !content.includes('getService'))
            return;
        // Match this._options followed by optional whitespace/newline/dot then .getService
        // Handles: this._options.getService / this._options.\n      .getService / this._options\n      .getService
        const pattern = /this\._options\.?\s*\.getService/g;
        if (!pattern.test(content))
            return;
        // Already migrated check: if getWorkspace().getService exists, skip
        if (content.includes('.getWorkspace().getService') || content.includes('.getWorkspace()\n')) {
            // More precise check: see if all occurrences are already migrated
            const unmigrated = content.replace(/this\._options\.getWorkspace\(\)\s*\.getService/g, '');
            if (!/this\._options\.?\s*\.getService/.test(unmigrated)) {
                return;
            }
        }
        const updatedContent = content.replace(/this\._options\.?\s*\.\s*getService/g, 'this._options.getWorkspace().getService');
        if (updatedContent !== content) {
            tree.write(filePath, updatedContent);
            updatedCount++;
            devkit_1.logger.info(`  ✅ Updated ${filePath}`);
        }
    });
    if (updatedCount === 0) {
        devkit_1.logger.info('ℹ️ No runtime files needed getWorkspace() insertion before getService');
    }
    else {
        await (0, devkit_1.formatFiles)(tree);
        devkit_1.logger.info(`✅ Updated ${updatedCount} runtime file(s)`);
    }
}
