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

def send_request(method, data):
    if method == 'getFile':
        response = requests.post(f'{config.TELEGRAM_API}{method}', json=data)
    else:
        response = requests.post(f'{config.TELEGRAM_API}{method}', json=data)
    return response

def monitor_file(process, input_file):
    while (True):
        if process.poll() is None:
            if not os.path.exists(input_file):
                parent = psutil.Process(process.pid)
                for child in parent.children(recursive=True):
                    child.kill()
                parent.kill()
                break
            t.sleep(1)
        else:
            break
try:
    with Database() as db:
        media_task_db = db.get_media_task(3, 'status', 'id,message_id,file_name,package_id')
    if media_task_db:
        for task in media_task_db:
            task_id = task[0]
            message_id = task[1]
            file_name = task[2]
            package_id = task[3]
            with Database() as db:
                package_db = db.get_package(package_id,'id','chat_id,type')
            chat_id = package_db[0][0]
            task_type = package_db[0][1]
            if task_type == 2 or task_type == 6:
                with Database() as db:
                    db.update_media_task(task_id, 'status', 4)
                reply_markup = {
                    'inline_keyboard': [
                        [{'text': '❌ انصراف', 'callback_data': f'cancel,{task_id}'}]
                    ]
                }
                data = {
                    'chat_id': chat_id,
                    'message_id': message_id,
                    'text': '💬 درحال اضافه کردن زیرنویس...',
                    'reply_markup': reply_markup
                }
                send_request('editMessageText', data)
                command = f"ffprobe -i {config.DOWNLOAD_DIR}'{file_name}' -v quiet -show_entries format=duration -hide_banner -of default=noprint_wrappers=1:nokey=1 -sexagesimal"
                res = subprocess.run(command, shell=True, capture_output=True, text=True)
                if res.returncode == 0:
                    duration = res.stdout.split('.')[0].split(':')
                    sec = 0
                    if int(duration[0]) != 0:
                        sec = int(duration[0]) * 60
                        sec = sec * 60
                    sec += int(duration[1]) * 60
                    sec += int(duration[2])
                    try:
                        random_sec = random.randint(300, sec - 300)
                    except:
                        random_sec = random.randint(0, sec - 60)
                    with Database() as db:
                        media_task_db = db.get_media_task(task_id, 'id', 'sub_or_audio')
                    name, file_format = os.path.splitext(f'{file_name}')
                    if file_format != '.mkv':
                        command = f"ffmpeg  -i {config.DOWNLOAD_DIR}{file_name} -n -c copy {config.DOWNLOAD_DIR}{file_name.replace(file_format, '.mkv')}"
                        subprocess.run(command, shell=True, capture_output=True, text=True)
                        os.remove(f"{config.DOWNLOAD_DIR}{file_name}")
                        file_name = file_name.replace(file_format, ".mkv")
                        with Database() as db:
                            db.update_media_task(task_id, 'file_name', file_name)
                    subtitle = media_task_db[0][0]
                    command = f"ffmpeg  -i {config.DOWNLOAD_DIR}{file_name} -map 0 -map -0:s -c copy {config.DOWNLOAD_DIR}temp_{file_name}"
                    subprocess.run(command, shell=True, capture_output=True, text=True)
                    command = f"rm {config.DOWNLOAD_DIR}{file_name}"
                    subprocess.run(command, shell=True, capture_output=True, text=True)
                    command = f"mv {config.DOWNLOAD_DIR}temp_{file_name} {config.DOWNLOAD_DIR}{file_name}"
                    subprocess.run(command, shell=True, capture_output=True, text=True)
                    command = f'ffmpeg  -i {config.DOWNLOAD_DIR}{file_name} -i {config.LOGO_DIR} -filter_complex "[1][0]scale2ref=w=iw/9:h=ow/mdar[wm][vid];[vid][wm]overlay=W-w-5:H-h-5:enable=' + f"'between(t,{random_sec},{random_sec + 60})'" + f',subtitles={config.SUBTITLE_DIR}' + f"'{subtitle}'"+ f'" -c:a copy {config.HARDSUB_DIR}{file_name}'
                    process = subprocess.Popen(command, shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
                    monitor_thread = threading.Thread(target=monitor_file,args=(process, f'{config.DOWNLOAD_DIR}{file_name}'))
                    monitor_thread.start()
                    process.communicate()
                    monitor_thread.join()
                    try:
                        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')}")
                    except:
                        pass
                    with Database() as db:
                        db.update_media_task(task_id, 'status', 5)
                    break
except Exception as e:
    try:
        data = {
            'chat_id': 689423806,
            'text': f'ERROR: {task_id}, {file_name} {e}',
        }
        send_request('sendMessage', data)
    except:
        pass