"""
Transformation logic from Cohere's /v1/rerank format to Jina AI's  `/v1/rerank` format.

Why separate file? Make it easy to see how transformation works

Docs - https://jina.ai/reranker
"""

from collections.abc import Mapping
from typing import Any, Final

from httpx import URL, Response

from litellm._uuid import uuid
from litellm.llms.base_llm.chat.transformation import LiteLLMLoggingObj
from litellm.llms.base_llm.rerank.transformation import BaseRerankConfig
from litellm.types.rerank import (
    OptionalRerankParams,
    RerankBilledUnits,
    RerankResponse,
    RerankResponseMeta,
    RerankTokens,
)
from litellm.types.utils import ModelInfo


class JinaAIRerankConfig(BaseRerankConfig):
    def get_supported_cohere_rerank_params(self, model: str) -> list:
        return [
            "query",
            "top_n",
            "documents",
            "return_documents",
        ]

    def map_cohere_rerank_params(
        self,
        non_default_params: dict,
        model: str,
        drop_params: bool,
        query: str,
        documents: list[str | dict[str, Any]],
        custom_llm_provider: str | None = None,
        top_n: int | None = None,
        rank_fields: list[str] | None = None,
        return_documents: bool | None = True,
        max_chunks_per_doc: int | None = None,
        max_tokens_per_doc: int | None = None,
        instruction: str | None = None,
    ) -> dict:
        optional_params: Final = {}
        supported_params: Final = self.get_supported_cohere_rerank_params(model)
        for k, v in non_default_params.items():
            if k in supported_params:
                optional_params[k] = v
        return dict(
            OptionalRerankParams(
                **optional_params,
            )
        )

    def get_complete_url(
        self,
        api_base: str | None,
        model: str,
        optional_params: dict | None = None,
    ) -> str:
        base_path: Final = "/v1/rerank"

        if api_base is None:
            return "https://api.jina.ai/v1/rerank"
        base: Final = URL(api_base)
        # Reconstruct URL with cleaned path
        cleaned_base: Final = str(base.copy_with(path=base_path))

        return cleaned_base

    def transform_rerank_request(
        self,
        model: str,
        optional_rerank_params: dict,
        headers: dict,
        litellm_params: dict | None = None,
    ) -> dict:
        return {"model": model, **optional_rerank_params}

    def transform_rerank_response(
        self,
        model: str,
        raw_response: Response,
        model_response: RerankResponse,
        logging_obj: LiteLLMLoggingObj,
        api_key: str | None = None,
        request_data: dict = {},
        optional_params: dict = {},
        litellm_params: dict = {},
    ) -> RerankResponse:
        if raw_response.status_code != 200:
            raise Exception(raw_response.text)

        logging_obj.post_call(original_response=raw_response.text)

        _json_response: Final = raw_response.json()

        _billed_units: Final = RerankBilledUnits(**_json_response.get("usage", {}))
        _tokens: Final = RerankTokens(**_json_response.get("usage", {}))
        rerank_meta: Final = RerankResponseMeta(billed_units=_billed_units, tokens=_tokens)

        _results: Final[list[dict] | None] = _json_response.get("results")

        if _results is None:
            raise ValueError(f"No results found in the response={_json_response}")

        # Transform Jina AI's response format to match LiteLLM's expected format
        # Jina AI returns: {"index": 0, "relevance_score": 0.72, "document": "hello"}
        # LiteLLM expects: {"index": 0, "relevance_score": 0.72, "document": {"text": "hello"}}
        transformed_results: Final = []
        for result in _results:
            transformed_result = {
                "index": result["index"],
                "relevance_score": result["relevance_score"],
            }
            # Convert document from string to dict format if it exists
            if "document" in result and isinstance(result["document"], str):
                transformed_result["document"] = {"text": result["document"]}
            elif "document" in result:
                # If it's already a dict, keep it as is
                transformed_result["document"] = result["document"]
            transformed_results.append(transformed_result)

        return RerankResponse(
            id=_json_response.get("id") or str(uuid.uuid4()),
            results=transformed_results,
            meta=rerank_meta,
        )  # Return response

    def validate_environment(
        self,
        headers: dict,
        model: str,
        api_key: str | None = None,
        optional_params: dict | None = None,
        litellm_params: Mapping[str, object] | None = None,
    ) -> dict:
        if api_key is None:
            raise ValueError("api_key is required. Set via `api_key` parameter or `JINA_API_KEY` environment variable.")
        return {
            "accept": "application/json",
            "content-type": "application/json",
            "authorization": f"Bearer {api_key}",
        }

    def calculate_rerank_cost(
        self,
        model: str,
        custom_llm_provider: str | None = None,
        billed_units: RerankBilledUnits | None = None,
        model_info: ModelInfo | None = None,
    ) -> tuple[float, float]:
        """
        Jina AI reranker is priced at $0.000000018 per token.
        """
        if (
            model_info is None
            or "input_cost_per_token" not in model_info
            or model_info["input_cost_per_token"] is None
            or billed_units is None
        ):
            return 0.0, 0.0

        total_tokens: Final = billed_units.get("total_tokens")
        if total_tokens is None:
            return 0.0, 0.0

        input_cost: Final = model_info["input_cost_per_token"] * total_tokens
        return input_cost, 0.0
