import os
import string
import secrets
import chardet
import pysrt
import shutil
from pysrt import SubRipFile, SubRipItem, SubRipTime
import pysubs2
import re
from fuzzywuzzy import fuzz
import subprocess
from datetime import timedelta
from base import DOWNLOAD_DIR,SUBTITLE_DIR

def detect_encoding(sub_name):
    with open(f'{DOWNLOAD_DIR}{sub_name}', 'rb') as f:
        raw_data = f.read()
    result = chardet.detect(raw_data)
    return result['encoding']


def repair_subtitle(sub_name):
    subs = pysubs2.load(f"{DOWNLOAD_DIR}{sub_name}", encoding="utf-8")
    if subs:
        subs.save(f"{DOWNLOAD_DIR}{sub_name}", format="srt")
    else:
        cleaned_srt_content = []
        pattern_subviewer = re.compile(r'(\d{1,2}:\d{2}:\d{2})\.(\d{2,3}),(\d{1,2}:\d{2}:\d{2})\.(\d{2,3})')

        pattern_srt = re.compile(r'(\d{2}:\d{2}:\d{2},\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2},\d{3})')

        with open(f"{DOWNLOAD_DIR}{sub_name}", 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.readlines()

        counter = 1
        i = 0
        while i < len(lines):
            line = lines[i].strip()

            match_sub = pattern_subviewer.match(line)
            match_srt = pattern_srt.match(line)

            start_srt = ""
            end_srt = ""
            is_match = False

            if match_sub:
                s_time, s_ms = match_sub.group(1), match_sub.group(2)
                e_time, e_ms = match_sub.group(3), match_sub.group(4)

                s_ms = s_ms.ljust(3, '0')
                e_ms = e_ms.ljust(3, '0')

                start_srt = f"{s_time},{s_ms}"
                end_srt = f"{e_time},{e_ms}"
                is_match = True

            elif match_srt:
                start_srt = match_srt.group(1)
                end_srt = match_srt.group(2)
                is_match = True

            if is_match:
                text_lines = []
                i += 1
                while i < len(lines):
                    next_line = lines[i].strip()
                    if pattern_subviewer.match(next_line) or pattern_srt.match(next_line):
                        i -= 1
                        break

                    if not next_line and len(text_lines) > 0:
                        pass

                    clean_text = next_line.replace('[br]', '\n').replace('<br>', '\n')
                    clean_text = re.sub(r'\[.*?\]', '', clean_text)
                    clean_text = re.sub(r'<.*?>', '', clean_text)

                    if clean_text:
                        text_lines.append(clean_text)

                    i += 1

                if text_lines:
                    block = f"{counter}\n{start_srt} --> {end_srt}\n{chr(10).join(text_lines)}\n\n"
                    cleaned_srt_content.append(block)
                    counter += 1

            i += 1

        if cleaned_srt_content:
            with open(f"{DOWNLOAD_DIR}{sub_name}", 'w', encoding='utf-8') as f:
                f.write("".join(cleaned_srt_content))


def repair_subtitle(sub_name):
    command = ['ffmpeg', '-y', '-v', 'error', '-i', f"{DOWNLOAD_DIR}{sub_name}", f"{DOWNLOAD_DIR}temp_{sub_name}"]
    subprocess.run(command, check=True)
    shutil.move(f"{DOWNLOAD_DIR}temp_{sub_name}", f"{DOWNLOAD_DIR}{sub_name}")

def convert_to_srt(input_path, file_format):
    output_path = input_path.replace(file_format,'.srt')
    subs = pysubs2.load(input_path)
    subs.save(output_path, format_="srt")
    os.remove(input_path)
    return output_path

def convert_to_utf8(sub_name):
    current_encode = detect_encoding(sub_name)
    if current_encode != 'UTF-8-SIG' and current_encode != 'utf-8':
        if current_encode not in ['UTF-16','UTF-32']:
            current_encode = 'Cp1256'
    with open(f'{DOWNLOAD_DIR}{sub_name}', 'r', encoding=current_encode, errors='ignore') as file:
        content = file.read()
    with open(f'{DOWNLOAD_DIR}{sub_name}', 'w', encoding='utf-8') as file:
        file.write(content)

def add_intro(sub_name, task_type: int):
    subtitles = pysrt.open(f"{SUBTITLE_DIR}{sub_name}")
    first_line_sec = 0
    try:
        first_line_sec = subtitles[0].start.seconds
    except:
        pass
    if first_line_sec >= 10:
        if task_type == 1 or task_type == 5:
            new_sub = pysrt.SubRipItem(index=0, start=pysrt.SubRipTime(0, 0, 2, 0), end=pysrt.SubRipTime(0, 0, 9, 0),text="<font color='#00BFFF'>*نسخه سافت ساب شده توسط موویوبات*\nموویوبات کامل ترین و پیشرفته ترین رسانه دانلود فیلم و سریال\nmovieobot.com</font>")
        elif task_type == 2 or task_type == 6:
            new_sub = pysrt.SubRipItem(index=0, start=pysrt.SubRipTime(0, 0, 2, 0), end=pysrt.SubRipTime(0, 0, 9, 0),text="<font color='#00BFFF'>*نسخه هارد ساب شده توسط موویوبات*\nموویوبات کامل ترین و پیشرفته ترین رسانه دانلود فیلم و سریال\nmovieobot.com</font>")
        subtitles.insert(0, new_sub)
    else:
        min_gap = timedelta(seconds=10)
        intro = False
        for i in range(len(subtitles) - 1):
            current_end = subtitles[i].end
            next_start = subtitles[i + 1].start
            current_end = timedelta(hours=current_end.hours,minutes=current_end.minutes,seconds=current_end.seconds)
            next_start = timedelta(hours=next_start.hours,minutes=next_start.minutes,seconds=next_start.seconds)
            gap = next_start - current_end
            if intro == False:
                if gap >= min_gap:
                    intro = True
                    new_start = current_end + timedelta(seconds=1)
                    new_end = new_start + timedelta(seconds=7)
                    total_seconds = new_start.total_seconds()
                    hours = total_seconds // 3600
                    remaining_seconds = total_seconds % 3600
                    minutes = remaining_seconds // 60
                    seconds = remaining_seconds % 60
                    new_start = pysrt.SubRipTime(hours=hours,minutes=minutes,seconds=seconds)
                    total_seconds = new_end.total_seconds()
                    hours = total_seconds // 3600
                    remaining_seconds = total_seconds % 3600
                    minutes = remaining_seconds // 60
                    seconds = remaining_seconds % 60
                    new_end = pysrt.SubRipTime(hours=hours, minutes=minutes, seconds=seconds)
                    if task_type == 1 or task_type == 5:
                        new_sub = pysrt.SubRipItem(index= i + 1, start=new_start, end=new_end,text="<font color='#00BFFF'>*نسخه سافت ساب شده توسط موویوبات*\nموویوبات کامل ترین و پیشرفته ترین رسانه دانلود فیلم و سریال\nmovieobot.com</font>")
                    elif task_type == 2 or task_type == 6:
                        new_sub = pysrt.SubRipItem(index= i + 1, start=new_start, end=new_end,text="<font color='#00BFFF'>*نسخه هارد ساب شده توسط موویوبات*\nموویوبات کامل ترین و پیشرفته ترین رسانه دانلود فیلم و سریال\nmovieobot.com</font>")
                    subtitles.insert(i + 1, new_sub)
            else:
                break
    subtitles.clean_indexes()
    subtitles.save(f'{SUBTITLE_DIR}{sub_name}',encoding='utf-8')

def add_outro(sub_name):
    subtitles = pysrt.open(f"{SUBTITLE_DIR}{sub_name}")
    indexes = len(subtitles)
    current_end = subtitles[indexes-1].end
    current_end = timedelta(hours=current_end.hours, minutes=current_end.minutes, seconds=current_end.seconds)
    new_start = current_end + timedelta(seconds=1)
    new_end = new_start + timedelta(seconds=7)
    total_seconds = new_start.total_seconds()
    hours = total_seconds // 3600
    remaining_seconds = total_seconds % 3600
    minutes = remaining_seconds // 60
    seconds = remaining_seconds % 60
    new_start = pysrt.SubRipTime(hours=hours, minutes=minutes, seconds=seconds)
    total_seconds = new_end.total_seconds()
    hours = total_seconds // 3600
    remaining_seconds = total_seconds % 3600
    minutes = remaining_seconds // 60
    seconds = remaining_seconds % 60
    new_end = pysrt.SubRipTime(hours=hours, minutes=minutes, seconds=seconds)
    new_sub = pysrt.SubRipItem(index=indexes + 1, start=new_start, end=new_end,text='دانلود هزاران فیلم و سریال با دوبله فارسی، زیرنویس چسبیده\nسافت ساب و هارد ساب + پخش آنلاین در موویوبات\nmovieobot.com')
    subtitles.insert(indexes, new_sub)
    subtitles.clean_indexes()
    subtitles.save(f'{SUBTITLE_DIR}{sub_name}',encoding='utf-8')

def find_ads_in_subtitle(sub_name):
    advertising_keywords = ['com','.me','net','ir','ws','best','<د','دیجــــی موویـــــز','سی نما','گرند موویز','baran','us','نایت‌مووی','دیباموویز','بامابین','فلامینگو','@','ترجمه','مترجم','.bid','بیاتوموویز','فیلامینگو','دیباموویز','مووی کاتیج','دیجی موویز','نایت مووی','سی‌نما','30نما','.co','tvcenter','.top','filamingo','link','cfd','kim','.in','org','.tv','www.','دیجی','30نما','.app','xyz']
    subtitles = pysrt.open(f"{DOWNLOAD_DIR}{sub_name}")
    deleted_subtitles = pysrt.SubRipFile()
    advertising_subs = set()

    for i, sub in enumerate(subtitles):
        text = sub.text.lower()
        if any(k in text for k in advertising_keywords):
            deleted_subtitles.append(sub)
            advertising_subs.add(i)

    for i, sub in enumerate(subtitles):
        text = sub.text.lower()
        text = re.sub(r'ـ+', '', text)
        text = re.sub(r'[.\s]+', '', text)
        for k in advertising_keywords:
            score = fuzz.ratio(text, k)
            if score >= 80:
                deleted_subtitles.append(sub)
                advertising_subs.add(i)

    filtered_subtitles = pysrt.SubRipFile(
        [s for i, s in enumerate(subtitles) if i not in advertising_subs]
    )

    filtered_subtitles.clean_indexes()
    filtered_subtitles.save(f"{SUBTITLE_DIR}{sub_name}", encoding="utf-8")
    print(f"Removed {len(advertising_subs)} ad subtitles from {sub_name}")

def convert_to_ass(file_name: str):
    subs = pysubs2.load(f'{SUBTITLE_DIR}{file_name}', encoding="utf-8")
    style = pysubs2.SSAStyle()
    style.fontname = "Vazirmatn"
    style.fontsize = 23
    style.primarycolor = pysubs2.Color(0, 210, 255)
    style.outlinecolor = pysubs2.Color(0, 0, 0)
    style.margin_v = 25
    style.bold = True
    subs.styles["Default"] = style
    os.remove(f'{SUBTITLE_DIR}{file_name}')
    ass_file = f"{file_name.replace('.srt','.ass')}"
    subs.save(f'{SUBTITLE_DIR}{ass_file}')
    return ass_file

def create_movieo_subtitle(sec):
    subs = SubRipFile()
    item = SubRipItem(
        index=1,
        start=SubRipTime(0, 0, 5, 0),
        end=SubRipTime(0, 0, 12, 0),
        text=f"ارائه شده توسط موویوبات\nmovieobot.com"
    )
    subs.append(item)
    seconds = sec - 300
    end_seconds = seconds + 7
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    remaining_seconds = seconds % 60
    hours_end = end_seconds // 3600
    minutes_end = (end_seconds % 3600) // 60
    remaining_seconds_end = end_seconds % 60
    item = SubRipItem(
        index=2,
        start=SubRipTime(hours, minutes, remaining_seconds, 0),
        end=SubRipTime(hours_end, minutes_end, remaining_seconds_end, 0),
        text = 'دانلود هزاران فیلم و سریال با دوبله فارسی، زیرنویس چسبیده\nسافت ساب و هارد ساب + پخش آنلاین در موویوبات\nmovieobot.com'
    )
    subs.append(item)
    chars = string.ascii_letters + string.digits
    sub_name = ''.join(secrets.choice(chars) for _ in range(5))
    subs.save(f'{SUBTITLE_DIR}{sub_name}.srt', encoding='utf-8')
    return sub_name