"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CODIAC_SESSION_ID_VAR = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const crypto = require("crypto");
const os = require("os");
/** The environment variable that carries a stable per-shell session identifier. */
exports.CODIAC_SESSION_ID_VAR = "CODIAC_SESSION_ID";
class ShellInit extends core_1.Command {
    run() {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(ShellInit);
            const shell = (_a = flags.shell) !== null && _a !== void 0 ? _a : this.detectShell();
            const sessionId = crypto.randomUUID();
            const snippet = this.buildSnippet(shell, sessionId);
            // Write directly to stdout (not through _ui) so `eval` captures only the snippet.
            process.stdout.write(snippet + '\n');
        });
    }
    detectShell() {
        var _a;
        // Shell-set variables are the most reliable signal — the shell injects these itself,
        // so they work even in environments like Git Bash on Windows where os.platform()
        // returns 'win32' but the running shell is actually bash.
        if (process.env['BASH_VERSION'] || process.env['BASH'])
            return 'bash';
        if (process.env['ZSH_VERSION'])
            return 'zsh';
        if (process.env['FISH_VERSION'])
            return 'fish';
        // Fall back to parsing $SHELL (set by most Unix shells on launch).
        // Split on both / and \ to handle Windows paths like C:\Program Files\Git\usr\bin\bash.exe.
        const shellEnv = process.env['SHELL'];
        if (shellEnv) {
            const base = (_a = shellEnv.split(/[/\\]/).pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase().replace(/\.exe$/, '');
            if (base === 'bash')
                return 'bash';
            if (base === 'zsh')
                return 'zsh';
            if (base === 'fish')
                return 'fish';
            if (base === 'sh')
                return 'sh';
        }
        // Only reach here on Windows with no Unix shell signals present — assume PowerShell.
        if (os.platform() === 'win32')
            return 'powershell';
        return 'bash';
    }
    buildSnippet(shell, sessionId) {
        switch (shell) {
            case 'bash':
            case 'zsh':
            case 'sh':
                return `export ${exports.CODIAC_SESSION_ID_VAR}="${sessionId}"`;
            case 'fish':
                return `set -x ${exports.CODIAC_SESSION_ID_VAR} "${sessionId}"`;
            case 'powershell':
                return `$env:${exports.CODIAC_SESSION_ID_VAR} = "${sessionId}"`;
        }
    }
}
exports.default = ShellInit;
ShellInit.description = 'Emits a shell snippet that establishes a stable session ID for this terminal instance. ' +
    'Add `eval "$(cod shell init)"` to your shell profile (~/.bashrc, ~/.zshrc, PowerShell $PROFILE, etc.) ' +
    'to enable per-console tenant/enterprise context isolation.';
ShellInit.examples = [
    {
        description: 'Emit the init snippet for the current shell (auto-detected).',
        command: '<%= config.bin %> <%= command.id %>',
    },
    {
        description: 'Emit the init snippet for bash/zsh. Add to ~/.bashrc or ~/.zshrc.',
        command: 'eval "$(<%= config.bin %> <%= command.id %> --shell bash)"',
    },
    {
        description: 'Emit the init snippet for fish. Add to ~/.config/fish/config.fish.',
        command: '<%= config.bin %> <%= command.id %> --shell fish | source',
    },
    {
        description: 'Emit the init snippet for PowerShell. Add to $PROFILE.',
        command: 'Invoke-Expression (<%= config.bin %> <%= command.id %> --shell powershell)',
    },
];
ShellInit.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    shell: core_1.Flags.string({
        char: 's',
        description: 'Shell to emit syntax for (bash, zsh, sh, fish, powershell). Auto-detected when omitted.',
        options: ['bash', 'zsh', 'sh', 'fish', 'powershell'],
    }),
};
ShellInit.args = {};
//# sourceMappingURL=init.js.map