"""Python 3, standard library only. See README.md; new requests use paid quota."""
import json
import os
import sys
import time
import uuid
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError

BASE = 'https://xrwqtifhqycpxfjzfrip.supabase.co/functions/v1'
api_key = os.environ.get('FASIHTTS_API_KEY')
if not api_key or len(sys.argv) < 2:
    raise SystemExit('Set FASIHTTS_API_KEY, then run: python3 fasih-hd.py script.txt speech.mp3')
request_id = os.environ.get('FASIHTTS_REQUEST_ID') or str(uuid.uuid4())
print('Request ID (keep for safe retries):', request_id)

def post(endpoint, body, extra=None):
    headers = {'Content-Type': 'application/json', 'x-api-key': api_key}
    headers.update(extra or {})
    req = Request(BASE + '/' + endpoint, data=json.dumps(body).encode('utf-8'), headers=headers, method='POST')
    try:
        with urlopen(req, timeout=30) as response:
            return json.load(response)
    except HTTPError as error:
        raise RuntimeError('{}: HTTP {}. Keep the request ID for retries of unchanged input.'.format(endpoint, error.code)) from None

text = Path(sys.argv[1]).read_text(encoding='utf-8')
job_id = post('generate-tts-v2', {
    'text': text,
    'voice': os.environ.get('FASIHTTS_VOICE', 'ar-msa-formal-male-2'),
    'dialect': os.environ.get('FASIHTTS_DIALECT', 'ar-msa'),
}, {'Idempotency-Key': request_id})['jobId']
print('Job ID:', job_id)
for attempt in range(150):
    time.sleep(2)
    job = post('get-long-tts-job', {'id': job_id})['job']
    if job['status'] == 'failed':
        raise RuntimeError('Generation failed. Review the job before submitting another generation.')
    if job['status'] != 'completed':
        continue
    if not job.get('audio_url'):
        raise RuntimeError('Audio unavailable; do not automatically create another paid job.')
    with urlopen(job['audio_url'], timeout=60) as response:
        Path(sys.argv[2] if len(sys.argv) > 2 else 'speech.mp3').write_bytes(response.read())
    print('Audio saved.')
    break
else:
    raise RuntimeError('Job {} still pending. Poll it later; do not create a new generation.'.format(job_id))
