"""Pipeshift LLMs"""

import logging
import warnings
from typing import Any, Dict, List, Optional

import requests
from aiohttp import ClientSession
from langchain_core.callbacks import (
    AsyncCallbackManagerForLLMRun,
    CallbackManagerForLLMRun,
)
from langchain_core.language_models.llms import LLM
from langchain_core.utils import secret_from_env
from pydantic import ConfigDict, Field, SecretStr, model_validator

logger = logging.getLogger(__name__)

DEFAULT_MODEL = "meta-llama/Meta-Llama-3.1-8B-Instruct"
BASE_URL = "https://api.pipeshift.com/api/v0/completions"

class Pipeshift(LLM):
    """LLM models from `Pipeshift`.

    To use, you'll need an API key which you can find here:
    https://dashboard.pipeshift.com. This can be passed in as init param
    ``pipeshift_api_key`` or set as environment variable ``PIPESHIFT_API_KEY``.

    Pipeshift AI API reference: refer pipehsift dashboard

    Example:
        .. code-block:: python

            from langchain_pipeshift import Pipeshift

            model = Pipeshift(model_name="meta-llama/Meta-Llama-3-8B-Instruct")
    """

    base_url: str = BASE_URL
    """Base completions API URL."""
    pipeshift_api_key: SecretStr = Field(
        alias="api_key",
        default_factory=secret_from_env("PIPESHIFT_API_KEY"),
    )
    """Pipeshift AI API key.

    Automatically read from env variable `PIPESHIFT_API_KEY` if not provided.
    """
    model: str
    """Model name. 
    Available models will be listed in the models section of pipeshift dashboard : https://dashbaord.pipeshift.com/models"""
    temperature: Optional[float] = None
    """Model temperature."""
    top_p: Optional[float] = None
    """Used to dynamically adjust the number of choices for each predicted token based
        on the cumulative probabilities. A value of 1 will always yield the same
        output. A temperature less than 1 favors more correctness and is appropriate
        for question answering or summarization. A value greater than 1 introduces more
        randomness in the output.
    """
    top_k: Optional[int] = None
    """Used to limit the number of choices for the next predicted word or token. It
        specifies the maximum number of tokens to consider at each step, based on their
        probability of occurrence. This technique helps to speed up the generation
        process and can improve the quality of the generated text by focusing on the
        most likely options.
    """
    max_tokens: Optional[int] = None
    """The maximum number of tokens to generate."""
    repetition_penalty: Optional[float] = None
    """A number that controls the diversity of generated text by reducing the
        likelihood of repeated sequences. Higher values decrease repetition.
    """
    logprobs: Optional[int] = None
    """An integer that specifies how many top token log probabilities are included in
        the response for each token generation step.
    """

    model_config = ConfigDict(
        extra="forbid",
        populate_by_name=True,
    )

    @model_validator(mode="before")
    @classmethod
    def validate_environment(cls, values: Dict) -> Any:
        """Validate if model exists."""
        if values.get("model") is None:
            warnings.warn(
                "'model' is a required argument."
            )
            values["model"] = DEFAULT_MODEL  # Default Value
        """Validate max_tokens exists."""
        if values.get("max_tokens") is None:
            warnings.warn(
                "'max_tokens' is a required argument."
                "The default value is being set to 512."
                "Consider setting this value, when initializing LLM"
            )
            values["max_tokens"] = 512  # Default Value
        return values

    @property
    def _llm_type(self) -> str:
        """Return type of model."""
        return "pipeshift"

    def _format_output(self, output: dict) -> str:
        """Format model response."""
        return output["choices"][0]["text"]

    @property
    def default_params(self) -> Dict[str, Any]:
        """Pipeshift model default parameters."""
        return {
            "model": self.model,
            "temperature": self.temperature,
            "top_p": self.top_p,
            "top_k": self.top_k,
            "max_tokens": self.max_tokens,
            "repetition_penalty": self.repetition_penalty,
        }

    def _call(
        self,
        prompt: str,
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> str:
        """Calling Pipeshift's text generation endpoint.

        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.
            run_manager: The CallbackManager for LLM run, it's not used at the moment.
            kwargs: Additional parameters to pass to the model.

        Returns:
            The string generated by the model..
        """
        headers = {
            "Authorization": f"Bearer {self.pipeshift_api_key.get_secret_value()}",
            "Content-Type": "application/json",
        }
        stop_to_use = stop[0] if stop and len(stop) == 1 else stop
        payload: Dict[str, Any] = {
            **self.default_params,
            "prompt": prompt,
            "stop": stop_to_use,
            **kwargs,
        }

        payload = {k: v for k, v in payload.items() if v is not None}
        # filter None values to not pass them to the http payload
        response = requests.post(url=self.base_url, json=payload, headers=headers)

        if response.status_code >= 500:
            raise Exception(f"Pipeshift Server: Error {response.status_code}")
        elif response.status_code >= 400:
            raise ValueError(f"Pipeshift received an invalid payload: {response.text}")
        elif response.status_code != 200:
            raise Exception(
                f"Pipeshift returned an unexpected response with status "
                f"{response.status_code}: {response.text}"
            )

        data = response.json()

        output = self._format_output(data)

        return output

    async def _acall(
        self,
        prompt: str,
        stop: Optional[List[str]] = None,
        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> str:
        """Calling Pipeshift model to get predictions based on the prompt.

        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.
            run_manager: The CallbackManager for LLM run, it's not used at the moment.
            kwargs: Additional parameters to pass to the model.

        Returns:
            The string generated by the model.
        """
        headers = {
            "Authorization": f"Bearer {self.pipeshift_api_key.get_secret_value()}",
            "Content-Type": "application/json",
        }
        stop_to_use = stop[0] if stop and len(stop) == 1 else stop
        payload: Dict[str, Any] = {
            **self.default_params,
            "prompt": prompt,
            "stop": stop_to_use,
            **kwargs,
        }

        payload = {k: v for k, v in payload.items() if v is not None}
        # filter None values to not pass them to the http payload
        async with ClientSession() as session:
            async with session.post(
                self.base_url, json=payload, headers=headers
            ) as response:
                if response.status >= 500:
                    raise Exception(f"Pipeshift Server: Error {response.status}")
                elif response.status >= 400:
                    raise ValueError(
                        f"Pipeshift received an invalid payload: {response.text}"
                    )
                elif response.status != 200:
                    raise Exception(
                        f"Pipeshift returned an unexpected response with status "
                        f"{response.status}: {response.text}"
                    )

                response_json = await response.json()

                output = self._format_output(response_json)
                return output
