import hashlib

from fastapi import APIRouter

from routers.asr_client import send_asr_request, send_task_request
from routers.database import insert, update, query, Task

router = APIRouter(prefix='/asr/task',
                   tags=['tengxunyun_script_server'])


@router.post('/submit')
def task_submit(signature: str, url: str):
    json = send_asr_request(url)
    task = Task(signature=signature, task_id=json.Data.TaskId, task_result=json.to_json_string(), task_status=1)
    insert(task)
    return {'code': 0, 'taskId': json.Data.TaskId}


@router.post('/result')
def task_submit(task_id: int):
    json = send_task_request(task_id)
    task = query(None, None, task_id)[0]
    task.task_status = json.Data.Status
    task.task_result = json.to_json_string()
    try:
        if json.Data.Status == 2:
            task.word_text = json.Data.ResultDetail[0].FinalSentence
            task.word_split = json.Data.ResultDetail[0].SliceSentence
            task.word_text_md5 = hashlib.md5(task.word_text.encode('utf-8')).hexdigest()
    except:
        # 提取原始文本内容和分词内容发生异常，把 task_status 置为 -1
        task.task_status = -1
    update(task)
    return {'code': 0, 'status': json.Data.StatusStr}


@router.post('/list')
def task_submit(task_status: int):
    task = query(None, task_status, None)
    return {'code': 0, 'data': task}
