"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var CliK3sScriptService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliK3sScriptService = void 0;
const common_1 = require("@nestjs/common");
const node_fs_1 = require("node:fs");
const path = __importStar(require("node:path"));
const os = __importStar(require("node:os"));
const cli_logger_service_1 = require("./cli-logger.service");
const bootstrap_config_1 = require("../config/bootstrap.config");
/**
 * CLI K3s Script Service
 *
 * Generates K3s initialization scripts for observability clusters.
 * Uses scripts from cli/src/modules/instances/assets/scripts/ directory.
 */
let CliK3sScriptService = CliK3sScriptService_1 = class CliK3sScriptService {
    constructor(cliLogger) {
        this.cliLogger = cliLogger;
        this.logger = new common_1.Logger(CliK3sScriptService_1.name);
    }
    /**
     * Log to both console and operation log file
     */
    log(message, operationId, level = 'INFO') {
        // Always log to console
        switch (level) {
            case 'ERROR':
                this.logger.error(message);
                break;
            case 'WARN':
                this.logger.warn(message);
                break;
            case 'DEBUG':
                this.logger.debug(message);
                break;
            default:
                this.logger.log(message);
        }
        // Also log to file if operationId is provided
        if (operationId) {
            this.cliLogger.writeLog(operationId, message, level);
        }
    }
    /**
     * Generate cloud-init script for K3s master node
     * Uses bootstrap approach: generates minimal script that downloads from GitHub
     */
    async generateMasterScript(config) {
        const opId = config.operationId;
        try {
            this.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, opId);
            this.log(`[BOOTSTRAP MASTER SCRIPT] Cluster: ${config.clusterName}`, opId);
            this.log(`Scripts URL: ${bootstrap_config_1.BOOTSTRAP_CONFIG.scriptsBaseUrl}`, opId);
            // Generate bootstrap script that downloads and executes k3s-master-init.sh from GitHub
            const script = this.generateBootstrapScript('master', {
                SCRIPTS_BASE_URL: bootstrap_config_1.BOOTSTRAP_CONFIG.scriptsBaseUrl,
                MANIFESTS_BASE_URL: bootstrap_config_1.BOOTSTRAP_CONFIG.scriptsBaseUrl.replace('/scripts', '/manifests'),
                SERVER_ID: config.serverId || '', // Database node ID for observability
                INSTANCE_ID: config.instanceId,
                INSTANCE_NAME: config.instanceName,
                CLOUD_PROVIDER: config.provider,
                CLUSTER_ID: config.clusterId,
                CLUSTER_NAME: config.clusterName,
                K3S_TOKEN: config.k3sToken,
                K3S_VERSION: config.k3sVersion || 'v1.35.4+k3s1',
                DEPLOY_OBSERVABILITY_STACK: config.deployObservabilityStack
                    ? 'true'
                    : 'false',
                POSTGRES_PASSWORD: config.postgresPassword,
                REDIS_PASSWORD: config.redisPassword,
                GRAFANA_PASSWORD: config.grafanaPassword,
                AUTH_MODE: config.authMode || 'local',
                JWT_SECRET: config.jwtSecret || '',
                ADMIN_EMAIL: config.adminEmail || '',
                ADMIN_PASSWORD: config.adminPassword || '',
                ENCRYPTION_KEY: config.encryptionKey || '',
                ZITADEL_MASTERKEY: config.zitadelMasterkey || '',
                ZITADEL_DB_ADMIN_PASSWORD: config.zitadelDbAdminPassword || '',
                ZITADEL_DB_USER_PASSWORD: config.zitadelDbUserPassword || '',
                ZITADEL_DOMAIN: config.zitadelDomain || '',
                ZITADEL_ADMIN_EMAIL: config.zitadelAdminEmail || config.adminEmail || '',
                ZITADEL_ADMIN_TEMP_PASSWORD: config.zitadelAdminTempPassword || '',
                ZITADEL_AUDIENCE: '',
                FLUI_CA_PUBLIC_KEY: config.caPublicKey || '',
                FLUI_NIP_IO_CERT_ENABLED: config.nipIoCertEnabled ? 'true' : '',
                FLUI_ACME_STAGING: config.acmeStaging ? 'true' : '',
                // BootstrapSeeder vars — available at envsubst time so API reads them at first boot
                FLUI_CLI_API_KEY: config.fluiApiKey || '',
                PROVIDER_HETZNER_API_KEY: config.provider === 'hetzner' ? config.providerApiKey || '' : '',
                PROVIDER_SCALEWAY_ACCESS_KEY: config.providerScalewayAccessKey || '',
                PROVIDER_SCALEWAY_SECRET_KEY: config.providerScalewaySecretKey || '',
                PROVIDER_REGIONS: config.providerRegions || '',
                CLUSTER_REGION: config.clusterRegion || '',
                INSTANCE_TYPE: config.instanceType || '',
                CLUSTER_FIREWALL_ID: config.clusterFirewallId || '',
                FLUI_VNET_PROVIDER_RESOURCE_ID: config.envVnet?.vnetProviderResourceId || '',
                FLUI_VNET_PROVIDER: config.envVnet?.vnetProvider || '',
                FLUI_VNET_NAME: config.envVnet?.vnetName || '',
                FLUI_VNET_IP_RANGE: config.envVnet?.vnetIpRange || '',
                FLUI_SUBNET_PROVIDER_RESOURCE_ID: config.envVnet?.subnetProviderResourceId || '',
                FLUI_SUBNET_IP_RANGE: config.envVnet?.subnetIpRange || '',
                FLUI_SUBNET_TYPE: config.envVnet?.subnetType || '',
                FLUI_SUBNET_NETWORK_ZONE: config.envVnet?.networkZone || '',
                NIP_HOSTNAME_TOKEN: config.nipHostnameToken || '',
                // Flui shared storage (NFS+fscache, scaling doc §14)
                FLUI_SHARED_STORAGE_ENABLED: config.sharedStorage?.enabled
                    ? 'true'
                    : 'false',
                FLUI_SHARED_STORAGE_DEVICE: config.sharedStorage?.volumeDevicePath ?? '',
                FLUI_SHARED_STORAGE_VOLUME_GB: String(config.sharedStorage?.volumeSizeGb ?? 0),
            });
            this.log(`Bootstrap script generated: ${script.length} bytes`, opId);
            // VALIDATION: Check script size is within limits
            const MAX_SIZE = 32000; // Hetzner limit: 32 KiB
            if (script.length > MAX_SIZE) {
                throw new Error(`Bootstrap script exceeds Hetzner limit: ${script.length} bytes > ${MAX_SIZE} bytes`);
            }
            this.log(`✓ Script size OK: ${script.length} / ${MAX_SIZE} bytes`, opId);
            // Save debug copy
            await this.saveDebugScript(config.clusterId, 'master.sh', script, opId);
            this.log(`✅ Bootstrap master script generated successfully`, opId);
            this.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, opId);
            return script;
        }
        catch (error) {
            this.logger.error(`Failed to generate master script: ${error.message}`, error.stack);
            throw error;
        }
    }
    /**
     * Generate cloud-init script for K3s worker node
     * Uses bootstrap approach: generates minimal script that downloads from GitHub
     */
    async generateWorkerScript(config) {
        const opId = config.operationId;
        try {
            this.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, opId);
            this.log(`[BOOTSTRAP WORKER SCRIPT] Cluster: ${config.clusterName}`, opId);
            this.log(`Scripts URL: ${bootstrap_config_1.BOOTSTRAP_CONFIG.scriptsBaseUrl}`, opId);
            // Generate bootstrap script that downloads and executes k3s-worker-init.sh from GitHub
            const script = this.generateBootstrapScript('worker', {
                SERVER_ID: config.serverId || '', // Database node ID for observability
                SCRIPTS_BASE_URL: bootstrap_config_1.BOOTSTRAP_CONFIG.scriptsBaseUrl,
                INSTANCE_ID: config.instanceId,
                INSTANCE_NAME: config.instanceName,
                CLOUD_PROVIDER: config.provider,
                CLUSTER_ID: config.clusterId,
                CLUSTER_NAME: config.clusterName,
                K3S_TOKEN: config.k3sToken,
                K3S_URL: `https://${config.masterIp}:6443`,
                K3S_VERSION: config.k3sVersion || 'v1.35.4+k3s1',
                MASTER_IP: config.masterIp,
                FLUI_CA_PUBLIC_KEY: config.caPublicKey || '',
                // Flui shared storage (NFS+fscache, scaling doc §14)
                FLUI_SHARED_STORAGE_ENABLED: config.sharedStorage?.enabled
                    ? 'true'
                    : 'false',
                FLUI_SHARED_STORAGE_MASTER_IP: config.sharedStorage?.masterPrivateIp ?? '',
            });
            this.log(`Bootstrap script generated: ${script.length} bytes`, opId);
            // VALIDATION: Check script size is within limits
            const MAX_SIZE = 32000; // Hetzner limit: 32 KiB
            if (script.length > MAX_SIZE) {
                throw new Error(`Bootstrap script exceeds Hetzner limit: ${script.length} bytes > ${MAX_SIZE} bytes`);
            }
            this.log(`✓ Script size OK: ${script.length} / ${MAX_SIZE} bytes`, opId);
            // Save debug copy
            await this.saveDebugScript(config.clusterId, 'worker.sh', script, opId);
            this.log(`✅ Bootstrap worker script generated successfully`, opId);
            this.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, opId);
            return script;
        }
        catch (error) {
            this.log(`Failed to generate worker script: ${error.message}`, opId, 'ERROR');
            this.logger.error(`Failed to generate worker script: ${error.message}`, error.stack);
            throw error;
        }
    }
    /**
     * Generate bootstrap script that downloads and executes K3s init script from GitHub
     */
    generateBootstrapScript(type, vars) {
        const scriptName = type === 'master' ? 'k3s-master-init.sh' : 'k3s-worker-init.sh';
        // Export all variables
        const exports = Object.entries(vars)
            .map(([key, value]) => {
            // Escape single quotes in value
            const escapedValue = value.replaceAll("'", String.raw `'\''`);
            return `export ${key}='${escapedValue}'`;
        })
            .join('\n');
        return `#!/bin/bash
# Flui.cloud Bootstrap Script (${type})
# Downloads and executes ${scriptName} from GitHub
set -euo pipefail

# Configuration variables
${exports}

if [ -z "\${PRIVATE_IP:-}" ]; then
  PRIVATE_IP=$(ip -4 -o addr show 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep -E '^(10\\.|172\\.(1[6-9]|2[0-9]|3[01])\\.|192\\.168\\.)' | head -1 || true)
fi
export PRIVATE_IP="\${PRIVATE_IP:-}"
export FLUI_BOOTSTRAP_NODE_PRIVATE_IP="\${PRIVATE_IP:-}"
echo "[Bootstrap] PRIVATE_IP=\${PRIVATE_IP:-(unresolved)}"

# Download and execute K3s initialization script
echo "[Bootstrap] Downloading ${scriptName} from \${SCRIPTS_BASE_URL}..."
if ! curl -fsSL "\${SCRIPTS_BASE_URL}/${scriptName}" -o /tmp/${scriptName}; then
    echo "[Bootstrap] ERROR: Failed to download ${scriptName}"
    exit 1
fi

chmod +x /tmp/${scriptName}
echo "[Bootstrap] Executing ${scriptName}..."
if ! /tmp/${scriptName}; then
    echo "[Bootstrap] ERROR: ${scriptName} execution failed"
    exit 1
fi

echo "[Bootstrap] ${scriptName} completed successfully"
`;
    }
    /**
     * Save script to debug directory for inspection
     */
    async saveDebugScript(clusterId, filename, content, operationId) {
        try {
            const debugDir = path.join(os.homedir(), '.flui', 'debug', clusterId);
            await node_fs_1.promises.mkdir(debugDir, { recursive: true });
            const debugPath = path.join(debugDir, filename);
            await node_fs_1.promises.writeFile(debugPath, content, 'utf8');
            this.log(`💾 Debug script saved: ${debugPath}`, operationId);
        }
        catch (error) {
            this.log(`Failed to save debug script: ${error.message}`, operationId, 'WARN');
            // Don't throw - this is just for debugging
        }
    }
};
exports.CliK3sScriptService = CliK3sScriptService;
exports.CliK3sScriptService = CliK3sScriptService = CliK3sScriptService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [cli_logger_service_1.CliLoggerService])
], CliK3sScriptService);
