/**
 * Phase 5 — Stage 4: Deployment Finalization
 *
 * Generates production-ready deployment scripts:
 * - deploy.sh (gcloud CLI commands)
 * - teardown.sh (cleanup script)
 * - env.template (Secret Manager references)
 * - vpc-setup.sh (VPC connector for ERP network)
 * - monitoring.yaml (Cloud Monitoring alert policies)
 *
 * References infra repo patterns for IAM/networking.
 * References integrations repo for webhook/event patterns.
 */
import { writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { createSpan, endSpan, emitSpan } from '../../phase2/telemetry.js';
// ============================================================================
// Constants
// ============================================================================
const DIR_MODE = 0o700;
const FILE_MODE = 0o600;
const EXEC_MODE = 0o700;
const SCRIPT_HEADER = [
    '#!/usr/bin/env bash',
    '# Generated by Phase 5 pipeline — do not edit manually',
    '#',
    '# This script is deterministic and idempotent.',
    '# Re-running it will update the deployment in place.',
    '',
    'set -euo pipefail',
    '',
].join('\n');
/**
 * Derive deployment variables from Phase 5 context.
 * Uses registration data from the service-registration stage if available,
 * otherwise falls back to sensible defaults.
 */
function deriveDeploymentVars(context) {
    const registrationStage = context.stageOutputs.get('service-registration');
    let serviceName = 'erp-service';
    let serviceAccount = 'erp-service-sa@PROJECT_ID.iam.gserviceaccount.com';
    let vpcConnector = 'sap-connector';
    if (registrationStage?.status === 'completed' && registrationStage.data) {
        const data = registrationStage.data;
        const registration = data['registration'];
        if (registration) {
            serviceName = registration['service_name'] ?? serviceName;
            const vpcConfig = registration['vpc_config'];
            if (vpcConfig) {
                vpcConnector = vpcConfig['connector_name'] ?? vpcConnector;
            }
            const iamConfig = registration['iam_config'];
            if (iamConfig) {
                serviceAccount = iamConfig['service_account'] ?? serviceAccount;
            }
        }
    }
    return {
        serviceName,
        region: 'us-central1',
        serviceAccount,
        vpcConnector,
    };
}
// ============================================================================
// Script Generators
// ============================================================================
/**
 * Generate deploy.sh: the primary deployment script for Cloud Run.
 *
 * Builds the container image, pushes it to GCR, and deploys to Cloud Run
 * with all production settings: VPC connector, Secret Manager references,
 * least-privilege service account, and internal-only ingress.
 */
function generateDeployScript(vars, erpSystem) {
    return [
        SCRIPT_HEADER,
        '# ============================================================================',
        `# Deploy ${vars.serviceName} to Cloud Run`,
        '# ============================================================================',
        '',
        '# Configuration (override via environment variables)',
        'GCP_PROJECT_ID=${GCP_PROJECT_ID:?ERROR: GCP_PROJECT_ID must be set}',
        `GCP_REGION="\${GCP_REGION:-${vars.region}}"`,
        `SERVICE_NAME="\${SERVICE_NAME:-${vars.serviceName}}"`,
        'IMAGE_TAG="${IMAGE_TAG:-latest}"',
        'IMAGE_URL="gcr.io/${GCP_PROJECT_ID}/${SERVICE_NAME}:${IMAGE_TAG}"',
        `SERVICE_ACCOUNT="\${SERVICE_ACCOUNT:-${vars.serviceAccount}}"`,
        `VPC_CONNECTOR="\${VPC_CONNECTOR:-${vars.vpcConnector}}"`,
        '',
        'echo "=================================================================="',
        'echo "Deploying ${SERVICE_NAME} to Cloud Run"',
        'echo "  Project:         ${GCP_PROJECT_ID}"',
        'echo "  Region:          ${GCP_REGION}"',
        'echo "  Image:           ${IMAGE_URL}"',
        'echo "  Service Account: ${SERVICE_ACCOUNT}"',
        'echo "  VPC Connector:   ${VPC_CONNECTOR}"',
        'echo "=================================================================="',
        '',
        '# Step 1: Authenticate with GCP (if not already authenticated)',
        'echo "[1/5] Checking GCP authentication..."',
        'gcloud auth print-identity-token > /dev/null 2>&1 || {',
        '  echo "Not authenticated. Run: gcloud auth login"',
        '  exit 1',
        '}',
        '',
        '# Step 2: Set the active project',
        'echo "[2/5] Setting project to ${GCP_PROJECT_ID}..."',
        'gcloud config set project "${GCP_PROJECT_ID}"',
        '',
        '# Step 3: Build the container image',
        'echo "[3/5] Building container image..."',
        'gcloud builds submit \\',
        '  --tag "${IMAGE_URL}" \\',
        '  --timeout=600s \\',
        '  .',
        '',
        '# Step 4: Deploy to Cloud Run',
        'echo "[4/5] Deploying to Cloud Run..."',
        'gcloud run deploy "${SERVICE_NAME}" \\',
        '  --image "${IMAGE_URL}" \\',
        '  --region "${GCP_REGION}" \\',
        '  --platform managed \\',
        '  --no-allow-unauthenticated \\',
        '  --vpc-connector "${VPC_CONNECTOR}" \\',
        '  --vpc-egress all-traffic \\',
        '  --service-account "${SERVICE_ACCOUNT}" \\',
        '  --set-secrets "SAP_API_KEY=sap-api-key:latest,SAP_CLIENT_CERT=sap-client-cert:latest,SAP_OAUTH_SECRET=sap-oauth-secret:latest" \\',
        `  --set-env-vars "NODE_ENV=production,PORT=8080,ERP_SYSTEM=${erpSystem},LOG_LEVEL=info" \\`,
        '  --min-instances 0 \\',
        '  --max-instances 10 \\',
        '  --memory 512Mi \\',
        '  --cpu 1 \\',
        '  --timeout 300 \\',
        '  --concurrency 80 \\',
        '  --ingress internal-and-cloud-load-balancing \\',
        '  --cpu-throttling \\',
        '  --quiet',
        '',
        '# Step 5: Verify deployment',
        'echo "[5/5] Verifying deployment..."',
        'SERVICE_URL=$(gcloud run services describe "${SERVICE_NAME}" \\',
        '  --region "${GCP_REGION}" \\',
        '  --format "value(status.url)")',
        '',
        'echo ""',
        'echo "=================================================================="',
        'echo "Deployment complete!"',
        'echo "  Service URL: ${SERVICE_URL}"',
        'echo "  Health:      ${SERVICE_URL}/api/v1/health"',
        'echo "=================================================================="',
        '',
    ].join('\n');
}
/**
 * Generate teardown.sh: cleanup script that removes all deployed resources.
 *
 * Deletes the Cloud Run service, container images, IAM bindings, and
 * optionally the service account.
 */
function generateTeardownScript(vars) {
    return [
        SCRIPT_HEADER,
        '# ============================================================================',
        `# Teardown ${vars.serviceName} — remove all deployed resources`,
        '# ============================================================================',
        '',
        'GCP_PROJECT_ID=${GCP_PROJECT_ID:?ERROR: GCP_PROJECT_ID must be set}',
        `GCP_REGION="\${GCP_REGION:-${vars.region}}"`,
        `SERVICE_NAME="\${SERVICE_NAME:-${vars.serviceName}}"`,
        `SERVICE_ACCOUNT="\${SERVICE_ACCOUNT:-${vars.serviceAccount}}"`,
        '',
        'echo "=================================================================="',
        'echo "WARNING: Tearing down ${SERVICE_NAME}"',
        'echo "  This will DELETE the Cloud Run service and associated resources."',
        'echo "=================================================================="',
        'echo ""',
        'read -rp "Are you sure? (y/N): " CONFIRM',
        'if [[ "${CONFIRM}" != "y" && "${CONFIRM}" != "Y" ]]; then',
        '  echo "Teardown cancelled."',
        '  exit 0',
        'fi',
        '',
        '# Step 1: Delete Cloud Run service',
        'echo "[1/4] Deleting Cloud Run service..."',
        'gcloud run services delete "${SERVICE_NAME}" \\',
        '  --region "${GCP_REGION}" \\',
        '  --quiet 2>/dev/null || echo "  Service not found — skipping."',
        '',
        '# Step 2: Delete container images from GCR',
        'echo "[2/4] Cleaning up container images..."',
        'gcloud container images list-tags "gcr.io/${GCP_PROJECT_ID}/${SERVICE_NAME}" \\',
        '  --format="get(digest)" 2>/dev/null | while read -r DIGEST; do',
        '  gcloud container images delete \\',
        '    "gcr.io/${GCP_PROJECT_ID}/${SERVICE_NAME}@${DIGEST}" \\',
        '    --quiet --force-delete-tags 2>/dev/null || true',
        'done',
        'echo "  Container images cleaned."',
        '',
        '# Step 3: Remove IAM policy bindings for the service account',
        'echo "[3/4] Removing IAM bindings for ${SERVICE_ACCOUNT}..."',
        'for ROLE in roles/run.invoker roles/secretmanager.secretAccessor roles/cloudsql.client roles/logging.logWriter roles/monitoring.metricWriter; do',
        '  gcloud projects remove-iam-policy-binding "${GCP_PROJECT_ID}" \\',
        '    --member "serviceAccount:${SERVICE_ACCOUNT}" \\',
        '    --role "${ROLE}" \\',
        '    --quiet 2>/dev/null || true',
        'done',
        'echo "  IAM bindings removed."',
        '',
        '# Step 4: Optionally delete the service account',
        'echo "[4/4] Optionally deleting service account..."',
        'read -rp "Delete service account ${SERVICE_ACCOUNT}? (y/N): " DEL_SA',
        'if [[ "${DEL_SA}" == "y" || "${DEL_SA}" == "Y" ]]; then',
        '  gcloud iam service-accounts delete "${SERVICE_ACCOUNT}" \\',
        '    --quiet 2>/dev/null || echo "  Service account not found."',
        'fi',
        '',
        'echo ""',
        'echo "=================================================================="',
        'echo "Teardown complete."',
        'echo "=================================================================="',
        '',
    ].join('\n');
}
/**
 * Generate env.template: environment variable template with Secret Manager
 * references for all production secrets.
 */
function generateEnvTemplate(vars, erpSystem) {
    return [
        '# Generated by Phase 5 pipeline — do not edit manually',
        '#',
        '# Environment variable template for production deployment.',
        '# Secret Manager references follow the format: projects/PROJECT/secrets/NAME/versions/latest',
        '#',
        '# Copy this file and fill in your GCP project-specific values.',
        '# NEVER commit resolved secrets to version control.',
        '',
        '# ---- GCP Configuration ----',
        'GCP_PROJECT_ID=',
        `GCP_REGION=${vars.region}`,
        `SERVICE_NAME=${vars.serviceName}`,
        `SERVICE_ACCOUNT=${vars.serviceAccount}`,
        '',
        '# ---- Application Configuration ----',
        'PORT=8080',
        'NODE_ENV=production',
        `ERP_SYSTEM=${erpSystem}`,
        'LOG_LEVEL=info',
        '',
        '# ---- SAP Credentials (Secret Manager references) ----',
        '# These are injected via --set-secrets in deploy.sh',
        '# Create these secrets in Secret Manager before deploying:',
        '#   gcloud secrets create sap-api-key --replication-policy="automatic"',
        '#   echo -n "YOUR_KEY" | gcloud secrets versions add sap-api-key --data-file=-',
        'SAP_API_KEY=projects/${GCP_PROJECT_ID}/secrets/sap-api-key/versions/latest',
        'SAP_CLIENT_CERT=projects/${GCP_PROJECT_ID}/secrets/sap-client-cert/versions/latest',
        'SAP_OAUTH_SECRET=projects/${GCP_PROJECT_ID}/secrets/sap-oauth-secret/versions/latest',
        '',
        '# ---- Database Configuration (if applicable) ----',
        'DB_CONNECTION_STRING=projects/${GCP_PROJECT_ID}/secrets/db-connection-string/versions/latest',
        'DB_MAX_POOL_SIZE=10',
        'DB_IDLE_TIMEOUT_MS=30000',
        '',
        '# ---- Observability ----',
        'OTEL_EXPORTER_OTLP_ENDPOINT=',
        'OTEL_SERVICE_NAME=${SERVICE_NAME}',
        'OTEL_RESOURCE_ATTRIBUTES=service.namespace=erp-surface,deployment.environment=production',
        '',
        '# ---- VPC / Networking ----',
        `VPC_CONNECTOR=${vars.vpcConnector}`,
        'VPC_EGRESS=all-traffic',
        '',
    ].join('\n');
}
/**
 * Generate vpc-setup.sh: creates the Serverless VPC Access connector
 * required for Cloud Run to reach the ERP network.
 *
 * If the infra repo is cached, references its networking patterns.
 */
function generateVpcSetupScript(vars, infraRepoPath) {
    let infraNote = '';
    if (infraRepoPath) {
        infraNote = [
            '# NOTE: This script follows the networking patterns from the infra repo.',
            `# Reference: ${infraRepoPath}/modules/networking/`,
            '#',
            '',
        ].join('\n');
    }
    return [
        SCRIPT_HEADER,
        '# ============================================================================',
        `# VPC Connector Setup for ${vars.serviceName}`,
        '# ============================================================================',
        '#',
        '# Creates a Serverless VPC Access connector so Cloud Run can reach',
        '# the ERP system over a private network path.',
        '#',
        infraNote,
        'GCP_PROJECT_ID=${GCP_PROJECT_ID:?ERROR: GCP_PROJECT_ID must be set}',
        `GCP_REGION="\${GCP_REGION:-${vars.region}}"`,
        `VPC_CONNECTOR="\${VPC_CONNECTOR:-${vars.vpcConnector}}"`,
        'VPC_NETWORK="${VPC_NETWORK:-default}"',
        'VPC_CIDR="${VPC_CIDR:-10.8.0.0/28}"',
        '',
        'echo "=================================================================="',
        'echo "Setting up VPC connector: ${VPC_CONNECTOR}"',
        'echo "  Project:  ${GCP_PROJECT_ID}"',
        'echo "  Region:   ${GCP_REGION}"',
        'echo "  Network:  ${VPC_NETWORK}"',
        'echo "  CIDR:     ${VPC_CIDR}"',
        'echo "=================================================================="',
        '',
        '# Step 1: Enable required APIs',
        'echo "[1/4] Enabling required APIs..."',
        'gcloud services enable vpcaccess.googleapis.com \\',
        '  --project "${GCP_PROJECT_ID}" \\',
        '  --quiet',
        '',
        '# Step 2: Create the VPC connector',
        'echo "[2/4] Creating VPC connector..."',
        'gcloud compute networks vpc-access connectors create "${VPC_CONNECTOR}" \\',
        '  --region "${GCP_REGION}" \\',
        '  --network "${VPC_NETWORK}" \\',
        '  --range "${VPC_CIDR}" \\',
        '  --min-instances 2 \\',
        '  --max-instances 10 \\',
        '  --machine-type e2-micro \\',
        '  --quiet 2>/dev/null || {',
        '    echo "  VPC connector already exists or creation failed."',
        '    echo "  Checking existing connector..."',
        '    gcloud compute networks vpc-access connectors describe "${VPC_CONNECTOR}" \\',
        '      --region "${GCP_REGION}" \\',
        '      --format "table(name, state, network, ipCidrRange)"',
        '  }',
        '',
        '# Step 3: Create firewall rules for ERP traffic',
        'echo "[3/4] Creating firewall rules..."',
        'gcloud compute firewall-rules create "allow-${VPC_CONNECTOR}-to-erp" \\',
        '  --network "${VPC_NETWORK}" \\',
        '  --allow tcp:443,tcp:8443 \\',
        '  --source-ranges "${VPC_CIDR}" \\',
        '  --target-tags "erp-backend" \\',
        '  --description "Allow VPC connector traffic to ERP system (HTTPS/OData)" \\',
        '  --quiet 2>/dev/null || echo "  Firewall rule already exists."',
        '',
        '# Step 4: Verify connectivity',
        'echo "[4/4] Verifying VPC connector status..."',
        'gcloud compute networks vpc-access connectors describe "${VPC_CONNECTOR}" \\',
        '  --region "${GCP_REGION}" \\',
        '  --format "table(name, state, network, ipCidrRange, minInstances, maxInstances)"',
        '',
        'echo ""',
        'echo "=================================================================="',
        'echo "VPC connector setup complete."',
        'echo "  Connector: ${VPC_CONNECTOR}"',
        'echo "  Use --vpc-connector=${VPC_CONNECTOR} in deploy.sh"',
        'echo "=================================================================="',
        '',
    ].join('\n');
}
/**
 * Generate monitoring.yaml: Cloud Monitoring alert policies for the
 * deployed ERP surface service.
 *
 * Includes alerts for:
 * - High error rate (5xx responses)
 * - Elevated latency (p99 > threshold)
 * - Instance count anomalies
 * - SAP connectivity failures
 */
function generateMonitoringYaml(vars) {
    const sn = vars.serviceName;
    return [
        '# Generated by Phase 5 pipeline — do not edit manually',
        '#',
        `# Cloud Monitoring alert policies for ${sn}`,
        '# Apply with: gcloud alpha monitoring policies create --policy-from-file=monitoring.yaml',
        '',
        '# ============================================================================',
        '# Alert Policy 1: High Error Rate (5xx)',
        '# ============================================================================',
        'alertPolicies:',
        `  - displayName: "[${sn}] High Error Rate"`,
        '    documentation:',
        '      content: |',
        `        The Cloud Run service ${sn} is returning an elevated`,
        '        rate of 5xx errors. This may indicate ERP connectivity issues,',
        '        authentication failures, or application-level bugs.',
        '      mimeType: text/markdown',
        '    conditions:',
        '      - displayName: "5xx Error Rate > 5%"',
        '        conditionThreshold:',
        '          filter: >-',
        '            resource.type="cloud_run_revision"',
        `            AND resource.labels.service_name="${sn}"`,
        '            AND metric.type="run.googleapis.com/request_count"',
        '            AND metric.labels.response_code_class="5xx"',
        '          comparison: COMPARISON_GT',
        '          thresholdValue: 0.05',
        '          duration: 300s',
        '          aggregations:',
        '            - alignmentPeriod: 60s',
        '              perSeriesAligner: ALIGN_RATE',
        '              crossSeriesReducer: REDUCE_SUM',
        '    combiner: OR',
        '    notificationChannels: []  # Configure after deployment',
        '    alertStrategy:',
        '      autoClose: 1800s',
        '',
        '  # ==========================================================================',
        '  # Alert Policy 2: Elevated Latency (p99)',
        '  # ==========================================================================',
        `  - displayName: "[${sn}] Elevated Latency (p99 > 5s)"`,
        '    documentation:',
        '      content: |',
        `        The p99 latency for ${sn} has exceeded 5 seconds.`,
        '        This may indicate SAP OData service degradation, cold start issues,',
        '        or VPC connector saturation.',
        '      mimeType: text/markdown',
        '    conditions:',
        '      - displayName: "p99 Latency > 5s"',
        '        conditionThreshold:',
        '          filter: >-',
        '            resource.type="cloud_run_revision"',
        `            AND resource.labels.service_name="${sn}"`,
        '            AND metric.type="run.googleapis.com/request_latencies"',
        '          comparison: COMPARISON_GT',
        '          thresholdValue: 5000',
        '          duration: 300s',
        '          aggregations:',
        '            - alignmentPeriod: 60s',
        '              perSeriesAligner: ALIGN_PERCENTILE_99',
        '              crossSeriesReducer: REDUCE_MAX',
        '    combiner: OR',
        '    notificationChannels: []',
        '    alertStrategy:',
        '      autoClose: 1800s',
        '',
        '  # ==========================================================================',
        '  # Alert Policy 3: Instance Count Anomaly',
        '  # ==========================================================================',
        `  - displayName: "[${sn}] Instance Count at Max"`,
        '    documentation:',
        '      content: |',
        `        The number of active instances for ${sn} has reached`,
        '        the configured maximum (10). This may indicate a traffic surge or',
        '        a resource leak causing instances to not terminate.',
        '      mimeType: text/markdown',
        '    conditions:',
        '      - displayName: "Active Instances >= 10"',
        '        conditionThreshold:',
        '          filter: >-',
        '            resource.type="cloud_run_revision"',
        `            AND resource.labels.service_name="${sn}"`,
        '            AND metric.type="run.googleapis.com/container/instance_count"',
        '          comparison: COMPARISON_GT',
        '          thresholdValue: 9',
        '          duration: 600s',
        '          aggregations:',
        '            - alignmentPeriod: 60s',
        '              perSeriesAligner: ALIGN_MAX',
        '              crossSeriesReducer: REDUCE_SUM',
        '    combiner: OR',
        '    notificationChannels: []',
        '    alertStrategy:',
        '      autoClose: 3600s',
        '',
        '  # ==========================================================================',
        '  # Alert Policy 4: SAP Connectivity Failure',
        '  # ==========================================================================',
        `  - displayName: "[${sn}] SAP Connectivity Failure"`,
        '    documentation:',
        '      content: |',
        `        The health check endpoint for ${sn} is reporting SAP`,
        '        connectivity failures. This may indicate VPC connector issues, SAP',
        '        system maintenance, or credential expiration.',
        '      mimeType: text/markdown',
        '    conditions:',
        '      - displayName: "Health Check Failures > 3 in 5m"',
        '        conditionThreshold:',
        '          filter: >-',
        '            resource.type="cloud_run_revision"',
        `            AND resource.labels.service_name="${sn}"`,
        '            AND metric.type="logging.googleapis.com/user/sap_connectivity_failure"',
        '          comparison: COMPARISON_GT',
        '          thresholdValue: 3',
        '          duration: 300s',
        '          aggregations:',
        '            - alignmentPeriod: 60s',
        '              perSeriesAligner: ALIGN_SUM',
        '              crossSeriesReducer: REDUCE_SUM',
        '    combiner: OR',
        '    notificationChannels: []',
        '    alertStrategy:',
        '      autoClose: 1800s',
        '',
    ].join('\n');
}
// ============================================================================
// Helper: Write a script file with executable permissions
// ============================================================================
/**
 * Write a script file to disk, creating parent directories as needed.
 * Scripts get 0o700 permissions (owner read/write/execute).
 */
function writeScript(absPath, content) {
    writeFileSync(absPath, content, { encoding: 'utf-8', mode: EXEC_MODE });
}
/**
 * Write a non-executable artifact file to disk.
 */
function writeArtifact(absPath, content) {
    writeFileSync(absPath, content, { encoding: 'utf-8', mode: FILE_MODE });
}
// ============================================================================
// Helper: Check for infra repo patterns
// ============================================================================
/**
 * If the infra platform repo is cached, return its path.
 * Used by vpc-setup.sh for reference documentation.
 */
function resolveInfraRepoPath(platformRepoPaths) {
    const infraPath = platformRepoPaths['infra'];
    if (!infraPath)
        return undefined;
    if (!existsSync(infraPath))
        return undefined;
    return infraPath;
}
// ============================================================================
// Main: finalizeDeployment
// ============================================================================
/**
 * Stage 4: Generate production-ready deployment scripts.
 *
 * Creates the `phase5/deploy/` directory and generates five deployment
 * artifacts:
 *
 * 1. **deploy.sh** - Primary gcloud CLI deployment script with VPC connector,
 *    Secret Manager references, least-privilege service account, and
 *    internal-only ingress.
 *
 * 2. **teardown.sh** - Reverse of deploy.sh: deletes Cloud Run service,
 *    container images, and IAM bindings.
 *
 * 3. **env.template** - Environment variable template with Secret Manager
 *    reference format for all production secrets.
 *
 * 4. **vpc-setup.sh** - Creates the Serverless VPC Access connector for
 *    ERP network connectivity. References infra repo patterns if cached.
 *
 * 5. **monitoring.yaml** - Cloud Monitoring alert policies for error rate,
 *    latency, instance count, and SAP connectivity.
 *
 * @param context - The mutable Phase 5 pipeline context
 * @returns Stage output describing success or failure
 */
export function finalizeDeployment(context) {
    const startTime = Date.now();
    const rootSpan = createSpan('deployment-finalization', 'finalize-deployment', {
        phase5Dir: context.phase5Dir,
        erpSystem: context.phase4Artifacts.erpSystem,
    });
    try {
        // -------------------------------------------------------------------------
        // Step 1: Derive deployment variables
        // -------------------------------------------------------------------------
        const varsSpan = createSpan('deployment-finalization', 'derive-deployment-vars', {}, rootSpan.spanId);
        const vars = deriveDeploymentVars(context);
        const erpSystem = context.phase4Artifacts.erpSystem;
        const infraRepoPath = resolveInfraRepoPath(context.platformRepoPaths);
        const finalVarsSpan = endSpan(varsSpan, 'ok', {
            serviceName: vars.serviceName,
            region: vars.region,
            vpcConnector: vars.vpcConnector,
            hasInfraRepo: infraRepoPath !== undefined,
        });
        emitSpan(finalVarsSpan);
        context.telemetrySpans.push(finalVarsSpan);
        // -------------------------------------------------------------------------
        // Step 2: Create the deploy/ directory
        // -------------------------------------------------------------------------
        const deployDir = join(context.phase5Dir, 'deploy');
        mkdirSync(deployDir, { recursive: true, mode: DIR_MODE });
        const writtenPaths = [];
        // -------------------------------------------------------------------------
        // Step 3: Generate all deployment scripts
        // -------------------------------------------------------------------------
        const genSpan = createSpan('deployment-finalization', 'generate-scripts', { deployDir }, rootSpan.spanId);
        // deploy.sh
        const deployShPath = join(deployDir, 'deploy.sh');
        writeScript(deployShPath, generateDeployScript(vars, erpSystem));
        writtenPaths.push(deployShPath);
        // teardown.sh
        const teardownShPath = join(deployDir, 'teardown.sh');
        writeScript(teardownShPath, generateTeardownScript(vars));
        writtenPaths.push(teardownShPath);
        // env.template
        const envTemplatePath = join(deployDir, 'env.template');
        writeArtifact(envTemplatePath, generateEnvTemplate(vars, erpSystem));
        writtenPaths.push(envTemplatePath);
        // vpc-setup.sh
        const vpcSetupPath = join(deployDir, 'vpc-setup.sh');
        writeScript(vpcSetupPath, generateVpcSetupScript(vars, infraRepoPath));
        writtenPaths.push(vpcSetupPath);
        // monitoring.yaml
        const monitoringPath = join(deployDir, 'monitoring.yaml');
        writeArtifact(monitoringPath, generateMonitoringYaml(vars));
        writtenPaths.push(monitoringPath);
        const finalGenSpan = endSpan(genSpan, 'ok', {
            filesGenerated: writtenPaths.length,
        });
        emitSpan(finalGenSpan);
        context.telemetrySpans.push(finalGenSpan);
        // -------------------------------------------------------------------------
        // Step 4: Build and return stage output
        // -------------------------------------------------------------------------
        const finalRootSpan = endSpan(rootSpan, 'ok', {
            serviceName: vars.serviceName,
            erpSystem,
            filesGenerated: writtenPaths.length,
            hasInfraRepo: infraRepoPath !== undefined,
        });
        emitSpan(finalRootSpan);
        context.telemetrySpans.push(finalRootSpan);
        const timing = Date.now() - startTime;
        const output = {
            stage: 'deployment-finalization',
            status: 'completed',
            data: {
                deployDir,
                serviceName: vars.serviceName,
                region: vars.region,
                vpcConnector: vars.vpcConnector,
                filesGenerated: writtenPaths.length,
            },
            artifacts: writtenPaths,
            timing,
        };
        context.stageOutputs.set('deployment-finalization', output);
        return output;
    }
    catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        const finalRootSpan = endSpan(rootSpan, 'error', { error: errorMessage });
        emitSpan(finalRootSpan);
        context.telemetrySpans.push(finalRootSpan);
        const timing = Date.now() - startTime;
        const output = {
            stage: 'deployment-finalization',
            status: 'failed',
            data: { error: errorMessage },
            artifacts: [],
            timing,
        };
        context.stageOutputs.set('deployment-finalization', output);
        return output;
    }
}
//# sourceMappingURL=deployment-finalizer.js.map