import requests
import time
import json
from datetime import datetime
import telegram


bot_token = '2135410897:AAH14rU1sjvyP2WqD7lNAgMeYRNinofm4oE'
channel_name = 'adtlasbot'

def send_msg_telegram3(msg):
    message = """
    ["""+msg+"""]
    """
    bot = telegram.Bot(token=bot_token)
    bot.send_message(chat_id="@%s" % channel_name,
        text=message, parse_mode=telegram.ParseMode.HTML)


# Step 1: Post the task
url = "http://102.53.12.137:2023/api/v1/tasks/process"
payload = {
    'url': 'http://173.212.199.208/new_level1/2m/2m_hls/index202305301685433417.ts',
    'frames': '1'
}
headers = {
    'accept': 'application/json',
    'Content-Type': 'multipart/form-data',
}
response = requests.post(url, headers=headers, data=payload)
response_data = response.json()

task_id = response_data["task_id"]
status = response_data["status"]

# Step 2: Check the task status until it's "SUCCESS"
while status != "SUCCESS":
    time.sleep(5)  # wait for 5 seconds before making the next request
    status_url = f"http://102.53.12.137:2023/api/v1/tasks/status/{task_id}"
    status_response = requests.get(status_url, headers={'accept': 'application/json'})
    status_data = status_response.json()
    status = status_data["status"]

# Step 3: If the task status is "SUCCESS", get the result and save it to a JSON file
if status == "SUCCESS":
    result_url = f"http://102.53.12.137:2023/api/v1/tasks/result/{task_id}"
    result_response = requests.get(result_url, headers={'accept': 'application/json'})
    result_data = result_response.json()
    adbread_gen = {}
    # create a timestamped filename
    filename = datetime.now().strftime("%Y-%m-%d_%H%M%S") + f"___{task_id}.json"
    with open("/var/www/html/CBA_json/"filename, 'w') as outfile:
        json.dump(result_data, outfile)
        json.dumps(adbread_gen, indent=4, sort_keys=True)
    send_msg_telegram3(adbread_gen)
