import os
import sys
import requests
import json
import threading
import multiprocessing
import random
import re
import psutil
import time as t
import subprocess
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import config
from base.utils.database import Database

for task in os.listdir(config.ACTIVE_TASKS):
    file_path = os.path.join(config.ACTIVE_TASKS,task)
    if os.path.isfile(file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            result = file.read()
            if result == 'done':
                task_id = int(task.replace('.txt',''))
                with Database() as db:
                    media_task_db = db.get_media_task(task_id, 'id', 'package_id,file_name,sub_or_audio')
                package_id = media_task_db[0][0]
                file_name = media_task_db[0][1]
                subtitle = media_task_db[0][2]
                with Database() as db:
                    package_db = db.get_package(package_id,'id','type')
                task_type = package_db[0][0]
                if task_type == 2:
                    os.remove(f"{config.DOWNLOAD_DIR}{file_name}")
                    os.remove(f"{config.DOWNLOAD_DIR}{subtitle.replace('mvo_', '').replace('.ass','.srt')}")
                    os.remove(f"{config.SUBTITLE_DIR}{subtitle}")
                    os.remove(f"{config.SUBTITLE_DIR}{subtitle.replace('.ass', '.srt')}")
                    os.remove(f"{config.SUBTITLE_DIR}deleted_{subtitle.replace('mvo_', '').replace('.ass', '.srt')}")
                    if os.path.exists(f'{config.HARDSUB_DIR}{file_name}'):
                        with Database() as db:
                            db.update_media_task(task_id, 'status', 5)
                elif task_type == 4:
                    if os.path.exists(f'{config.MOVIEO_ENCODES_DIR}temp_{file_name}'):
                        command = f'rm {config.MOVIEO_ENCODES_DIR}{file_name}'
                        subprocess.run(command, shell=True, capture_output=True, text=True)
                        command = f'mv {config.MOVIEO_ENCODES_DIR}temp_{file_name} {config.MOVIEO_ENCODES_DIR}{file_name}'
                        subprocess.run(command, shell=True, capture_output=True, text=True)
                        os.remove(f"{config.DOWNLOAD_DIR}{file_name}")
                        os.remove(f"{config.SUBTITLE_DIR}movieo.srt")
                        with Database() as db:
                            db.update_media_task(task_id, 'status', 5)
                os.remove(file_path)