'use strict';

const ANTHROPIC_SAMPLING_PARAMS = Object.freeze([
  'temperature',
  'top_p',
  'topP',
  'top_k',
  'topK',
]);

function normalizeModelId(model) {
  if (!model) return '';
  let id = typeof model === 'string' ? model : String(model.id || model.model || model.name || '');
  id = id.trim();
  id = id.replace(/^@anthropic\//i, '');
  id = id.replace(/^anthropic[.:/]/i, '');
  id = id.replace(/@(default|[a-z0-9_.-]+)$/i, '');
  return id.toLowerCase();
}

function anthropicModelRejectsSamplingParams(model) {
  const id = normalizeModelId(model);
  const match = id.match(/^claude-(?:opus|sonnet|haiku)-4-(\d+)(?:-|$)/);
  return Boolean(match && Number(match[1]) >= 7);
}

function stripParams(request, keys, reason) {
  const stripped = [];
  for (const key of keys) {
    if (Object.prototype.hasOwnProperty.call(request, key) && request[key] !== undefined) {
      delete request[key];
      stripped.push(key);
    }
  }
  return stripped.length > 0 ? [{ reason, keys: stripped }] : [];
}

function stripAnthropicUnsupportedParams(request = {}, { model = request.model, force = false } = {}) {
  const next = { ...request };
  const shouldStrip = force || anthropicModelRejectsSamplingParams(model);
  if (!shouldStrip) return { request: next, warnings: [] };
  const warnings = stripParams(
    next,
    ANTHROPIC_SAMPLING_PARAMS,
    `Removed Anthropic sampling parameter(s) unsupported by ${normalizeModelId(model) || 'selected model'}.`
  );
  return { request: next, warnings };
}

function isAnthropicSamplingParamError(error) {
  const text = [
    error?.message,
    error?.responseBody,
    error?.body,
    JSON.stringify(error?.error || ''),
  ].filter(Boolean).join('\n').toLowerCase();
  return /(?:temperature|top[_ ]?p|top[_ ]?k).*(?:deprecated|not supported|unsupported|invalid)/i.test(text)
    || /(?:deprecated|not supported|unsupported|invalid).*(?:temperature|top[_ ]?p|top[_ ]?k)/i.test(text);
}

module.exports = {
  ANTHROPIC_SAMPLING_PARAMS,
  anthropicModelRejectsSamplingParams,
  isAnthropicSamplingParamError,
  normalizeModelId,
  stripAnthropicUnsupportedParams,
};
