#!/usr/bin/env python
"""
This module provides the BARTProvider class for enhancing text using the BART (Bidirectional and Auto-Regressive
Transformers) model via HTTP POST requests to a specified AI service endpoint.

The BARTProvider class is initialized using the "JIRA_AI_URL" environment variable to set the endpoint URL. It includes
error handling for HTTP request failures, raising an AiError when necessary.

Key Attributes:
- url (str): The endpoint URL for the BART model.
- headers (dict): Default HTTP request headers set to {"Content-Type": "application/json"}.

Key Methods:
- improve_text(prompt: str, text: str) -> str:
Combines the prompt and text, sends a POST request to the BART model, and returns the improved text. Raises an AiError
if the request fails.
"""

# pylint: disable=too-few-public-methods

import requests

from jira_creator.core.env_fetcher import EnvFetcher
from jira_creator.exceptions.exceptions import AiError
from jira_creator.providers.ai_provider import AIProvider


class BARTProvider(AIProvider):
    """
    BARTProvider class represents a provider for interacting with the BART (Bidirectional and Auto-Regressive
    Transformers) model.

    Attributes:
    - url (str): The URL endpoint to communicate with the BART model, fetched from the environment variable
    "JIRA_AI_URL".
    - headers (dict): A dictionary containing headers for the HTTP request, defaulting to {"Content-Type":
    "application/json"}.

    Methods:
    - improve_text(prompt: str, text: str) -> str:
    Combines the provided prompt and text, sends a POST request to the BART model endpoint with the concatenated text,
    and returns the improved text generated by the model. If the request fails, it raises an AiError with details of
    the failure.
    """

    url: str
    headers: dict[str, str]

    def __init__(self) -> None:
        """
        Initialize the class with a URL and headers for API requests.
        """

        self.url = EnvFetcher.get("JIRA_AI_URL")
        self.headers = {"Content-Type": "application/json"}

    def improve_text(self, prompt: str, text: str) -> str:
        """
        Improve the given text using an API endpoint.

        Arguments:
        - prompt (str): The initial prompt or context for the text improvement.
        - text (str): The text to be improved.

        Return:
        - str: The improved text generated by the API.

        Exceptions:
        - This function may raise exceptions related to the HTTP request or response handling.
        """

        full_prompt: str = f"{prompt}\n\n{text}"
        response: requests.Response = requests.post(
            self.url, headers=self.headers, json={"text": full_prompt}, timeout=30
        )
        if response.status_code == 200:
            return response.json().get("output", "").strip()

        raise AiError(f"BART request failed: {response.status_code} - {response.text}")
