import os
import httpx
from typing import List, Dict
from .base_tts_service import BaseTTSService

class CustomTTSService(BaseTTSService):
    """
    TTS Service implementation that calls our self-hosted, custom FastAPI model.
    """
    def __init__(self):
        base_url = os.getenv("CUSTOM_TTS_URL", "http://localhost:5000")

        self.api_url = f"{base_url}/generate_audio"
        
        self._is_available = bool(base_url)
        print(f"Custom TTS Service initialized. Target Endpoint: {self.api_url}")

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

    def generate_speech(self, text: str) -> bytes:
        """
        Makes an HTTP POST request to the custom TTS FastAPI server.
        Expected API Payload: {"text": "some text"}
        Returns: Binary audio data (WAV)
        """
        payload = {
            "text": text
        }
        
        try:
            with httpx.Client(timeout=60.0) as client:
                response = client.post(self.api_url, json=payload)
                
                # Check if the request was successful (2xx status codes)
                response.raise_for_status()
                
                # Return the binary content (the WAV file)
                return response.content
                
        except httpx.HTTPStatusError as exc:
            print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")
            raise exc
        except httpx.RequestError as exc:
            print(f"An error occurred while requesting {exc.request.url!r}: {exc}")
            raise exc
        except Exception as e:
            print(f"Unexpected error in CustomTTSService: {e}")
            raise e