# video_player.py
import re
import fnmatch
import subprocess
import math
import sys
import time
from led_controller import CLEAR
import vlc
import os
import RPi.GPIO as gpio
from PyQt5.QtCore import Qt, QTimer, QObject, pyqtSignal, QCoreApplication
from PyQt5.QtWidgets import QMainWindow, QFrame, QApplication
from client_handler import get_message_play_video, get_setting_client, set_filepath, set_message_play_video, \
    onClient, setting, connected_socket, get_specialNavigationRequests

timeout = 0
app = None
player = None
Flag_LoopingVideoPlayer = False
specialNavigationRequests = []
# search_directory = "/home/blade/Videos/VDNH"


# Получаем абсолютный путь к директории, где находится скрипт
base_path = (os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Создание относительного пути к папке Videos
search_directory = os.path.join(base_path, "data", "Videos")

# Получаем имя пользователя из переменной окружения
user_name = os.getenv('USER', 'blade')  # по умолчанию 'blade', если переменная USER не задана
# Задаем переменную окружения для других нужд
os.environ['XDG_RUNTIME_DIR'] = f'/run/user/{user_name}'
# os.environ['XDG_RUNTIME_DIR'] = '/run/user/blade'

# Здесь определяются функции и классы для воспроизведения видео

def get_app(global_app = None):
    global app
    if app is None:
        app = global_app
    return app

def remove_createdVideos(flag_remove_cv = True):
    if flag_remove_cv:
        # Путь к папке Videos
        path = os.path.join(base_path, 'data', 'Videos', 'VDNH')
        
        folders = ['createdVideos', 'createdEvent', 'createdNavigation']  # Заданные папки для очистки
        for folder in folders:
            folder_path = os.path.join(path, folder)
            if os.path.exists(folder_path):
                for filename in os.listdir(folder_path):
                    file_path = os.path.join(folder_path, filename)
                    try:
                        if os.path.isfile(file_path):
                            os.remove(file_path)
                        print(f'Содержимое папки {folder} очищено')
                    except Exception as e:
                        print(f'Ошибка при удалении файла {file_path}: {e}')
            else:
                print(f'Папка {folder_path} не найдена')
    else:
        print('Папки остались без изменений')


class VideoPlayer(QMainWindow):  # Видеоплейер
    global connected_socket, timeout, start_time
    windowClosed = pyqtSignal()
    stopTimerSignal = pyqtSignal()

    def __init__(self, filename, timeout, initXaxis, initYaxis, sizeXaxis, sizeYaxis, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.stopTimerSignal.connect(self.stopTimer)
        
        self.setWindowTitle("Video Player")
        self.setGeometry(initXaxis, initYaxis, sizeXaxis, sizeYaxis)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)

        self.setStyleSheet("background-color: #000000")

        self.videoframe = QFrame()
        self.videoframe.setAutoFillBackground(False)
        self.setCentralWidget(self.videoframe)

        self.instance = vlc.Instance()
        self.instance.log_unset()
        self.player = self.instance.media_player_new()
        self.player.video_set_mouse_input(False)
        self.player.video_set_key_input(False)
        if sys.platform.startswith('linux'):  # for Linux using the X Server
            self.player.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":  # for Windows
            self.player.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":  # for MacOS
            self.player.set_nsobject(self.videoframe.winId())

        self.media = self.instance.media_new(filename)
        self.player.set_media(self.media)

        self.start_time = time.time()
        self.timeout = timeout
        self.finished = False

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.check_timeout)
        self.timer.start(1000)  # Проверять каждую секунду

        self.player.play()
        
    def check_timeout(self):
        global timeout, start_time, setting_client
        remaining_time = self.timeout - (time.time() - self.start_time)
        print(f"Осталось времени: {remaining_time:.1f} сек.")
        setting_client = get_setting_client()
        if remaining_time <= 0 or len(setting_client) > 1:
            print("Воспроизведение видео завершено!")
            self.finished = True
            self.timer.stop()
            self.release_resources()
            self.close()

    def release_resources(self):
        try:
            if self.timer:
                self.timer.stop()
                self.timer.deleteLater()
                self.timer = None  # Обнуляем ссылку на таймер после его удаления
        except Exception as e:
            print(f"Ошибка при остановке таймера: {e}")

        try:
            if self.player:
                self.player.stop()
                self.player = None  # Обнуляем ссылку на плеер после его остановки
        except Exception as e:
            print(f"Ошибка при остановке плеера: {e}")

        try:
            if self.instance:
                self.instance.release()
                self.instance = None  # Обнуляем ссылку на VLC instance после его освобождения
        except Exception as e:
            print(f"Ошибка при освобождении VLC instance: {e}")

        try:
            if self.videoframe:
                self.videoframe.deleteLater()
                self.videoframe = None  # Обнуляем ссылку на видеофрейм
        except Exception as e:
            print(f"Ошибка при удалении видеофрейма: {e}")
  

    def closeEvent(self, event):
        if not self.finished:
            event.ignore()
        else:
            self.stopTimer()
            self.release_resources()
            event.accept()
            self.windowClosed.emit()

    def stopTimer(self):
        if self.timer and self.timer.isActive():
            self.timer.stop()
    
    def set_new_media(self, filename, new_timeout):
        self.media = self.instance.media_new(filename)
        self.player.set_media(self.media)
        self.timeout = new_timeout
        self.start_time = time.time()
        self.player.play()
        if self.timer.isActive():
            self.timer.stop()
        self.timer.start(1000)

class LoopingVideoPlayer(VideoPlayer):
    global Flag_LoopingVideoPlayer, timeout, start_time
    def check_timeout(self):
        remaining_time = self.timeout - (time.time() - self.start_time)
        print(f"Осталось времени: {remaining_time:.1f} сек.")
        if Flag_LoopingVideoPlayer:
            print("Остановка воспроизведения видео!")
            self.stop_video()
            return
        if remaining_time <= 0 and not Flag_LoopingVideoPlayer:
            print("Перезапуск воспроизведения видео!")
            self.restart_video()
    
    def stop_video(self):
        self.finished = True
        self.timer.stop()
        self.release_resources()
        self.close()

    def restart_video(self):
        if self.player.is_playing():
            self.player.stop()
        self.player.play()  # Запустить повторно
        self.start_time = time.time()  # Сбросить таймер

    def stopTimer(self):
        if self.timer and self.timer.isActive():
            self.timer.stop()

def get_Flag_LoopingVideoPlayer():
    global Flag_LoopingVideoPlayer
    return Flag_LoopingVideoPlayer

def set_Flag_LoopingVideoPlayer(SetterParamFlag_LoopingVideoPlayer):
    global Flag_LoopingVideoPlayer
    Flag_LoopingVideoPlayer = SetterParamFlag_LoopingVideoPlayer

def video(filepath, timeout, initXaxis, initYaxis, sizeXaxis, sizeYaxis, play_in_loop=False):  
    global app
    if filepath is None or timeout is None:
        print('Отсутствует видеофайл для воспроизведения. Не запускаем видеоплеер')
        return
    
    app = QApplication(sys.argv)  # Получаем глобальный экземпляр QApplication
    
    global player  

    try:
        if play_in_loop:
            player = LoopingVideoPlayer(filepath, timeout, initXaxis, initYaxis, sizeXaxis, sizeYaxis)
        else:
            player = VideoPlayer(filepath, timeout, initXaxis, initYaxis, sizeXaxis, sizeYaxis)
        player.show()
        app.exec_()  # Запускаем цикл обработки событий
    except Exception as e:
        print(f"Произошла ошибка при воспроизведении видео: {e}")
    finally:
        if player:
            player.release_resources()  # Вызываем улучшенный метод освобождения ресурсов
            player.close()  # Закрываем окно плеера, если это еще не было сделано
            player = None  # Обнуляем глобальную переменную

        if app:
            app.quit()  # Завершаем QApplication
            app = None  # Обнуляем глобальный экземпляр QApplication

        return False 

def client_play_video(filepath, mode, counter_client_play_video, filepath_settinh_client, message_play_video, setting_init = None):  # Общеее или одиночное воспроизведение видеофайлов
    from client_handler import pixel
    global timeout, setting, setting_client
    setting = setting_init
    try:
        print(f'mode {mode}')
        setting_client = get_setting_client()
        if len(setting_client) < 2 and mode == True:
            print("Ждем команду для воспроизведения видео mode == True")
            if (filepath == '0' or filepath == None):
                timeout = 0
                return False
            else:
                timeout = get_length(filepath)
            print(f'Время воспроизведения видео {timeout}')

            onClient('Ожидание команды для воспроизведения')
            print(f'Ожидание {counter_client_play_video} сек команды для воспроизведения')

            value = 0
            while ((value <= counter_client_play_video) and (len(setting_client) < 2)):
                message_play_video = get_message_play_video()
                if (message_play_video == "Старт видео"):
                    set_message_play_video('')
                    print("Получена команда для воспроизвеедения видео")
                    return True
                else:
                    # onClient("Я еще жду...")
                    time.sleep(1)
                    value += 1
                    print(f'Ожидаем команду для старта видео: {value} сек')
            print('Закрыли цикл ожидания команды Старт')
            if value >= counter_client_play_video:
                print(f'Вышло время ожидания команды для воспроизведения. Заканчиваем выполнение команды {filepath_settinh_client}')
                # if filepath_settinh_client:
                #     filepath_settinh_client.pop(0)
                # if setting_client:
                #     setting_client.pop(0)
                # return_start()
                # print(f"Запрос клиента выполнен: {setting}")
                # onClient("Запрос клиента выполнен")
                # raise ContinueLoop()
                return False

        print(f'mode {mode}')
        if len(setting_client) > 1 and not mode == True:
            print("Ждем команду для воспроизведения видео mode == False")
            if (filepath == '0'):
                timeout = 0
                return False
            else:
                timeout = get_length(filepath)
            print(f'Время воспроизведения видео {timeout}')

            onClient('Ожидание команды для воспроизведения')
            print(f'Ожидание {counter_client_play_video} сек команды для воспроизведения')

            value = 0
            while ((value <= counter_client_play_video) and (len(setting_client) > 1)):
                message_play_video = get_message_play_video()
                if (message_play_video == "Старт видео"):
                    set_message_play_video('')
                    print("Получена команда для воспроизвеедения видео")
                    return True
                else:
                    # onClient("Я еще жду...")
                    time.sleep(1)
                    value += 1
                    print(f'Ожидаем команду для старта видео: {value} сек')
            print('Закрыли цикл ожидания команды Старт')
            if value >= counter_client_play_video:
                print(f'Вышло время ожидания команды для воспроизведения. Заканчиваем выполнение команды {filepath_settinh_client}')
                # if filepath_settinh_client:
                #     filepath_settinh_client.pop(0)
                # if setting_client:
                #     setting_client.pop(0)
                # return_start()
                # print(f"Запрос клиента выполнен: {setting}")
                # onClient("Запрос клиента выполнен")
                # raise ContinueLoop()
                return False



    except ConnectionResetError:
        print("close client_play_video")

        pixel.fill(CLEAR)
        time.sleep(3)
        gpio.cleanup()
        connected_socket.close()

        os.execv(sys.executable, [sys.executable] + sys.argv)

    except OSError:

        print("close onClient")

        pixel.fill(CLEAR)
        time.sleep(3)
        gpio.cleanup()
        connected_socket.close()

        os.execv(sys.executable, [sys.executable] + sys.argv)


def get_length(filepath):  # Определение продолжительности видеофайла
    print(f"Проверяем наличие и длину файла: {filepath}")
    if filepath is None:
        print("Нет файла, видео будет пропущено.")
        return None
    
    counter = 0

    while counter < 15:
        try:
            videofile = filepath
            result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
                                     "format=duration", "-of",
                                     "default=noprint_wrappers=1:nokey=1", videofile],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            return math.ceil(float(result.stdout))
        except:
            # onClient("Видеофайл отсутствует")
            print(f"Видеофайл {videofile} отсутствует.\n")
            time.sleep(1)
            counter += 1
            # return 0
    print('Видеофайл так и не появился')
    return None

def get_timeout():
    return timeout

def find_file(filename, search_path = search_directory):  # Определение пути видеофайла в директории
    if filename == None:
        print('Отсутствует файл для поиска, поиск не будет осуществлён.')
        return
    for root, dirs, files in os.walk(search_path):
        for file in files:
            if fnmatch.fnmatch(file, filename):
                print(os.path.join(root, file))
                return os.path.join(root, file)
    print(f'Файла {filename} отсутствует.')
    return None  # Нет файла!!!

# Функция для поиска китайских символов шрифта
def get_font(text):
    global chinese_pattern, font_cyrillic
    # Регулярное выражение для поиска китайских иероглифов
    chinese_pattern = re.compile(r'[\u4e00-\u9fff]+')
    # Путь к шрифту для китайского языка
    font_chinese = os.path.join(base_path, 'data', 'font_VDNH', 'NotoSansSC-Regular.ttf')
    print(f'Путь к файлу с китайским шрифтом: {font_chinese}')# Путь к шрифту для кириллицы и латиницы
    font_cyrillic = os.path.join(base_path, 'data', 'font_VDNH', 'VDNH-0.ttf')
    print(f'Путь к файлу с кириллическим шрифтом: {font_cyrillic}')
    # Проверяем, содержит ли текст китайские символы
    if chinese_pattern.search(text):
        return font_chinese
    else:
        return font_cyrillic

def add_scroll_text(inten, components):
    global start_time, specialNavigationRequests
    
     
    if not specialNavigationRequests:
        specialNavigationRequests = get_specialNavigationRequests()

    if inten == 'object_navigation':  # Наложение текста навигации
        distance_str, textNav, category = components.split('_')
        distance = int(distance_str)

        # new_parts = components[2][len(f'objectNav_'):]
        # textNav = new_parts[:30]
        

        print(f'category {category}')
        print(f'distance {distance}')
        print(f'text {textNav}')
        lowercase_textNav = textNav.lower()

        # Определение пути к файлам
        special_videos_path = os.path.join(base_path, "data", "Videos", "VDNH", "basic", "special")
        created_navigation_path = os.path.join(base_path, "data", "Videos", "VDNH", "createdNavigation")
        category_navigation_path = os.path.join(base_path, "data", "Videos", "VDNH", "basic", "category")
        # Поиск соответствующего видео в JSON
        video_title = None
        for item in specialNavigationRequests:
            if textNav in item.values():
                video_title = item['videoTitle']
                break
        print(f'||||||||||||||||||||||||||||||||||||||||||Значение поля со специальной болванкой: {video_title}||||||||||||||||||||||||||||||||||||||||||')
        
        # Тернарный оператор выбора видео либо из специальной болванки, либо из директории со стандартными болванками
        video_file_path = os.path.join(special_videos_path, f'{video_title}.mp4') if video_title else os.path.join(category_navigation_path, f'{category}.mp4')
        print(f'||||||||||||||||||||||||||||||||||||||||||Итоговая болванка для видео: {video_file_path}||||||||||||||||||||||||||||||||||||||||||')
        
        input_video = video_file_path
        print(f'Выбрано видео: {video_file_path}')

        text = textNav.replace('&', ' ')
        # Проверяем, существует ли уже выходной файл
        textNav_name = components[:30]
        output_video = os.path.join(created_navigation_path, f'{textNav_name}.mp4')
        if not os.path.isfile(output_video):
            print(f'Создается видео: {output_video}')
            
        else:
            print(f'Видео уже существует: {output_video}')
            return output_video

        # Дополнительные параметры для настройки текста и видео
        font_text = get_font(text)
        font_unit = os.path.join(base_path, 'data', 'Fonts', 'VDNH-0.ttf')
        font_color_list = ['white', 'white', 'white']
        font_size_list = [None, None]  # размеры шрифта для текста и единиц измерения

        # Время начала и окончания появления
        appearance_start_time = 5.5  # Начало появления текста на 1 секунде
        appearance_start_time_distance = 6.0  # Начало появления текста для дистанции также на 1 секунде
        appearance_finish_time = 6.5  # Завершение появления текста на 2.5 секунде
        appearance_finish_time_distance = 7  # Завершение появления текста для дистанции на 2.5 секунде
        appearance_time = 1.5  # Общее время появления

        # Время начала и окончания исчезновения
        disappearance_start_time = 18  # Начало исчезновения текста за 3.5 секунды до конца (при условии длительности 20 секунд)
        disappearance_start_time_distance = 17.5  # Начало исчезновения текста для дистанции за 3.5 секунды до конца
        disappearance_finish_time = 19.0  # Завершение исчезновения на 18 секунде
        disappearance_finish_time_distance = 18.0  # Завершение исчезновения текста для дистанции на 18 секунде
        disappearance_time = 1.5  # Общее время исчезновения

        text_filter = ""

        distance_obj = {
            'meaning': None,
            'meaning_left': [None, None],
            'meaning_right': [None, None],
            'unit': None,
            'unit_left': [None, None],
            'unit_right': [None, None],
        }

        if distance < 100:
            print('distance_obj 1 условие')
            font_size_list[1] = 50
            distance_obj['meaning'] = distance
            distance_obj['meaning_left'] = ['0.35*w', '0.425*h-th*0.25']
            distance_obj['meaning_right'] = ['w-0.35*w-tw*1.25', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
            distance_obj['unit'] = "м"
            distance_obj['unit_left'] = ['0.35*w+tw*1.75', '0.425*h']
            distance_obj['unit_right'] = ['w-0.35*w-tw*0.35', '0.425*h']  # Задаем правую координату относительно ширины экрана
        elif 100 <= distance <= 999:
            print('distance_obj 2 условие')
            font_size_list[1] = 50
            distance_obj['meaning'] = distance
            # Относительные координаты для позиционирования текста
            distance_obj['meaning_left'] = ['0.35*w-tw*0.25', '0.425*h-th*0.25']
            distance_obj['meaning_right'] = ['w-0.35*w-tw*1.25', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
            distance_obj['unit'] = "м"
            distance_obj['unit_left'] = ['0.35*w+tw*2.15', '0.425*h']
            distance_obj['unit_right'] = ['w-0.35*w-tw*0.35', '0.425*h']  # Задаем правую координату относительно ширины экрана
        elif 1000 <= distance <= 9999:
            if distance % 1000 == 0:
                print('distance_obj 3 условие')
                distance = distance // 1000
                font_size_list[1] = 50
                distance_obj['meaning'] = distance
                distance_obj['meaning_left'] = ['0.35*w', '0.425*h-th*0.25']
                distance_obj['meaning_right'] = ['w-0.35*w-tw*3.65', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
                distance_obj['meaning_right'] = ['w-0.35*w-tw*3.65', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
                distance_obj['unit'] = "км"
                distance_obj['unit_left'] = ['0.35*w+tw*0.75', '0.425*h']
                distance_obj['unit_right'] = ['w-0.35*w-tw*1.', '0.425*h']  # Задаем правую координату относительно ширины экрана
                distance_obj['unit_left'] = ['0.35*w+tw*0.75', '0.425*h']
                distance_obj['unit_right'] = ['w-0.35*w-tw*1.', '0.425*h']  # Задаем правую координату относительно ширины экрана

                
            elif distance % 1000 != 0:
                decimal_part = distance % 1000
                number_without_zeros = str(decimal_part).rstrip('0')
                decimal_part = int(number_without_zeros)
                if 0 < decimal_part <= 9:
                    print('distance_obj 4 условие')
                    distance = distance / 1000
                    font_size_list[1] = 50
                    distance_obj['meaning'] = distance
                    distance_obj['meaning_left'] = ['0.35*w-tw*0.75', '0.425*h-th*0.25']
                    distance_obj['meaning_left'] = ['0.35*w-tw*0.75', '0.425*h-th*0.25']
                    distance_obj['meaning_right'] = ['w-0.35*w-tw*0.75', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
                    distance_obj['unit'] = "км"
                    distance_obj['unit_left'] = ['0.35*w+tw*0.75', '0.425*h']
                    distance_obj['unit_right'] = ['w-0.35*w+tw*0.75', '0.425*h']  # Задаем правую координату относительно ширины экрана
                    distance_obj['unit_left'] = ['0.35*w+tw*0.75', '0.425*h']
                    distance_obj['unit_right'] = ['w-0.35*w+tw*0.75', '0.425*h']  # Задаем правую координату относительно ширины экрана
                elif 9 < decimal_part and str(distance)[:3].count('1') < 2:
                    print('distance_obj 5 условие')
                    distance = "{:.2f}".format(distance / 1000)
                    font_size_list[1] = 40
                    distance_obj['meaning'] = distance
                    distance_obj['meaning_left'] = ['0.35*w-tw*0.45', '0.425*h-th*0.25']
                    distance_obj['meaning_right'] = ['w-0.35*w-tw*1.25', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
                    distance_obj['unit'] = "км"
                    distance_obj['unit_left'] = ['0.35*w+tw*1', '0.425*h']
                    distance_obj['unit_right'] = ['w-0.35*w-tw*0.25', '0.425*h']  # Задаем правую координату относительно ширины экрана
                elif 9 < decimal_part and str(distance)[:3].count('1') > 1:
                    print('distance_obj 6 условие')
                    print(distance)
                    distance = "{:.2g}".format(distance / 1000)
                    print(distance)
                    font_size_list[1] = 50
                    distance_obj['meaning'] = distance
                    distance_obj['meaning_left'] = ['0.35*w-tw*0.45', '0.425*h-th*0.25']
                    distance_obj['meaning_right'] = ['w-0.35*w-tw*1.25', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
                    distance_obj['unit'] = "км"
                    distance_obj['unit_left'] = ['0.35*w+tw*1', '0.425*h']
                    distance_obj['unit_right'] = ['w-0.35*w-tw*0.25', '0.425*h']  # Задаем правую координату относительно ширины экрана
        elif 10000 <= distance <= 99999:
            print('distance_obj 7 условие')
            distance = round(distance)
            
            # distance = round(distance / 1000)
            font_size_list[1] = 35
            distance_obj['meaning'] = distance
            distance_obj['meaning_left'] = ['0.325*w-tw*0.25', '0.425*h-th*0.25']
            distance_obj['meaning_right'] = ['w-0.305*w-tw*1.75', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
            distance_obj['unit'] = "км"
            distance_obj['unit_left'] = ['0.35*w+tw*1.25', '0.425*h']
            distance_obj['unit_right'] = ['w-0.35*w+tw*0.225', '0.425*h']  # Задаем правую координату относительно ширины экрана
        elif 100000 <= distance <= 999999:
            print('distance_obj 8 условие')
            distance = round(distance / 1000)
            font_size_list[1] = 40
            distance_obj['meaning'] = distance
            distance_obj['meaning_left'] = ['0.35*w-tw*0.25', '0.425*h-th*0.25']
            distance_obj['meaning_right'] = ['w-0.35*w-tw*1.65', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
            distance_obj['unit'] = "км"
            distance_obj['unit_left'] = ['0.35*w+tw*1.25', '0.425*h']
            distance_obj['unit_right'] = ['w-0.35*w-tw*0.75', '0.425*h']  # Задаем правую координату относительно ширины экрана
        elif 1000000 <= distance <= 9999999:
            print('distance_obj 9 условие')
            distance = round(distance / 1000)
            font_size_list[1] = 32
            distance_obj['meaning'] = distance
            distance_obj['meaning_left'] = ['0.35*w-tw*0.15', '0.425*h-th*0.25']
            distance_obj['meaning_right'] = ['w-0.35*w-tw*1.5', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
            distance_obj['unit'] = "км"
            distance_obj['unit_left'] = ['0.35*w+tw*1.75', '0.425*h']
            distance_obj['unit_right'] = ['w-0.35*w-tw*0.75', '0.425*h']  # Задаем правую координату относительно ширины экрана
        elif 10000000 <= distance <= 99999999:
            print('distance_obj 10 условие')
            distance = round(distance / 1000)
            font_size_list[1] = 30
            distance_obj['meaning'] = distance
            distance_obj['meaning_left'] = ['0.35*w-tw*0.35', '0.425*h-th*0.25']
            distance_obj['meaning_right'] = ['w-0.35*w-tw*1.25', '0.425*h-th*0.25']  # Задаем правую координату относительно ширины экрана
            distance_obj['unit'] = "км"
            distance_obj['unit_left'] = ['0.35*w+tw*1.75', '0.425*h']
            distance_obj['unit_right'] = ['w-0.35*w-tw*0.25', '0.425*h']  # Задаем правую координату относительно ширины экрана

        # _________________

        character_count = len(text)

        text_obj = {
            'text': None,
            'text_left': [None, None],
            'text_right': [None, None]
        }

        if  character_count <= 5:  # Название места в 1 строку 10 символов
            print('text_obj 1 условие')
            text_obj['text'] = text
            font_size_list[0] = 52
            text_obj['text_left'] = ['0.13*w-tw*0.35', '0.425*h-th*0.265']
            text_obj['text_right'] = ['w-0.13*w-tw*0.65', '0.425*h-th*0.265']


        if 6 <= character_count <= 10:  # Название места в 1 строку 10 символов
            print('text_obj 1 условие')
            text_obj['text'] = text
            font_size_list[0] = 52
            text_obj['text_left'] = ['0.165*w-tw*0.35', '0.425*h-th*0.265']
            text_obj['text_right'] = ['w-0.165*w-tw*0.65', '0.425*h-th*0.265']

        elif 11 <= character_count <= 14:  # Название места в 1 строку 14 символов
            print('text_obj 2 условие')
            text_obj['text'] = text
            if chinese_pattern.search(text):
                font_size_list[0] = 19
            else: font_size_list[0] = 40
            text_obj['text_left'] = ['0.17*w-tw*0.35', '0.425*h-th*0.25']
            text_obj['text_right'] = ['w-0.17*w-tw*0.65', '0.425*h-th*0.25']

        elif 15 <= character_count <= 22:  # Название места в 2 строки по 10 символов
            print('text_obj 3 условие')
            words = text.split()
            new_line = ''
            current_length = 0
            maximum_string_length = 14

            for i, word in enumerate(words):
                word_length = len(word)

                if current_length + word_length + 1 > maximum_string_length:

                    if "-" in word and current_length < maximum_string_length - 1:
                        last_dash = word.rfind("-")

                        if last_dash > current_length:
                            new_line = new_line.rstrip() + '\n'
                            current_length = 0

                            # Добавляем в новую строку слово, начиная с символа "-", и обновляем текущую длину
                            new_line += word[last_dash + 1:] + ' '
                            current_length += len(word[last_dash + 1:]) + 1
                            continue
                
                new_line += word + ' '
                current_length += word_length + 1

                # Добавление отступа на следующую строчку
                if i < len(words) - 1:
                    next_word = words[i + 1]
                    next_word_length = len(next_word)


                    if current_length + next_word_length + 1 > maximum_string_length and next_word[-1] != "-":
                        new_line += '\n'
                        current_length = 0
                    #Обработка трёхбуквенных слов и менее
                    elif (next_word_length <= 3) and (current_length + word_length + next_word_length >= maximum_string_length):
                        new_line += '\n'
                        current_length = 0

            text = new_line.rstrip()
            print(text)
            text_obj['text'] = text
            if chinese_pattern.search(text):
                font_size_list[0] = 22
            else: font_size_list[0] = 36
            
            text_obj['text_left'] = ['0.155*w-tw*0.35', '0.425*h-th*0.37']
            text_obj['text_right'] = ['w-0.155*w-tw*0.6', '0.425*h-th*0.37']

        elif 23 <= character_count <= 40:  # Название места в 2 строки по 18 символов
            print('text_obj 4 условие')
            words = text.split()
            new_line = ''
            current_length = 0
            maximum_string_length = 20

            for i, word in enumerate(words):
                word_length = len(word)

                if current_length + word_length + 1 > maximum_string_length:
                    if "-" in word and current_length < maximum_string_length - 1:
                        last_dash = word.rfind("-")

                        if last_dash > current_length:
                            new_line = new_line.rstrip() + '\n'
                            current_length = 0

                            # Добавляем в новую строку слово, начиная с символа "-", и обновляем текущую длину
                            new_line += word[last_dash + 1:] + ' '
                            current_length += len(word[last_dash + 1:]) + 1
                            continue
                
                new_line += word + ' '
                current_length += word_length + 1

                # Добавление отступа на следующую строчку
                if i < len(words) - 1:
                    next_word = words[i + 1]
                    next_word_length = len(next_word)


                    if current_length + next_word_length + 1 > maximum_string_length and next_word[-1] != "-":
                        new_line += '\n'
                        current_length = 0

                    elif (next_word_length <= 3) and (current_length + word_length + next_word_length >= maximum_string_length):
                        new_line += '\n'
                        current_length = 0

            text = new_line.rstrip()
            print(text)
            text_obj['text'] = text
            
            if chinese_pattern.search(text):
                font_size_list[0] = 17
            else: font_size_list[0] = 30
            
            
            text_obj['text_left'] = ['0.095*w', '0.425*h-th*0.345']
            text_obj['text_right'] = ['w-0.31*w', '0.425*h-th*0.345']
                
        elif 41 <= character_count <= 55:  # Название места в 3 строки по 16 символов
            print('text_obj 5 условие')
            words = text.split()
            new_line = ''
            current_length = 0
            maximum_string_length = 18

            for i, word in enumerate(words):
                word_length = len(word)

                if current_length + word_length + 1 > maximum_string_length:

                    if "-" in word and current_length < maximum_string_length - 1:
                        last_dash = word.rfind("-")

                        if last_dash > current_length:
                            new_line = new_line.rstrip() + '\n'
                            current_length = 0

                            # Добавляем в новую строку слово, начиная с символа "-", и обновляем текущую длину
                            new_line += word[last_dash + 1:] + ' '
                            current_length += len(word[last_dash + 1:]) + 1
                            continue
                
                new_line += word + ' '
                current_length += word_length + 1

                # Добавление отступа на следующую строчку
                if i < len(words) - 1:
                    next_word = words[i + 1]
                    next_word_length = len(next_word)


                    if current_length + next_word_length + 1 > maximum_string_length and next_word[-1] != "-":
                        new_line += '\n'
                        current_length = 0

                    elif (next_word_length <= 3) and (current_length + word_length + next_word_length >= maximum_string_length):
                        new_line += '\n'
                        current_length = 0

            text = new_line.rstrip()
            print(text)
            text_obj['text'] = text
            
            if chinese_pattern.search(text):
                font_size_list[0] = 12
            else: font_size_list[0] = 25
            
            text_obj['text_left'] = ['0.145*w-tw*0.35', '0.425*h-th*0.4']
            text_obj['text_right'] = ['w-0.145*w-tw*0.625', '0.425*h-th*0.4']

        elif 56 <= character_count:  # Название места в 3 строки по 26 символов
            print('text_obj 6 условие')
            words = text.split()
            new_line = ''
            current_length = 0
            maximum_string_length = 36

            for i, word in enumerate(words):
                word_length = len(word)

                if current_length + word_length + 1 > maximum_string_length:

                    if "-" in word and current_length < maximum_string_length - 1:
                        last_dash = word.rfind("-")

                        if last_dash > current_length:
                            new_line = new_line.rstrip() + '\n'
                            current_length = 0

                            # Добавляем в новую строку слово, начиная с символа "-", и обновляем текущую длину
                            new_line += word[last_dash + 1:] + ' '
                            current_length += len(word[last_dash + 1:]) + 1
                            continue
                
                new_line += word + ' '
                current_length += word_length + 1

                # Добавление отступа на следующую строчку
                if i < len(words) - 1:
                    next_word = words[i + 1]
                    next_word_length = len(next_word)


                    if current_length + next_word_length + 1 > maximum_string_length and next_word[-1] != "-":
                        new_line += '\n'
                        current_length = 0

                    elif (next_word_length <= 3) and (current_length + word_length + next_word_length >= maximum_string_length):
                        new_line += '\n'
                        current_length = 0

            text = new_line.rstrip()
            print(text)
            text_obj['text'] = text
            
            if chinese_pattern.search(text):
                font_size_list[0] = 10
            else: font_size_list[0] = 17
            
            text_obj['text_left'] = ['0.17*w-tw*0.35', '0.425*h-th*0.355']
            text_obj['text_right'] = ['w-0.17*w-tw*0.625', '0.425*h-th*0.355']

        line_spacing_value = 10  # Значение интерлиньяжа, которое нужно установить

        text_filter += f"drawtext=fontfile={font_text}:text='{text_obj['text']}':fontcolor={font_color_list[0]}:fontsize={font_size_list[0]}:line_spacing={line_spacing_value}:x={text_obj['text_left'][0]}:y={text_obj['text_left'][1]}:alpha='if(gte(t,{appearance_start_time})*lte(t,{disappearance_finish_time}), if(between(t,{appearance_start_time},{appearance_finish_time}), (t-{appearance_start_time})/{appearance_time}, if(between(t,{disappearance_start_time},{disappearance_finish_time}), 1-(t-{disappearance_start_time})/{disappearance_time}, 1)), 0)',"
        text_filter += f"drawtext=fontfile={font_text}:text='{text_obj['text']}':fontcolor={font_color_list[0]}:fontsize={font_size_list[0]}:line_spacing={line_spacing_value}:x={text_obj['text_right'][0]}:y={text_obj['text_right'][1]}:alpha='if(gte(t,{appearance_start_time})*lte(t,{disappearance_finish_time}), if(between(t,{appearance_start_time},{appearance_finish_time}), (t-{appearance_start_time})/{appearance_time}, if(between(t,{disappearance_start_time},{disappearance_finish_time}), 1-(t-{disappearance_start_time})/{disappearance_time}, 1)), 0)',"

        text_filter += f"drawtext=fontfile={font_unit}:text='{distance_obj['meaning']}':fontcolor={font_color_list[1]}:fontsize={font_size_list[1]}:x={distance_obj['meaning_left'][0]}:y={distance_obj['meaning_left'][1]}:alpha='if(gte(t,{appearance_start_time_distance})*lte(t,{disappearance_finish_time_distance}), if(between(t,{appearance_start_time_distance},{appearance_finish_time_distance}), (t-{appearance_start_time_distance})/{appearance_time}, if(between(t,{disappearance_start_time_distance},{disappearance_finish_time_distance}), 1-(t-{disappearance_start_time_distance})/{disappearance_time}, 1)), 0)',"
        text_filter += f"drawtext=fontfile={font_unit}:text='{distance_obj['unit']}':fontcolor={font_color_list[2]}:fontsize={font_size_list[1]}:x={distance_obj['unit_left'][0]}:y={distance_obj['unit_left'][1]}:alpha='if(gte(t,{appearance_start_time_distance})*lte(t,{disappearance_finish_time_distance}), if(between(t,{appearance_start_time_distance},{appearance_finish_time_distance}), (t-{appearance_start_time_distance})/{appearance_time}, if(between(t,{disappearance_start_time_distance},{disappearance_finish_time_distance}), 1-(t-{disappearance_start_time_distance})/{disappearance_time}, 1)), 0)',"
        text_filter += f"drawtext=fontfile={font_unit}:text='{distance_obj['meaning']}':fontcolor={font_color_list[1]}:fontsize={font_size_list[1]}:x={distance_obj['meaning_right'][0]}:y={distance_obj['meaning_right'][1]}:alpha='if(gte(t,{appearance_start_time_distance})*lte(t,{disappearance_finish_time_distance}), if(between(t,{appearance_start_time_distance},{appearance_finish_time_distance}), (t-{appearance_start_time_distance})/{appearance_time}, if(between(t,{disappearance_start_time_distance},{disappearance_finish_time_distance}), 1-(t-{disappearance_start_time_distance})/{disappearance_time}, 1)), 0)',"
        text_filter += f"drawtext=fontfile={font_unit}:text='{distance_obj['unit']}':fontcolor={font_color_list[2]}:fontsize={font_size_list[1]}:x={distance_obj['unit_right'][0]}:y={distance_obj['unit_right'][1]}:alpha='if(gte(t,{appearance_start_time_distance})*lte(t,{disappearance_finish_time_distance}), if(between(t,{appearance_start_time_distance},{appearance_finish_time_distance}), (t-{appearance_start_time_distance})/{appearance_time}, if(between(t,{disappearance_start_time_distance},{disappearance_finish_time_distance}), 1-(t-{disappearance_start_time_distance})/{disappearance_time}, 1)), 0)'"

        # Генерируем команду FFmpeg для наложения текстовs
        cmd = [
            'ffmpeg',
            '-i', input_video,
            '-vf', text_filter,
            '-codec:a', 'copy',
            '-y', output_video
        ]

        # Запускаем процесс FFmpeg
        # subprocess.run(cmd)
        print("Видеофайл с объектом навигации создаеться")
        return (cmd)

    elif inten == 'event': # Наложение бегущей строки, названия объекта и времени
        print(f'Строка для разбиения: {components}')
        # Генерируем команду FFmpeg для наложения бегущей строки
        textNav, category, time, text  = components.split('_')
        print(f'name object {textNav}')
        print(f'categoty {category}')
        print(f'time {time}')
        print(f'text {text}')
        lowercase_textNav = textNav.lower()
        textObj = textNav.replace(' ', '&')
        textObj = textObj.replace('&', ' ') # Название объекта
        # time_event = time.replace('-', ' ') # Время проведения события
        # time_event = time
        time_event = time.replace(':', '∶')
        print('_______________________________________________________________________________')
        print(time_event)
        text = text.replace('&nbsp', '&')
        text = text.replace(' ', '&')
        text = text.replace('&', ' ')

        numberLines = math.ceil(375/len(text))
        text_event = text + ' ' * 10 + ((text + ' ' * 10) * (numberLines - 1)) # Информационный текст события

        categoryColor = {
			'музейная': '#e93747',
			'парковая': '#85bf57',
			'спортивная': '#3da3db',
			'знания': '#f0803d',
			'выставка«россия»\u200e': '#2b4d9e',
			'развлекательная': '#8c57a0'
		}
        color = categoryColor.get(category, '#000000')

        # text_name = components[:30]
        print(f'textNav {textNav}')
        
        input_video = os.path.join(search_directory, "VDNH", "basic", "event", f"{category}.mp4")
        print(f'Путь к входному видео «input_video»: {input_video}')
        output_video = os.path.join(search_directory, "VDNH", "createdEvent", f"{textNav}.mp4")
        print(f'Путь к выходному видео «output_video»: {output_video}')
        font = os.path.join(base_path, "data", "font_VDNH", "VDNH-0.ttf")
        font_color = '#ffccee'

        event_obj = {
			'fontsize': {
				'text_event': None,
				'time_event': None,
				'textObj': None
			},
			'x_y': {
				'left': {
					'time_event': [None,None],
					'textObj': [None,None]
				},
				'right': {
					'time_event': [None,None],
					'textObj': [None,None]
				}
			},
			'color': {
				'drawbox': None
			}
		}

        event_obj['fontsize']['text_event'] = '48'
        event_obj['fontsize']['time_event'] = '35'
        event_obj['x_y']['left']['time_event'][0] = '15'
        event_obj['x_y']['left']['time_event'][1] = '80'
        event_obj['x_y']['right']['time_event'][0] = 'w-tw-12'
        event_obj['x_y']['right']['time_event'][1] = '80'
        event_obj['color']['drawbox'] = color

        len_textObj = len(textObj)
        if len_textObj <= 12:
            event_obj['fontsize']['textObj'] = 48
            event_obj['x_y']['left']['textObj'] = ['w*0.2175','h*0.105']
            event_obj['x_y']['right']['textObj'] = ['w-w*0.445','h*0.105']
        elif 12 < len_textObj <= 24:
            words = textObj.split()
            new_line = ''
            current_length = 0
            maximum_string_length = 20

            for word in words:
                word_length = len(word)

                if current_length + word_length + 1 > maximum_string_length:
                    new_line += '\n'
                    current_length = 0

                new_line += word + ' '
                current_length += word_length + 1

            textObj = new_line.strip() 
            event_obj['fontsize']['textObj'] = 36
            event_obj['x_y']['left']['textObj'] = ['w*0.2175', 'h*0.105']
            event_obj['x_y']['right']['textObj'] = ['w-w*0.445', 'h*0.105']

        elif 24 < len_textObj <= 30:
            words = textObj.split()
            new_line = ''
            current_length = 0
            maximum_string_length = 20

            for word in words:
                word_length = len(word)

                if current_length + word_length + 1 > maximum_string_length:
                    new_line += '\n'
                    current_length = 0

                new_line += word + ' '
                current_length += word_length + 1
            
            textObj = new_line.strip() 
            event_obj['fontsize']['textObj'] = 26
            event_obj['x_y']['left']['textObj'] = ['w*0.2175', 'h*0.055']
            event_obj['x_y']['right']['textObj'] = ['w-w*0.445', 'h*0.055']
        elif len_textObj > 30:
            textObj = textObj[:23]
            words = textObj.split()
            new_line = ''
            current_length = 0
            maximum_string_length = 15

            for word in words:
                word_length = len(word)

                if current_length + word_length + 1 > maximum_string_length:
                    new_line += '\n'
                    current_length = 0

                new_line += word + ' '
                current_length += word_length + 1

            textObj = new_line.strip() + "..."
            event_obj['fontsize']['textObj'] = 28
            event_obj['x_y']['left']['textObj'] = ['w*0.2175', 'h*0.055']
            event_obj['x_y']['right']['textObj'] = ['w-w*0.445', 'h*0.055']



        text_filter = ''
        text_filter += f"drawtext=fontfile={font}:text='{text_event}':fontcolor={font_color}:fontsize={event_obj['fontsize']['text_event']}:x='if(gte(t,7),w-mod((t-7)*210,(w+tw)),w+tw)':y=h-th-10:enable='between(t,1,55.5)',"
        text_filter += f"drawbox=x=0:y=65:w=242:h=57:color={event_obj['color']['drawbox']}:t=fill:enable='between(t,7,56.5)',"
        text_filter += f"drawbox=x=1293:y=65:w=244:h=57:color={event_obj['color']['drawbox']}:t=fill:enable='between(t,7,56.5)',"
        text_filter += f"drawtext=fontfile={font}:text='{time_event}':fontcolor={font_color}:fontsize={event_obj['fontsize']['time_event']}:x={event_obj['x_y']['left']['time_event'][0]}:y={event_obj['x_y']['left']['time_event'][1]}:enable='between(t,7,56)':alpha='if(between(t,7,9),(t-7)/2,if(between(t,9,56.5),1,0))',"
        text_filter += f"drawtext=fontfile={font}:text='{time_event}':fontcolor={font_color}:fontsize={event_obj['fontsize']['time_event']}:x={event_obj['x_y']['right']['time_event'][0]}:y={event_obj['x_y']['right']['time_event'][1]}:enable='between(t,7,56)':alpha='if(between(t,7,9),(t-7)/2,if(between(t,9,56.5),1,0))',"
        text_filter += f"drawtext=fontfile={font}:text='{textObj}':fontcolor={font_color}:fontsize={event_obj['fontsize']['textObj']}:x={event_obj['x_y']['left']['textObj'][0]}:y={event_obj['x_y']['left']['textObj'][1]}:enable='between(t,7,56)':alpha='if(between(t,7,9),(t-7)/2,if(between(t,9,56.5),1,0))',"
        text_filter += f"drawtext=fontfile={font}:text='{textObj}':fontcolor={font_color}:fontsize={event_obj['fontsize']['textObj']}:x={event_obj['x_y']['right']['textObj'][0]}:y={event_obj['x_y']['right']['textObj'][1]}:enable='between(t,7,56)':alpha='if(between(t,7,9),(t-7)/2,if(between(t,9,56.5),1,0))'"

        cmd = [
            'ffmpeg',
            '-i', input_video,
            '-vf', text_filter,
            '-codec:a', 'copy',
            '-y', output_video
        ]

        # Запускаем процесс FFmpeg
        #subprocess.run(cmd)
        
        print(f"Создаеться файл с текстом {text[:30]}")
        return(cmd)


    elif inten == 'weather forecast':  # Наложение текста погоды
        main, temp, dirwind, speed, pressure = components.split('_')
        print(f'Main: {main}')
        print(f'temp: {temp}')
        print(f'dirwind: {dirwind}')
        print(f'speed: {speed}')
        print(f'pressure: {pressure}')

        if temp and temp[0] != "-":
            plus_symbol = '+'
            temp = plus_symbol + temp

        print(main)
        print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
        
        # Генерируем фильтр для наложения текстов погоды
        base_weather_path = os.path.join(search_directory, "VDNH", "basic", "weather")
        created_videos_path = os.path.join(search_directory, "VDNH", "createdVideos")
        font = os.path.join(base_path, "data", "font_VDNH", "VDNH-0.ttf")

        if os.path.isfile(os.path.join(base_weather_path, f"{main}.mp4")):
            input_video = os.path.join(base_weather_path, f"{main}.mp4")
        else:
            if (len(main) == 2 and (main[2] == 'd' or main[2] == 'n')):
                main = '02' + main[2]
                input_video = os.path.join(base_weather_path, f"{main}.mp4")
                print(f'Путь к входному видео «input_video»: {input_video}')
                
                print("Видеофайл для создания прогноза погоды отсутствует")
                # set_filepath(main)
                # return

        output_video = os.path.join(created_videos_path, "pogoda.mp4")
        
        print(f'Путь к выходному видео «output_video»: {output_video}')
        
        text_list = [f'{temp}°', f'{dirwind} {speed} м/с', f'{pressure} мм.рт.ст.']
        font_color_list = ['white', 'white', 'white']
        font_size_list = [100, 30, 30]
        start_time = 2
        fade_in_duration = 2  # Плавное появление в течение 2 секунд
        finish_time = 20
        fade_out_start = finish_time - 5  # Начало исчезновения текста за 5 секунд до конца
        fade_out_duration = 5  # Плавное исчезновение в течение 5 секунд
        # Определите x-координаты для левой и правой стороны, вернём координаты к предыдущему варианту
        left_x = "0.12*w"
        right_x = "w-0.12*w-tw"


        # Формируем фильтр
        text_filter = (
            f"drawtext=fontfile={font}:text='{text_list[0]}':fontcolor={font_color_list[0]}:fontsize={font_size_list[0]}:x={left_x}:y=0.25*h:enable='between(t,{start_time},{finish_time})'," # Левая циферка
            f"drawtext=fontfile={font}:text='{text_list[1]}':fontcolor={font_color_list[1]}:fontsize={font_size_list[1]}:x=0.262*w:y=0.25*h:enable='between(t,{start_time},{finish_time})'," # Верхняя левая надпись
            f"drawtext=fontfile={font}:text='{text_list[2]}':fontcolor={font_color_list[2]}:fontsize={font_size_list[2]}:x=0.64*w:y=0.65*h:enable='between(t,{start_time},{finish_time})'," # Правая нижняя надпись
            f"drawtext=fontfile={font}:text='{text_list[0]}':fontcolor={font_color_list[0]}:fontsize={font_size_list[0]}:x={right_x}:y=0.25*h:enable='between(t,{start_time},{finish_time})'," # Правая циферка
            f"drawtext=fontfile={font}:text='{text_list[1]}':fontcolor={font_color_list[1]}:fontsize={font_size_list[1]}:x=w-0.36*w:y=0.25*h:enable='between(t,{start_time},{finish_time})'," # Правая верхняя циферка
            f"drawtext=fontfile={font}:text='{text_list[2]}':fontcolor={font_color_list[2]}:fontsize={font_size_list[2]}:x=w-0.625*w-tw:y=0.65*h:enable='between(t,{start_time},{finish_time})'," # Левая нижняя надпись
            f"fade=t=in:st={start_time}:d={fade_in_duration},"
            f"fade=t=out:st={fade_out_start}:d={fade_out_duration}"
        )
        # Генерируем команду FFmpeg для наложения текстовs
        cmd = [
            'ffmpeg',
            '-i', input_video,
            '-vf', text_filter,
            '-codec:a', 'copy',
            '-y', output_video
        ]

        # Запускаем процесс FFmpeg
        # subprocess.run(cmd)
        print("Видеофайл с прогнозом погоды создаеться")
        return (cmd)

    elif inten == 'triffic widget':  # Наложение текста трафика
        main, score = components.split('_')
        score = int(score)
        print(f'Main: {main}')
        print(f'score: {score}')

        print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')

        # Пути к видео
        created_videos_path = os.path.join(base_path, 'data', 'Videos', 'VDNH', 'createdVideos')
        traffic_videos_path = os.path.join(base_path, 'data', 'Videos', 'VDNH', 'basic', 'traffic')
        font = os.path.join(base_path, 'data', 'font_VDNH', 'VDNH-0.ttf')
        
        # Проверяем, существует ли уже видео с учетом текущего балла
        input_video_path = os.path.join(created_videos_path, f"{main}_{score}.mp4")
        if os.path.isfile(input_video_path):
            input_video = input_video_path
        else:
            # Определяем имя базового видеофайла на основе уровня пробок
            if 1 <= score <= 3:
                base_video = 'green.mp4'
            elif 4 <= score <= 7:
                base_video = 'yellow.mp4'
            elif 8 <= score <= 10:
                base_video = 'red.mp4'
            else:
                print("Некорректный балл пробок")
                return

            input_video = os.path.join(traffic_videos_path, base_video)
            output_video = os.path.join(created_videos_path, f"traffic_{score}.mp4")
            print(f'Путь к входному видео «input_video»: {input_video}')
            print(f'Путь к выходному видео «output_video»: {output_video}')
        
            # Текстовый фильтр для FFmpeg
            fade_in_duration = 2  # текст появляется на протяжении 2 секунд
            fade_in_start = 2  # текст начинает появляться на 2-й секунде
            fade_out_duration = 5
            fade_out_start = 17 - fade_out_duration  # текст начинает исчезать на 12-й секунде

            # Плавное появление и исчезновение для каждого текста
            text_filter = (
                f"drawtext=fontfile={font}:text='{score}':fontcolor=black:fontsize=100:x=0.05*w:y=(h-th)/1.5:enable='between(t,{fade_in_start},{fade_out_start+fade_out_duration})',"
                f"fade=t=in:st={fade_in_start}:d={fade_in_duration},"
                f"fade=t=out:st={fade_out_start}:d={fade_out_duration},"
                f"drawtext=fontfile={font}:text='{score}':fontcolor=black:fontsize=100:x=w-(0.05*w)-tw:y=(h-th)/1.5:enable='between(t,{fade_in_start},{fade_out_start+fade_out_duration})',"
                f"fade=t=in:st={fade_in_start}:d={fade_in_duration},"
                f"fade=t=out:st={fade_out_start}:d={fade_out_duration}"
            )
            # Команда FFmpeg для наложения текста
            cmd = [
                'ffmpeg',
                '-i', input_video,
                '-vf', text_filter,
                '-codec:a', 'copy',
                '-y', output_video
            ]

            # Запускаем процесс FFmpeg
            subprocess.run(cmd)
            print(f"Видеофайл с баллом пробок {score} создан")
            return cmd
