"""Python 3, standard library only. Arabic speech to text with your FasihTTS API key.

Run only on your server. Each NEW upload holds paid audio minutes; see README.md.
  FASIHTTS_API_KEY=... FASIHTTS_REQUEST_ID=$(python3 -c "import uuid; print(uuid.uuid4())") \
    python3 fasih-stt.py recording.mp3 transcript.txt
To resume polling after /start was accepted: FASIHTTS_JOB_ID=... python3 fasih-stt.py - transcript.txt
"""
import json
import os
import re
import sys
import time
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen

BASE = 'https://api.fasihtts.com/v1/stt/account'
api_key = os.environ.get('FASIHTTS_API_KEY')
request_id = os.environ.get('FASIHTTS_REQUEST_ID', '')
job_id = os.environ.get('FASIHTTS_JOB_ID')
output_file = sys.argv[2] if len(sys.argv) > 2 else 'transcript.txt'
UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$', re.I)
if not api_key or not job_id and (len(sys.argv) < 2 or not UUID.match(request_id)):
    raise SystemExit('Set FASIHTTS_API_KEY and a saved UUID in FASIHTTS_REQUEST_ID, then run: '
                     'python3 fasih-stt.py recording.mp3 transcript.txt. To resume, set FASIHTTS_JOB_ID.')


def call(path, method='GET', data=None, headers=None, timeout=30):
    all_headers = {'x-api-key': api_key}
    all_headers.update(headers or {})
    req = Request(BASE + path, data=data, headers=all_headers, method=method)
    try:
        with urlopen(req, timeout=timeout) as response:
            return json.load(response)
    except HTTPError as error:
        try:
            code = json.load(error).get('error', '')
        except Exception:
            code = ''
        raise RuntimeError('{}: HTTP {} {}. Keep the same request ID and job ID; do not upload again with a new ID.'
                           .format(path, error.code, code)) from None


if not job_id:
    print('Request ID (keep for unchanged retries):', request_id)
    # 1. Upload raw MP3 bytes. Retrying the same bytes with the same request ID returns the same job.
    upload = call('/source', 'POST', Path(sys.argv[1]).read_bytes(),
                  {'Content-Type': 'audio/mpeg', 'Idempotency-Key': request_id}, timeout=90)
    job_id = upload['jobId']
    # 2. Accept the quote. A job ID from /source does not mean /start was accepted.
    start_body = json.dumps({
        'jobId': job_id,
        'requestKey': upload['requestKey'],
        'quoteFingerprint': upload['creditQuote']['fingerprint'],
    })
    try:
        call('/start', 'POST', start_body.encode('utf-8'), {'Content-Type': 'application/json'})
    except Exception:
        print('If /start was interrupted, retry POST /start with this exact JSON before quote expiry:',
              start_body, file=sys.stderr)
        print('Do not switch to polling-only mode until /start is accepted.', file=sys.stderr)
        raise
    print('Job ID (safe to resume polling):', job_id, '· reserved seconds:', upload['creditQuote']['reservedUnits'],
          flush=True)

# 3. Poll the same job every 3 seconds for up to 5 minutes.
for attempt in range(100):
    result = call('/jobs/{}/result'.format(job_id))
    if result['status'] in ('queued', 'processing'):
        time.sleep(3)
        continue
    if result['status'] == 'ready':
        Path(output_file).write_text(result['reviewedTranscript'] or result['rawTranscript'], encoding='utf-8')
        print('Saved {}. Charged {} seconds.'.format(output_file, result['credit']['chargedUnits']))
        break
    # failed, no_speech and outcome_uncertain are final and release the held minutes.
    raise RuntimeError('Job {} ended as {}. Your minutes were released.'.format(job_id, result['status']))
else:
    raise RuntimeError('Job {} is still pending. Poll it later with FASIHTTS_JOB_ID; do not upload again.'.format(job_id))
