import requests

class ChatCompletions:
    def __init__(self, client):
        self._client = client

    def create(self, messages: list, model: str = "arcee-ai/trinity-mini-20251201", pretty: bool = False):
        """
        Wywołuje chat completion w SynteriaAI.
        :param messages: lista słowników [{"role": "user", "content": "..."}]
        :param model: model do użycia
        :param pretty: czy ładnie wydrukować odpowiedź w konsoli
        """
        url = f"{self._client.base_url}/v1/chat/completions.php"

        payload = {
            "api_key": self._client.api_key,
            "messages": messages,
            "model": model  # dynamiczny model
        }

        try:
            response = requests.post(url, json=payload, timeout=120)
        except requests.exceptions.RequestException as e:
            raise Exception(f"❌ Błąd połączenia z API: {e}")

        if response.status_code != 200:
            raise Exception(f"API Error {response.status_code}: {response.text}")

        data = response.json()

        # Obsługa openrouter_response jeśli istnieje
        if "openrouter_response" in data:
            data = data["openrouter_response"]

        # Usuń reasoning i reasoning_details
        for choice in data.get("choices", []):
            message = choice.get("message", {})
            message.pop("reasoning", None)
            message.pop("reasoning_details", None)

        if pretty:
            self._pretty_print(data, model)

        return data

    # ===============================
    # CLEAN RESPONSE
    # ===============================
    def _clean_content(self, content: str) -> str:
        lines = content.splitlines()
        cleaned = []
        for line in lines:
            if "translation" in line.lower():
                continue
            if line.strip().startswith("("):
                continue
            cleaned.append(line.replace("  ", " ").strip())
        return "\n".join(cleaned).strip()

    # ===============================
    # PRETTY PRINT Z FORMATOWANIEM MARKDOWN
    # ===============================
    def _pretty_print(self, data: dict, model: str):
        choices = data.get("choices")
        if not choices or len(choices) == 0:
            print("❌ Brak odpowiedzi od API lub błędny format danych:")
            print(data)
            return

        content = choices[0].get("message", {}).get("content", "")
        content = self._clean_content(content)
        tokens = data.get("usage", {}).get("total_tokens", "unknown")
        masked_key = self._client.api_key[:6] + "****" + self._client.api_key[-4:]

        print("\n==============================")
        print("🔑  SynteriaAI Chat Response")
        print("==============================")
        print(f"API KEY 🔑 : {masked_key}")
        print(f"Model 🤖   : {model}")  # teraz dokładnie użyty model
        print(f"Tokens 📊  : {tokens}")
        print("\n💬 Odpowiedź:\n")

        for line in content.splitlines():
            line = line.strip()
            if line.startswith("**") and line.endswith("**"):
                print(f"\033[1m{line}\033[0m")
            elif line.startswith("*"):
                print(f"  {line}")
            else:
                print(line)

        print("==============================\n")