import requests
import os
import json
import logging
import time

''' 准备数据 '''
SCHEDULER_BASE_URL = os.getenv("SCHEDULER_BASE_URL")
BACKEND_BASE_URL = os.getenv("BACKEND_BASE_URL")

logger = logging.getLogger("algoA logger")
missionId = os.getenv("missionId")
planId = os.getenv("planId")

headers = {
    "Content-Type": "application/json",  # 明确声明数据格式
    "Accept": "application/json"         # 声明期望的响应格式
}
params = {
    "missionId": missionId,
    "planId": planId,
}

print(json.dumps({'msg': 'started'}), flush=True)

response = requests.get(SCHEDULER_BASE_URL + '/fetchData', params=params, headers=headers)
data = response.json()
if not data:
    quit()
print(json.dumps({'msg': 'start', 'data': data}), flush=True)

''' 开始计算 '''
progressData = {
    'missionId': missionId,
    'planId': planId,
    'progress': 0,
}
print(json.dumps({'msg': 'progress', 'data': progressData}), flush=True)
start_time = time.perf_counter()
count = 0
while True:
    count += 1
    if time.perf_counter() - start_time >= 10.0:
        break   
progressData['progress'] = 20
print(json.dumps({'msg': 'progress', 'data': progressData}), flush=True)
start_time = time.perf_counter()
count = 0
while True:
    count += 1
    if time.perf_counter() - start_time >= 10.0:
        break   

progressData['progress'] = 40
print(json.dumps({'msg': 'progress', 'data': progressData}), flush=True)
start_time = time.perf_counter()
count = 0
while True:
    count += 1
    if time.perf_counter() - start_time >= 10.0:
        break   
progressData['progress'] = 60
print(json.dumps({'msg': 'progress', 'data': progressData}), flush=True)
start_time = time.perf_counter()
count = 0
while True:
    count += 1
    if time.perf_counter() - start_time >= 10.0:
        break   


''' 完成计算 '''
result = {
    'missionId': missionId,
    'planId': planId,
    'progress': 100,
    'nodes': [[1, 'S'], [2, 'D'], [3, 'D'], [4, 'I']],
    'edges': [[1, 2], [1, 4], [2, 4], [3, 4]],
}
print(json.dumps({'msg': 'result', 'data': result}), flush=True)

# if response:
#     if response.json()['code'] == 'OK':
#         print("response is ok")

#         response = requests.post(BACKEND_BASE_URL + "/rawDataTrans/", json={
#             'missionId': missionId,
#             'planId': planId,
#             'progress': 100,
#             'nodes': [[1, 'S'], [2, 'D'], [3, 'D'], [4, 'I']],
#             'edges': [[1, 2], [1, 4], [2, 4], [3, 4]],
#         })
#         print(f"算法控制程序推送结果完毕 MissionId: {missionId} PlanId: {planId} Message: {response.json()}")
#     else:
#         print(f"算法控制程序结果反馈未被识别 MissionId: {missionId} PlanId: {planId}")
# else:
#     print(f"算法控制程序结果反馈失败 MissionId: {missionId} PlanId: {planId}")