import os
import sys
import requests
import json
import threading
import multiprocessing
import random
import re
import psutil
import time as t
import subprocess
import torch
import torchaudio
import numpy as np
from silero_vad import get_speech_timestamps, read_audio, save_audio
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')
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 == 1 or task_type == 5:
        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)
        print(task_id)
        with Database() as db:
            media_task_db = db.get_media_task(task_id,'id','sub_or_audio')
        subtitle = media_task_db[0][0]
        name, file_format = os.path.splitext(f'{file_name}')
        # command = f'ffmpeg -i {config.DOWNLOAD_DIR}{file_name} {config.DOWNLOAD_DIR}{task_id}.wav'
        # result = subprocess.run(command, shell=True, capture_output=True, text=True)
        # model, utils = torch.hub.load(
        #     repo_or_dir='snakers4/silero-vad',
        #     model='silero_vad',
        #     force_reload=False
        # )
        # (get_speech_timestamps, save_audio, read_audio, VADIterator, collect_chunks) = utils
        # input_path = f'{config.DOWNLOAD_DIR}{task_id}.wav'
        # wav = read_audio(input_path)
        # sr = 16000
        # speech_timestamps = get_speech_timestamps(wav, model, sampling_rate=sr)
        # output = torch.zeros_like(wav)
        # for segment in speech_timestamps:
        #     start, end = segment['start'], segment['end']
        #     output[start:end] = wav[start:end]
        # save_audio(f"{config.DOWNLOAD_DIR}speech_{task_id}.wav", output, sampling_rate=sr)
        # command = f"alass {config.DOWNLOAD_DIR}speech_{task_id}.wav {config.SUBTITLE_DIR}'{subtitle}' {config.SUBTITLE_DIR}'fixed_{subtitle}'"
        # result = subprocess.run(command, shell=True, capture_output=True, text=True)
        # command = f"rm {config.SUBTITLE_DIR}'{subtitle}'"
        # subprocess.run(command, shell=True, capture_output=True, text=True)
        # command = f"rm {config.DOWNLOAD_DIR}{task_id}.wav"
        # subprocess.run(command, shell=True, capture_output=True, text=True)
        # command = f"rm {config.DOWNLOAD_DIR}speech_{task_id}.wav"
        # subprocess.run(command, shell=True, capture_output=True, text=True)
        # command = f"mv {config.SUBTITLE_DIR}'fixed_{subtitle}' {config.SUBTITLE_DIR}'{subtitle}'"
        # subprocess.run(command, shell=True, capture_output=True, text=True)
        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)
        command = f"ffmpeg -i {config.DOWNLOAD_DIR}'{file_name}' -n -sub_charenc 'UTF-8' -f srt -i {config.SUBTITLE_DIR}'{subtitle}' -map 0:0 -map 0:1 -map 1:0 -disposition:s:0 default -c:v copy -c:a copy -c:s srt {config.SOFTSUB_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_','')}")
            os.remove(f"{config.SUBTITLE_DIR}{subtitle}")
            os.remove(f"{config.SUBTITLE_DIR}deleted_{subtitle.replace('mvo_','')}")
        except:
            pass
        if os.path.exists(f'{config.SOFTSUB_DIR}{file_name}'):
            with Database() as db:
                db.update_media_task(task_id, 'status', 5)
# except Exception as e:
#         if os.path.exists(f'{config.SOFTSUB_DIR}{file_name}'):
#             with Database() as db:
#                 db.update_media_task(task_id, 'status', 5)
#         data = {
#             'chat_id': 689423806,
#             'text': f'ERROR: {task_id}, {file_name} {e}',
#         }
#         send_request('sendMessage', data)
