from flask import Flask, request
from uuid import uuid4
import os, json
import requests

app = Flask(__name__)

secret = os.environ.get("auth")
headers = {'Authorization': os.environ.get("auth")}

res_dict = {}

@app.route('/queue', methods=['POST'])
def queue():
    if request.json.get('secret') != secret:
        return {}, 400
        
    uuid = str(uuid4())
    res_dict[uuid] = request.json
    
    return { 'uuid': uuid }, 200

@app.route('/asr', methods=['GET'])
def asr():
    uuid = request.args.get('uuid')
    data = res_dict.get(uuid)
    if not data:
        return {}, 400
        
    URL = data.get('URL')
    body = data.get('body')
    
    res = requests.post(URL, json=body, headers=headers)
    if res.status_code == 200:
        res_json = res.json()
        
        callbackURL = data.get('callbackURL')
        callback_body = data.get('callbackBody')
        
        if res_json.get('data'):
            callback_body['length'] = len(res_json.data[0])
        if res_json.get('srt'):
            callback_body['srt'] = res_json.srt[0]
        
        requests.post(callbackURL, json=callback_body)

        print(callback_body)
        print(res_json)
        
        return res_json

    return {'error': '請求失敗'}, 500


# @app.route('/client', methods=['POST'])
# def client():
#     token = request.json.get('token')
#     data = reqList.get(token)
#     if not data:
#         return {}, 400
#     print(data)
#     URL = data.get('URL')
#     postData = data.get('postData')
    
#     response = requests.post(URL, json=postData)

#     return response.json()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)