import os
import httpx
from .base_tts_service import BaseTTSService

class CustomTTSService(BaseTTSService):
    """
    TTS Service implementation that calls our self-hosted, custom FastAPI model.
    """
    def __init__(self):
        # Read the URL of our FastAPI server from an environment variable
        self.api_url = os.getenv("CUSTOM_TTS_URL", "http://localhost:5000/synthesize")
        self._is_available = bool(self.api_url)
        print(f"Custom TTS Service initialized. API URL: {self.api_url}")

    def is_available(self) -> bool:
        return self._is_available

    def generate_speech(self, text: str, language: str = "en") -> bytes:
        """
        Makes an HTTP POST request to the custom TTS FastAPI server.
        """
        if not self.is_available():
            raise ConnectionError("Custom TTS service is not configured or available.")

        try:
            # Use httpx for modern, async-friendly requests
            with httpx.Client() as client:
                response = client.post(
                    self.api_url,
                    json={"text": text, "language": language},
                    timeout=120.0  # Set a generous timeout for long text
                )
                
                # Raise an exception for bad status codes (4xx or 5xx)
                response.raise_for_status()
                
                # The raw audio data is in the response content
                audio_bytes = response.content
                print(f"Successfully received audio from custom TTS service for language '{language}'.")
                return audio_bytes

        except httpx.RequestError as e:
            print(f"Error calling custom TTS service: {e}")
            # Re-raise as a standard ConnectionError
            raise ConnectionError(f"Failed to connect to custom TTS service at {self.api_url}") from e