"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.codexBinarySupportsConfigOverrides = exports.getCodexBinaryInfo = exports.detectCodexCli = exports.readCodexVersion = void 0;
const fs = __importStar(require("fs"));
const childProcess = __importStar(require("child_process"));
const helpers_1 = require("../utils/helpers");
const shell_executor_1 = require("../utils/shell-executor");
const CODEX_CONFIG_OVERRIDE_FEATURE = 'config-overrides';
const CODEX_CONFIG_OVERRIDE_PROBE_ARGS = ['-c', 'model="gpt-5"', '--version'];
function buildWindowsCodexCandidates(matches) {
    const shellCandidates = matches.filter((entry) => /\.(exe|cmd|bat|ps1)$/i.test(entry));
    const bareCandidates = matches.filter((entry) => !/\.(exe|cmd|bat|ps1)$/i.test(entry));
    const prioritized = shellCandidates.map((entry) => {
        if (!/\.ps1$/i.test(entry)) {
            return entry;
        }
        for (const preferredExtension of ['.cmd', '.bat', '.exe']) {
            const siblingCandidate = entry.replace(/\.ps1$/i, preferredExtension);
            try {
                if (fs.statSync(siblingCandidate).isFile()) {
                    return siblingCandidate;
                }
            }
            catch {
                // Ignore missing sibling wrappers and keep the original PowerShell path.
            }
        }
        return entry;
    });
    return [...new Set([...prioritized, ...bareCandidates])];
}
function runCodexProbe(codexPath, args) {
    const isWindows = process.platform === 'win32';
    const isPowerShellScript = isWindows && /\.ps1$/i.test(codexPath);
    const needsShell = isWindows && /\.(cmd|bat)$/i.test(codexPath);
    try {
        if (isPowerShellScript) {
            return childProcess.execFileSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', codexPath, ...args], {
                encoding: 'utf8',
                stdio: ['ignore', 'pipe', 'ignore'],
                timeout: 5000,
                windowsHide: true,
            });
        }
        if (needsShell) {
            const cmdString = [codexPath, ...args].map(shell_executor_1.escapeShellArg).join(' ');
            const result = childProcess.spawnSync(cmdString, {
                encoding: 'utf8',
                stdio: ['ignore', 'pipe', 'ignore'],
                timeout: 5000,
                windowsHide: true,
                shell: (0, shell_executor_1.getWindowsEscapedCommandShell)(),
            });
            return result.status === 0 ? result.stdout : undefined;
        }
        return childProcess.execFileSync(codexPath, args, {
            encoding: 'utf8',
            stdio: ['ignore', 'pipe', 'ignore'],
            timeout: 5000,
        });
    }
    catch {
        return undefined;
    }
}
function readCodexVersion(codexPath) {
    return runCodexProbe(codexPath, ['--version'])?.trim();
}
exports.readCodexVersion = readCodexVersion;
function codexHelpAdvertisesConfigOverrides(helpText) {
    if (!helpText) {
        return false;
    }
    return /(^|\n)\s*-c,\s*--config\b/m.test(helpText) || helpText.includes('--config <key=value>');
}
function codexSupportsConfigOverrideProbe(codexPath) {
    return !!runCodexProbe(codexPath, CODEX_CONFIG_OVERRIDE_PROBE_ARGS)?.trim();
}
function detectCodexFeatures(codexPath) {
    if (codexSupportsConfigOverrideProbe(codexPath)) {
        return [CODEX_CONFIG_OVERRIDE_FEATURE];
    }
    const helpText = runCodexProbe(codexPath, ['--help']);
    return codexHelpAdvertisesConfigOverrides(helpText) ? [CODEX_CONFIG_OVERRIDE_FEATURE] : [];
}
function detectCodexCli() {
    if (process.env.CCS_CODEX_PATH) {
        const customPath = (0, helpers_1.expandPath)(process.env.CCS_CODEX_PATH);
        try {
            if (fs.statSync(customPath).isFile()) {
                return customPath;
            }
            console.warn('[!] CCS_CODEX_PATH points to a directory, not a file:', customPath);
            console.warn('    Refusing PATH fallback while CCS_CODEX_PATH is explicitly set.');
            return null;
        }
        catch (err) {
            const error = err;
            if (error.code === 'ENOENT') {
                console.warn('[!] Warning: CCS_CODEX_PATH is set but file not found:', customPath);
            }
            else {
                console.warn(`[!] Warning: CCS_CODEX_PATH is not accessible (${error.code || 'unknown error'}):`, customPath);
            }
            console.warn('    Refusing PATH fallback while CCS_CODEX_PATH is explicitly set.');
            return null;
        }
    }
    const isWindows = process.platform === 'win32';
    try {
        const cmd = isWindows ? 'where.exe codex' : 'which codex';
        const result = childProcess
            .execSync(cmd, {
            encoding: 'utf8',
            stdio: ['ignore', 'pipe', 'ignore'],
            timeout: 5000,
        })
            .trim();
        const matches = result
            .split('\n')
            .map((entry) => entry.trim())
            .filter(Boolean);
        const candidates = isWindows ? buildWindowsCodexCandidates(matches) : matches;
        for (const candidate of candidates) {
            try {
                if (fs.statSync(candidate).isFile()) {
                    return candidate;
                }
            }
            catch {
                // Ignore disappearing PATH candidates.
            }
        }
    }
    catch {
        // codex not in PATH
    }
    return null;
}
exports.detectCodexCli = detectCodexCli;
function getCodexBinaryInfo(options) {
    const codexPath = detectCodexCli();
    if (!codexPath)
        return null;
    const isWindows = process.platform === 'win32';
    return {
        path: codexPath,
        needsShell: isWindows && /\.(cmd|bat|ps1)$/i.test(codexPath),
        version: options?.includeVersion === false ? undefined : readCodexVersion(codexPath),
        features: options?.includeFeatures === false ? undefined : detectCodexFeatures(codexPath),
    };
}
exports.getCodexBinaryInfo = getCodexBinaryInfo;
function codexBinarySupportsConfigOverrides(binaryInfo) {
    if (!binaryInfo) {
        return false;
    }
    if (binaryInfo.features) {
        return binaryInfo.features.includes(CODEX_CONFIG_OVERRIDE_FEATURE);
    }
    return detectCodexFeatures(binaryInfo.path).includes(CODEX_CONFIG_OVERRIDE_FEATURE);
}
exports.codexBinarySupportsConfigOverrides = codexBinarySupportsConfigOverrides;
//# sourceMappingURL=codex-detector.js.map