#!/usr/bin/env python3
"""Call the TTSMint reader API from a trusted server-side environment."""

import json
import os
import sys
import tempfile
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


API_URL = "https://ttsmint.com/v1/audio/speech"
USER_AGENT = "TTSMintPythonExample/1.0"
REQUEST_FILE = Path(__file__).with_name("tts-reader-request.json")


def show_error(status, body):
    try:
        payload = json.loads(body.decode("utf-8"))
        error = payload.get("error", {}) if isinstance(payload, dict) else {}
        if isinstance(error, dict):
            print("HTTP {}: {} ({})".format(status, error.get("message", "Request failed"), error.get("code", "UNKNOWN_ERROR")), file=sys.stderr)
            return
    except (UnicodeDecodeError, json.JSONDecodeError, AttributeError):
        pass
    print("HTTP {}: the server did not return an audio response".format(status), file=sys.stderr)


def download_audio(output_path, api_key, opener=None):
    """Return True after an MP3 is atomically saved; otherwise keep old output."""
    if not api_key:
        print("Set TTSMINT_API_KEY in the server environment first.", file=sys.stderr)
        return False

    request_body = REQUEST_FILE.read_bytes()
    request = Request(
        API_URL,
        data=request_body,
        headers={
            "Authorization": "Bearer " + api_key,
            "Content-Type": "application/json",
            "Accept": "audio/mpeg",
            "User-Agent": USER_AGENT,
        },
        method="POST",
    )
    send = opener or urlopen
    try:
        response = send(request, timeout=60)
    except HTTPError as error:
        show_error(error.code, error.read())
        return False
    except URLError as error:
        print("Network request failed: {}".format(error.reason), file=sys.stderr)
        return False

    with response:
        content_type = response.headers.get_content_type()
        if response.status != 200 or content_type != "audio/mpeg":
            show_error(response.status, response.read())
            return False
        audio = response.read()

    if not audio:
        print("The server returned an empty audio response; output was left unchanged.", file=sys.stderr)
        return False

    target = Path(output_path)
    target.parent.mkdir(parents=True, exist_ok=True)
    temporary_path = None
    try:
        with tempfile.NamedTemporaryFile(dir=str(target.parent), prefix="." + target.name + ".", suffix=".tmp", delete=False) as temporary:
            temporary_path = temporary.name
            temporary.write(audio)
            temporary.flush()
            os.fsync(temporary.fileno())
        os.replace(temporary_path, target)
        temporary_path = None
    finally:
        if temporary_path and os.path.exists(temporary_path):
            os.unlink(temporary_path)
    print("Saved MP3 to {}".format(target))
    return True


def main(argv=None):
    arguments = list(argv if argv is not None else sys.argv[1:])
    output_path = arguments[0] if arguments else "speech.mp3"
    return 0 if download_audio(output_path, os.environ.get("TTSMINT_API_KEY")) else 1


if __name__ == "__main__":
    raise SystemExit(main())
