"""Generate WAV speech from a UTF-8 text file. Python standard library only."""
import argparse
import json
import os
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--text-file", type=Path, required=True)
parser.add_argument("--output", type=Path, default=Path("speech.wav"))
args = parser.parse_args()
text = args.text_file.read_text(encoding="utf-8").strip()
if not text:
    parser.error("The text file is empty")
key = os.environ.get("SAWALNI_API_KEY")
if not key:
    parser.error("Set SAWALNI_API_KEY in your terminal")
base = os.environ.get("SAWALNI_BASE_URL", "https://api.sawalni.com/v1").rstrip("/")
request = Request(base + "/audio/speech", data=json.dumps({
    "model": "asat", "input": text, "voice": "male-1",
    "response_format": "wav", "stream": False
}).encode("utf-8"), headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
try:
    with urlopen(request, timeout=120) as response:
        if not response.headers.get("Content-Type", "").startswith("audio/"):
            raise SystemExit("The API did not return audio")
        audio = response.read()
        if not audio.startswith(b"RIFF") or audio[8:12] != b"WAVE":
            raise SystemExit("The API did not return a WAV file")
        args.output.write_bytes(audio)
except HTTPError as error:
    raise SystemExit(f"API request failed with HTTP {error.code}. Check access, input, credits and rate limits.") from None
except URLError:
    raise SystemExit("Could not connect to the API. No automatic retry was made.") from None
print(f"Saved {args.output}")
