"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.writeSshConfig = writeSshConfig;
const fs = __importStar(require("node:fs/promises"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const vscode = __importStar(require("vscode"));
const authority_1 = require("./authority");
const START_MARKER = '# --- START-NICLOUD ---';
const END_MARKER = '# --- END-NICLOUD ---';
async function writeSshConfig(deployment, _owner, _workspace, _agent, cliPath, output) {
    const sshDir = path.join(os.homedir(), '.ssh');
    const configPath = path.join(sshDir, 'config');
    await fs.mkdir(sshDir, { recursive: true, mode: 0o700 });
    let existing = '';
    try {
        existing = await fs.readFile(configPath, 'utf8');
    }
    catch {
        // file doesn't exist yet
    }
    const headerCmd = getHeaderCommand();
    const insecure = vscode.workspace
        .getConfiguration('neuralinverse.cloud')
        .get('insecure', false);
    const hostPattern = `${authority_1.AUTHORITY_PREFIX}${deployment.safeHostname}--*`;
    const quotedCliPath = cliPath.includes(' ') ? `"${cliPath}"` : cliPath;
    const prefix = `${authority_1.AUTHORITY_PREFIX}${deployment.safeHostname}--`;
    // Use --global-config to store session config, matching coder extension pattern.
    // This avoids /bin/sh -c wrappers which break open-remote-ssh's arg splitting.
    const globalConfigDir = path.dirname(cliPath);
    const proxyCmd = [
        quotedCliPath,
        `--global-config "${globalConfigDir}"`,
        `--url ${deployment.url}`,
        `--token ${deployment.token}`,
        'ssh --stdio',
        `--ssh-host-prefix ${prefix}`,
    ];
    if (headerCmd) {
        proxyCmd.push(`--header-command "${headerCmd}"`);
    }
    proxyCmd.push('%h');
    const userSshConfig = vscode.workspace
        .getConfiguration('neuralinverse.cloud')
        .get('sshConfig', []);
    const lines = [
        `Host ${hostPattern}`,
        `  ProxyCommand ${proxyCmd.join(' ')}`,
        '  ConnectTimeout 30',
        '  StrictHostKeyChecking no',
        '  UserKnownHostsFile /dev/null',
        '  LogLevel ERROR',
        '  ServerAliveInterval 5',
        '  ServerAliveCountMax 3',
    ];
    if (insecure) {
        lines.push('  SetEnv NEURALINVERSE_TLS_INSECURE=true');
    }
    for (const item of userSshConfig) {
        lines.push(`  ${item}`);
    }
    const block = `${START_MARKER}\n${lines.join('\n')}\n${END_MARKER}`;
    const startIdx = existing.indexOf(START_MARKER);
    const endIdx = existing.indexOf(END_MARKER);
    let updated;
    if (startIdx >= 0 && endIdx >= 0) {
        updated = existing.slice(0, startIdx) + block + existing.slice(endIdx + END_MARKER.length);
    }
    else {
        updated = existing ? `${existing.trimEnd()}\n\n${block}\n` : `${block}\n`;
    }
    await fs.writeFile(configPath, updated, { mode: 0o600 });
    output.appendLine(`SSH config updated: ${configPath}`);
}
function getHeaderCommand() {
    return vscode.workspace
        .getConfiguration('neuralinverse.cloud')
        .get('headerCommand', '');
}
//# sourceMappingURL=sshConfig.js.map