import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from celery_tasks.celery import app
from config import TELEGRAM_API,LOGO_DIR,HARDSUB_DIR,MOVIEO_TELEGRAM_API
from base.utils.funcs import run_command
from base.utils.workflows import hardsub_workflow
from base.utils.subtitle_editor import *
from base.utils import MovieoDatabase, download_video, get_video_duration_seconds, get_random_second, convert_to_mkv


@app.task(queue='hardsubs')
def convert_to_hardsub(first_step_res: dict, file_name: str):
    status = first_step_res.get('status')
    if status:
        print(f'\n**********************\n--- trying to convert the file to hard sub... \n**********************')
        server_file_name = first_step_res.get('server_file_name')
        subtitle = first_step_res.get('subtitle')
        sync_score = first_step_res.get('sync_score')
        random_sec = first_step_res.get('random_sec')

        print(f'\n**********************\n--- trying to convert the file to hard sub... \n**********************')
        command = f'ffmpeg  -i {DOWNLOAD_DIR}{server_file_name} -i {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={SUBTITLE_DIR}' + f"'{subtitle}':charenc=UTF-8" + f'" -c:a copy {HARDSUB_DIR}{server_file_name}'
        run_command(command, 'something went wrong when trying to convert file to hard sub.')

        caption = f'{file_name}\n\nsync score: {sync_score}'
        first_step_res['caption'] = caption
        return first_step_res
    else:
        return {'status': False}

@app.task(queue='hardsubs')
def convert_softsub_to_hardsub(admin_user_id: int, request_id: int, request_type_str: str, file_id: str, file_name: str):
    try:
        with MovieoDatabase() as db:
            db.update_admins_requests(request_id, 'status', 1)
            db.update_users_requests(request_id, 'status', 1)
        print(f'\n**********************\n--- download {file_name} has begun. \n**********************')
        server_file_name, file_format = download_video(TELEGRAM_API,file_id,file_name)
        if server_file_name:
            subtitle = f'{file_id}.srt'
            print(f'\n**********************\n--- extracting persian subtitle from file.\n**********************')
            command = f"ffmpeg  -y -i {DOWNLOAD_DIR}{server_file_name} -map 0:s:m:language:per {DOWNLOAD_DIR}{subtitle}"
            subprocess.run(command, shell=True, capture_output=True, text=True)
            if not os.path.exists(f'{DOWNLOAD_DIR}{subtitle}'):
                print(f'\n**********************\n--- persian subtitle not found. trying to extract first subtitle track (maybe english).\n**********************')
                command = f"ffmpeg  -y -i {DOWNLOAD_DIR}{server_file_name} -map 0:s:0 {DOWNLOAD_DIR}{subtitle}"
                subprocess.run(command, shell=True, capture_output=True, text=True)

            if os.path.exists(f'{DOWNLOAD_DIR}{subtitle}'):
                print(f'\n**********************\n--- cleaning and preparation of the subtitles began.\n**********************')
                convert_to_utf8(subtitle)
                if request_type_str == 'Persian HardSub':
                    find_ads_in_subtitle(subtitle)
                if os.path.exists(f'{SUBTITLE_DIR}{subtitle}'):
                    os.remove(f'{DOWNLOAD_DIR}{subtitle}')
                else:
                    os.rename(f'{DOWNLOAD_DIR}{subtitle}', f'{SUBTITLE_DIR}{subtitle}')
                add_intro(subtitle, 2)
                add_outro(subtitle)
                subtitle = convert_to_ass(subtitle)

                print(f'\n**********************\n--- trying to delete all soft sub tracks... \n**********************')
                command = f"ffmpeg  -i {DOWNLOAD_DIR}{server_file_name} -map 0 -map -0:s -c copy {DOWNLOAD_DIR}temp_{server_file_name}"
                run_command(command, 'something went wrong when trying to delete all soft subs.')
                os.remove(f'{DOWNLOAD_DIR}{server_file_name}')
                os.rename(f"{DOWNLOAD_DIR}temp_{server_file_name}", f"{DOWNLOAD_DIR}{server_file_name}")

                if file_format != '.mkv':
                    print(f'\n**********************\n--- file format is {file_format}. we have to change it to mkv. \n**********************')
                    server_file_name = convert_to_mkv(server_file_name, file_format)

                print(f'\n**********************\n--- fetching duration and choosing random timestamp. \n**********************')
                sec = get_video_duration_seconds(f'{DOWNLOAD_DIR}{server_file_name}')
                random_sec = get_random_second(sec)

                print(f'\n**********************\n--- trying to convert the file to hard sub... \n**********************')
                command = f'ffmpeg  -i {DOWNLOAD_DIR}{server_file_name} -i {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={SUBTITLE_DIR}' + f"'{subtitle}':charenc=UTF-8"+ f'" -c:a copy {HARDSUB_DIR}{server_file_name}'
                run_command(command, 'something went wrong when trying to convert file to hard sub.')
                return {
                    'status': True,
                    'api_url': MOVIEO_TELEGRAM_API,
                    'user_id': -1003267897656,
                    'admin_review': False,
                    'server_file_name': server_file_name,
                    'caption': file_name,
                    'duration': sec
                }
        else:
            return {'status': False}
    except:
        with MovieoDatabase() as db:
            user_request_db = db.get_users_requests('id',request_id,'title_id')
        title_id = user_request_db[0][0]
        with MovieoDatabase() as db:
            title_db = db.get_title('id',title_id,'imdb_id,en_name,type')
        imdb_id = title_db[0][0]
        title_name = title_db[0][1]
        title_type = title_db[0][2]
        hardsub_workflow(int(admin_user_id), int(request_id), request_type_str, title_id, imdb_id, title_type, title_name, file_name, file_id)