"use strict";
/**
 * Migration: Comment out the "Security Audit" step in cicd.yml
 *
 * The `Security Audit` step (`npx unisphere tools audit`) is temporarily
 * disabled across projects. This migration comments out the step's lines in
 * .github/workflows/cicd.yml by prefixing each with `#`:
 *
 *   #      - name: Security Audit
 *   #        run: npx unisphere tools audit
 *   #        env:
 *   #          KALTURA_JFROG_TOKEN: ${{ steps.setup-jfrog.outputs.oidc-token }}
 *
 * The step's block is matched by its `- name: Security Audit` anchor and the
 * following contiguous body lines (stopping at the first blank line or the next
 * `- name:` step), so it is resilient to indentation differences between repos.
 *
 * Idempotent: if the step is already commented out (or absent), re-running
 * makes no further changes.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const CICD_PATH = '.github/workflows/cicd.yml';
const STEP_ANCHOR = '- name: Security Audit';
async function update(tree) {
    devkit_1.logger.info(`🔄 Commenting out the Security Audit step in ${CICD_PATH}...`);
    if (!tree.exists(CICD_PATH)) {
        devkit_1.logger.info(`ℹ️ No ${CICD_PATH} found, skipping migration`);
        return;
    }
    const content = tree.read(CICD_PATH, 'utf-8') ?? '';
    const lines = content.split('\n');
    // Match the anchor whether or not it is already commented out, so re-running
    // recognises the existing state instead of treating it as "not found".
    const stripComment = (line) => line.replace(/^\s*#/, '').trim();
    const anchorIndex = lines.findIndex((line) => stripComment(line) === STEP_ANCHOR);
    if (anchorIndex === -1) {
        devkit_1.logger.info(`ℹ️ Security Audit step not found in ${CICD_PATH}, skipping migration`);
        return;
    }
    // Already commented? (anchor line begins with #) — don't add a second #.
    if (lines[anchorIndex].trimStart().startsWith('#')) {
        devkit_1.logger.info('✅ Security Audit step already commented out, skipping');
        return;
    }
    // Comment the step's contiguous block: the anchor line plus the following
    // body lines, stopping at the first blank line or the next `- name:` step.
    let commented = 0;
    for (let i = anchorIndex; i < lines.length; i++) {
        const line = lines[i];
        if (i > anchorIndex &&
            (line.trim() === '' || stripComment(line).startsWith('- name:'))) {
            break;
        }
        // Per-line guard: never prefix a line that is already commented.
        if (!line.trimStart().startsWith('#')) {
            lines[i] = `#${line}`;
            commented++;
        }
    }
    tree.write(CICD_PATH, lines.join('\n'));
    devkit_1.logger.info(`✅ Commented out ${commented} lines of the Security Audit step`);
}
