'use strict';

const path = require('path');

function isCodexCommand(cmd) {
  const first = String(cmd || '').trim().split(/\s+/)[0] || '';
  return path.basename(first).toLowerCase() === 'codex';
}

/**
 * Strip env-injected OpenAI auth before spawning an interactive Codex CLI.
 *
 * CTM itself may have OPENAI_API_KEY/OPENAI_BASE_URL in its process env for
 * provider setup and background jobs. Interactive Codex sessions should use
 * Codex's own login/config state unless the operator explicitly opts into env
 * inheritance; otherwise a stale API-key route can override the user's normal
 * ChatGPT/Codex auth path and select a different transport/billing mode.
 */
function sanitizeOpenAiAuth(env, cmd) {
  if (!env || typeof env !== 'object') return env;
  if (!isCodexCommand(cmd)) return env;
  if (String(process.env.CTM_KEEP_OPENAI_ENV_FOR_CODEX || '').trim()) return env;
  delete env.OPENAI_API_KEY;
  delete env.OPENAI_BASE_URL;
  return env;
}

module.exports = {
  isCodexCommand,
  sanitizeOpenAiAuth,
};
