"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 __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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrCreateSSHKey = getOrCreateSSHKey;
exports.getSSHKeyInfo = getSSHKeyInfo;
exports.deleteSSHKey = deleteSSHKey;
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const os = __importStar(require("node:os"));
const node_child_process_1 = require("node:child_process");
const SSH_DIR = path.join(os.homedir(), '.ssh');
const FLUI_KEY_NAME = 'flui_shared_dev';
const FLUI_KEY_PATH = path.join(SSH_DIR, FLUI_KEY_NAME);
/**
 * Ensure .ssh directory exists with correct permissions
 */
function ensureSSHDir() {
    if (!fs.existsSync(SSH_DIR)) {
        fs.mkdirSync(SSH_DIR, { mode: 0o700, recursive: true });
    }
}
/**
 * Get or generate SSH key pair for Flui CLI
 * @returns SSH key pair with public key content and private key path
 */
function getOrCreateSSHKey() {
    ensureSSHDir();
    const privateKeyPath = FLUI_KEY_PATH;
    const publicKeyPath = `${FLUI_KEY_PATH}.pub`;
    // Check if key already exists
    if (fs.existsSync(publicKeyPath) && fs.existsSync(privateKeyPath)) {
        const publicKey = fs.readFileSync(publicKeyPath, 'utf-8').trim();
        return {
            publicKey,
            privateKeyPath,
        };
    }
    // Generate new SSH key (ed25519 for security and performance)
    try {
        (0, node_child_process_1.execFileSync)('ssh-keygen', [
            '-t',
            'ed25519',
            '-C',
            'flui-cli@shared-dev',
            '-f',
            privateKeyPath,
            '-N',
            '',
        ], { stdio: 'pipe' });
        // Set correct permissions
        fs.chmodSync(privateKeyPath, 0o600);
        fs.chmodSync(publicKeyPath, 0o644);
        const publicKey = fs.readFileSync(publicKeyPath, 'utf-8').trim();
        return {
            publicKey,
            privateKeyPath,
        };
    }
    catch (error) {
        throw new Error(`Failed to generate SSH key: ${error instanceof Error ? error.message : String(error)}`);
    }
}
/**
 * Get SSH key information without generating
 * @returns Key info or null if doesn't exist
 */
function getSSHKeyInfo() {
    const publicKeyPath = `${FLUI_KEY_PATH}.pub`;
    if (fs.existsSync(publicKeyPath)) {
        const publicKey = fs.readFileSync(publicKeyPath, 'utf-8').trim();
        return {
            exists: true,
            path: FLUI_KEY_PATH,
            publicKey,
        };
    }
    return {
        exists: false,
        path: FLUI_KEY_PATH,
    };
}
/**
 * Delete SSH key pair
 */
function deleteSSHKey() {
    const privateKeyPath = FLUI_KEY_PATH;
    const publicKeyPath = `${FLUI_KEY_PATH}.pub`;
    if (fs.existsSync(privateKeyPath)) {
        fs.unlinkSync(privateKeyPath);
    }
    if (fs.existsSync(publicKeyPath)) {
        fs.unlinkSync(publicKeyPath);
    }
}
