"""
author: Yagnik Poshiya
organization: Webbrains Technologies Private Limited

Customers type their own model names, so a request built for one model family can be
rejected by another (reasoning models refuse `temperature`, newer OpenAI models want
`max_completion_tokens`, some Claude models refuse `temperature` together with `top_p`).
`adjust_rejected_params` turns a 400 error message into the smallest change that lets
the same request be retried, or None when the error is about something else.
"""

from __future__ import annotations

from typing import Any

MAX_COMPAT_RETRIES = 3


def adjust_rejected_params(kwargs: dict[str, Any], error_message: str) -> dict[str, Any] | None:
    msg = (error_message or "").lower()
    out = dict(kwargs)

    if "max_tokens" in out and "max_completion_tokens" in msg:
        out["max_completion_tokens"] = out.pop("max_tokens")
        return out
    # Drop the most specific sampling knob the provider named; keep temperature last.
    for param in ("top_k", "top_p", "temperature"):
        if param in out and param in msg:
            out.pop(param)
            if param == "top_p":
                out.pop("top_k", None)
            return out
    return None
