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 DUBBED_DIR
from base.utils.funcs import run_command
from base.utils.subtitle_editor import *

@app.task(queue='dubbeds')
def convert_to_dubbed(first_step_res: dict, file_name: str):
    status = first_step_res.get('status')
    if status:
        server_file_name = first_step_res.get('server_file_name')
        audio_url = first_step_res.get('audio_url')
        print(f'\n**********************\n--- downloading audio file... \n**********************')
        audio_name = audio_url.split('/')[-1]
        command = f'wget -O "{DUBBED_DIR}{audio_name}" "{audio_url}"'
        run_command(command,'something went wrong when trying to download audio track.')

        print(f'\n**********************\n--- trying to convert the file to dubbed... \n**********************')
        command = f'ffmpeg -i "{DOWNLOAD_DIR}{server_file_name}" -i "{DUBBED_DIR}{audio_name}" -map 0:v:0 -map 1:a:0 -c:v copy -c:a copy -disposition:a:0 default -shortest "{DUBBED_DIR}{server_file_name}"'
        run_command(command, 'something went wrong when trying to convert file to dubbed.')
        os.remove(f'{DUBBED_DIR}{audio_name}')
        first_step_res['caption'] = file_name
        return first_step_res
    else:
        return {'status': False}