import os
import subprocess
from provider import star_provider


class FliteProvider(star_provider):
    def get_voices(self):
        voices = {}

        # -------------------------------------------
        # 1. Built-in voices from `flite -lv`
        # -------------------------------------------
        try:
            result = subprocess.run(
                ["flite", "-lv"],
                capture_output=True,
                text=True,
                check=True
            )

            output = result.stdout.strip()
            prefix = "Voices available:"

            if output.lower().startswith(prefix.lower()):
                output = output[len(prefix):].strip()

            for v in output.split():
                voices[v] = {
                    "full_name": v  # built-ins use their name directly
                }

        except Exception as e:
            print(f"Warning: could not query built-in flite voices: {e}")

        # -------------------------------------------
        # 2. External .flitevox voices
        # -------------------------------------------
        search_paths = [os.getcwd()]

        if "FLITE_VOX_PATH" in os.environ:
            search_paths.append(os.environ["FLITE_VOX_PATH"])

        for path in search_paths:
            if not os.path.isdir(path):
                continue

            for filename in os.listdir(path):
                if filename.lower().endswith(".flitevox"):
                    display_name = os.path.splitext(filename)[0]

                    # Avoid overwriting built-in voice if names collide
                    if display_name not in voices:
                        voices[display_name] = {
                            "full_name": filename  # keep extension for execution
                        }

        return voices


FliteProvider(
    "flite",
    synthesis_process=[
        "flite",
        "-voice", "{voice}",
        "-t", "{text}",
        "-o", "{filename}"
    ],
    synthesis_audio_extension="wav"
)