import path from 'node:path';
import { findCodexBinary } from '../codex-adapter.js';
import { compareSemverLike, parseCodexVersionText } from '../codex-compat/codex-version-policy.js';
import { nowIso, runProcess, writeJsonAtomic } from '../fsx.js';
export async function detectCodex0138Capability(input = {}) {
    const fake = process.env.SKS_CODEX_0138_FAKE === '1';
    const codexBin = fake
        ? input.codexBin || process.env.CODEX_BIN || 'codex'
        : input.codexBin || process.env.CODEX_BIN || await findCodexBinary();
    const versionText = fake
        ? String(process.env.SKS_CODEX_VERSION_FAKE || 'codex-cli 0.138.0')
        : await readCodexVersionText(codexBin);
    const parsed = parseCodexVersion(versionText);
    const atLeast138 = Boolean(parsed && semverGte(parsed, '0.138.0'));
    const probeMode = process.env.SKS_CODEX_0138_PROBE === '1' ? 'feature-probe' : 'version-only';
    const featureProbeResults = probeMode === 'feature-probe'
        ? await probeCodex0138Features(codexBin, { fake })
        : {
            plugin_json: 'skipped',
            app_handoff_platform: 'skipped',
            image_path_exposure_contract: 'sks-enforced'
        };
    const pluginJsonOk = atLeast138 && (probeMode === 'version-only' || featureProbeResults.plugin_json !== 'failed');
    const appHandoffOk = atLeast138 && (probeMode === 'version-only' || featureProbeResults.app_handoff_platform === 'passed');
    const blockers = [
        ...(!codexBin ? ['codex_cli_missing'] : []),
        ...(atLeast138 ? [] : ['codex_0_138_required_for_app_plugin_features']),
        ...(probeMode === 'feature-probe' && featureProbeResults.plugin_json === 'failed' ? ['codex_plugin_json_probe_failed'] : [])
    ];
    return {
        schema: 'sks.codex-0138-capability.v1',
        ok: atLeast138 && blockers.length === 0,
        probe_mode: probeMode,
        codex_bin: codexBin || null,
        version_text: versionText || null,
        parsed_version: parsed,
        supports_app_handoff: appHandoffOk,
        supports_plugin_json: pluginJsonOk,
        supports_image_path_exposure: atLeast138,
        supports_model_defined_efforts: atLeast138,
        supports_app_server_token_usage: atLeast138,
        supports_v2_pat_auth: atLeast138,
        supports_oauth_mcp_prerefresh: atLeast138,
        feature_probe_results: featureProbeResults,
        blockers
    };
}
export async function writeCodex0138CapabilityArtifacts(root, input = {}) {
    const capability = await detectCodex0138Capability({ codexBin: input.codexBin || null });
    const report = { ...capability, generated_at: nowIso() };
    const rootArtifact = path.join(root, '.sneakoscope', 'codex-0138-capability.json');
    await writeJsonAtomic(rootArtifact, report);
    let missionArtifact = null;
    if (input.missionId) {
        missionArtifact = path.join(root, '.sneakoscope', 'missions', input.missionId, 'codex-0138-capability.json');
        await writeJsonAtomic(missionArtifact, report);
    }
    return { report, root_artifact: rootArtifact, mission_artifact: missionArtifact };
}
export function parseCodexVersion(text) {
    return parseCodexVersionText(text);
}
export function semverGte(actual, minimum) {
    return compareSemverLike(actual, minimum) >= 0;
}
async function readCodexVersionText(codexBin) {
    if (!codexBin)
        return null;
    const result = await runProcess(codexBin, ['--version'], { timeoutMs: 10_000, maxOutputBytes: 16 * 1024 }).catch((err) => ({
        code: 1,
        stdout: '',
        stderr: err?.message || String(err)
    }));
    const text = `${result.stdout || ''}${result.stderr || ''}`.trim();
    return result.code === 0 ? text : text || null;
}
async function probeCodex0138Features(codexBin, opts = {}) {
    if (opts.fake) {
        return {
            plugin_json: process.env.SKS_CODEX_0138_FAKE_PLUGIN_JSON_FAIL === '1' ? 'failed' : 'passed',
            app_handoff_platform: process.platform === 'darwin' || process.platform === 'win32' ? 'passed' : 'failed',
            image_path_exposure_contract: 'sks-enforced'
        };
    }
    const timeoutMs = Math.max(1, Number(process.env.SKS_CODEX_0138_PROBE_TIMEOUT_MS || 3000) || 3000);
    const platformSupported = process.platform === 'darwin' || process.platform === 'win32';
    if (!codexBin) {
        return {
            plugin_json: 'failed',
            app_handoff_platform: platformSupported ? 'skipped' : 'failed',
            image_path_exposure_contract: 'sks-enforced'
        };
    }
    const list = await runProcess(codexBin, ['plugin', 'list', '--json'], { timeoutMs, maxOutputBytes: 64 * 1024 }).catch(() => ({ code: 1 }));
    const detailHelp = await runProcess(codexBin, ['plugin', 'detail', '--help'], { timeoutMs, maxOutputBytes: 64 * 1024 }).catch(() => ({ code: 1 }));
    return {
        plugin_json: list.code === 0 && detailHelp.code === 0 ? 'passed' : 'failed',
        app_handoff_platform: platformSupported ? 'passed' : 'failed',
        image_path_exposure_contract: 'sks-enforced'
    };
}
//# sourceMappingURL=codex-0138-capability.js.map