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):
        # Read the URL of our FastAPI server from an environment variable
        base_url = os.getenv("CUSTOM_TTS_URL", "http://localhost:5000")
        self.api_url = f"{base_url}/synthesize"
        self.sequence_api_url = f"{base_url}/synthesize_sequence" 
        self._is_available = bool(base_url)
        print(f"Custom TTS Service initialized. Base URL: {base_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

    def generate_speech_from_sequence(self, segments: List[Dict[str, str]]) -> bytes:
        """Makes a single POST request with the list of segments."""
        if not self.is_available():
            raise ConnectionError("Custom TTS service is not configured.")

        try:
            with httpx.Client() as client:
                print(f"Sending sequence of {len(segments)} segments to custom TTS service.")
                response = client.post(
                    self.sequence_api_url,
                    json={"segments": segments}, # Send the list directly
                    timeout=300.0  # Longer timeout for sequence processing
                )
                response.raise_for_status()
                audio_bytes = response.content
                print("Successfully received stitched audio from custom TTS service.")
                return audio_bytes
        except httpx.RequestError as e:
            raise ConnectionError(f"Failed to connect to custom TTS at {self.sequence_api_url}") from e