import phpserialize
import pymysql
import re
from multiprocessing import Pool
from collections import defaultdict
from operator import itemgetter


def get_db_connection():
    """Create and return a new database connection."""
    return pymysql.connect(
        host='127.0.0.1',
        user='sql_seo2024_ir',
        password='1bd0d20735dfd8',
        database='sql_seo2024_ir'
    )


def decode_byte_strings(data):
    if isinstance(data, dict):
        return {decode_byte_strings(key): decode_byte_strings(value) for key, value in data.items()}
    elif isinstance(data, bytes):
        return data.decode('utf-8')
    elif isinstance(data, list):
        return [decode_byte_strings(item) for item in data]
    else:
        return data
    
def get_capacity(link):
    import requests
    try:
        response = requests.head(link, allow_redirects=True, timeout=10)
        file_size = response.headers.get('Content-Length')
        if file_size is not None:
            cap = int(file_size) / (1024 * 1024 * 1024)
            return f"{cap:.2f}"
    except requests.RequestException as e:
        print(f"An error occurred in get_capacity: {e}")
        return '0'


########## For MOVIES 
def movies_dlbox(lines, post_id):
    data = {}
    srt = ''
    xsrt = ''
    
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            for count, line in enumerate(lines):
                if 'Dubbed' in str(str(str(line).split(';')[-1].strip())):
                    sql_insert_meta_post = """
                    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                    VALUES (%s, %s, %s)
                    """
                    cursor.execute(sql_insert_meta_post, (post_id, 'has_dubbed', str('on')))
                    connection.commit()
    except Exception as e:
        print(f"Error setting has_dubbed for post_id {post_id}: {e}")
    
    try:
        with connection.cursor() as cursor:
            for count, line in enumerate(lines):
                if '.vtt' in line:
                    xsrt = str(str(line).split(';')[-1].strip()).replace('cdnfun.info', 'hostikadeh.ir')
                    sql_insert_meta_post = """
                        INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                        VALUES (%s, %s, %s)
                        """
                    cursor.execute(sql_insert_meta_post, (post_id, 'has_subtitle', str('on')))
                    connection.commit()
                    break
    except Exception as e:
        print(f"Error setting has_subtitle for post_id {post_id}: {e}")
    
    quality_order = {"1080p": 3, "720p": 2, "480p": 1}
    # Create a list to store movie links with their quality
    movie_links = []
    for count, line in enumerate(lines):
        if '.mp4' in line:
            quality = ''
            if '1080' in line:
                quality = '1080p'
            if '720' in line:
                quality = '720p'
            if '480' in line:
                quality = '480p'
            movie_links.append((line, quality, count))
    
    # Sort movie links by quality (1080p > 720p > 480p)
    movie_links.sort(key=lambda x: -quality_order.get(x[1], 0))
    
    for new_count, (line, quality, old_count) in enumerate(movie_links):
        type_link = 'sub'
        if 'Dubbed' in str(str(str(line).split(';')[-1].strip())):
            type_link = 'dub'
        
        quality_link = ''
        if '1080' in line:
            quality_link = '1080p'
            if 'bluray' in str(line).lower():
                quality_link = 'BluRay 1080p'
            if 'web-dl' in str(line).lower():
                quality_link = 'WEB-DL 1080p'
        if '720' in line:
            quality_link = '720p'
            if 'bluray' in str(line).lower():
                quality_link = 'BluRay 720p'
            if 'web-dl' in str(line).lower():
                quality_link = 'WEB-DL 720p'
        if '480' in line:
            quality_link = '480p'
            if 'bluray' in str(line).lower():
                quality_link = 'BluRay 480p'
            if 'web-dl' in str(line).lower():
                quality_link = 'WEB-DL 480p'
            
        if type_link == 'dub':
            srt = ''
        else:
            srt = xsrt
        
        dl_capacity = get_capacity(str(str(str(line).split(';')[-1].strip())))
        # print(dl_capacity)
        try:
            if float(dl_capacity) < 1:
                dl_capacity = str(dl_capacity).split('.')[1]+'0' + ' MegaByte '
            else:
                dl_capacity = str(dl_capacity) + ' GigaByte '
        except:
            dl_capacity = '0'
        # print(dl_capacity)
        data[new_count] = {
            b'dl_link': str(str(str(line).split(';')[-1].strip()).split(',')[0]).replace("'", "").encode(),
            b'quality_link': str(quality_link).encode(),
            b'dl_capacity': str(dl_capacity).encode(),
            b'encoder_link': b'',
            b'dl_quality_example': b'',
            b'dl_sound': b'',
            b'dl_sub': str(re.sub(r'https://[^/]+', 'https://dl-2.seo2024.ir', str(srt))).encode(),
            b'link_type': str(type_link).encode(),
            b'sub_type': b'0',
            b'dl_price': b''
        }
    
    data = dict(sorted(data.items(), key=lambda x: x[1][b'link_type'] == b'dub'))
    deserialized_data = decode_byte_strings(data)
    connection.close()
    return phpserialize.dumps(deserialized_data)


def movies_playlinks(lines):
    data = {}
    srt = ''
    xsrt = ''
    for count, line in enumerate(lines):
        if '.vtt' in line:
            xsrt = str(str(line).split(';')[-1].strip()).replace('cdnfun.info', 'hostikadeh.ir')
            break
    
    quality_order = {"1080p": 3, "720p": 2, "480p": 1}
    # Create a list to store movie links with their quality
    movie_links = []
    for count, line in enumerate(lines):
        if '.mp4' in line:
            quality = ''
            if '1080' in line:
                quality = '1080p'
            if '720' in line:
                quality = '720p'
            if '480' in line:
                quality = '480p'
            movie_links.append((line, quality, count))
    
    # Sort movie links by quality (1080p > 720p > 480p)
    movie_links.sort(key=lambda x: -quality_order.get(x[1], 0))
    
    for new_count, (line, quality, old_count) in enumerate(movie_links):
        type_link = 'sub'
        if 'Dubbed' in str(str(str(line).split(';')[-1].strip())):
            type_link = 'dub'
        quality_link = ''
        if '1080' in line:
            quality_link = '1080'
        if '720' in line:
            quality_link = '720'
        if '480' in line:
            quality_link = '480'
            
        if type_link == 'dub':
            srt = ''
        else:
            srt = xsrt
        
        data[new_count] = {
            b'play_link': str(str(str(str(line).split(';')[-1].strip()).split(',')[0]).replace('hostikadeh.ir', 'hostikadeh.ir').replace('cdnfun.info', 'hostikadeh.ir')).replace("'", "").encode(),
            b'fasub_link': str(re.sub(r'https://[^/]+', 'https://dl.seo2024.ir', str(srt))).encode(),
            b'ensub_link': str('').encode(),
            b'quality_link': str(quality_link).encode(),
            b'type_link': str(type_link).encode(),
        }
    
    data = dict(sorted(data.items(), key=lambda x: x[1][b'type_link'] == b'dub'))
    deserialized_data = decode_byte_strings(data)
    return phpserialize.dumps(deserialized_data)


# ... (بقیه کد macher.py بدون تغییر، از جمله serials_dlbox و serials_playlinks)
######################  
    
    
############ For Series
def serials_dlbox(lines, post_id):
    connection = get_db_connection()
    data = {}
    
    try:
        with connection.cursor() as cursor:
            sql_insert_meta_post = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
            cursor.execute(sql_insert_meta_post, (post_id, 'has_subtitle', str('on')))
            connection.commit()
    except Exception as e:
        print(f"Error setting has_subtitle for post_id {post_id}: {e}")
    
    for count, line in enumerate(lines):
        links = {}
        go = False
        type_link = 'sub'
        for l, x in enumerate(lines[line]):
            quality = ''
            if 'x265' not in str(str(x[-2]).strip()):
                links[l] = {
                    b'title': str("Episode "+str(x[-3])).encode(),
                    b'link': str(x[-2]).strip().encode(),
                    b'subtitle': str(re.sub(r'https://[^/]+', 'https://dl-2.seo2024.ir', str(x[-1]))).encode(),
                }
                if 'Dubbed' in str(x[-2]).strip():
                    type_link = 'dub'
                    
                if '1080' in str(x[-2]).strip():
                    quality = '1080p'
                    if 'bluray' in str(x[-2]).strip().lower():
                        quality = 'BluRay 1080p'
                    if 'web-dl' in str(x[-2]).strip().lower():
                        quality = 'WEB-DL 1080p'
                if '720' in str(x[-2]).strip():
                    quality = '720p'
                    if 'bluray' in str(x[-2]).strip().lower():
                        quality = 'BluRay 720p'
                    if 'web-dl' in str(x[-2]).strip().lower():
                        quality = 'WEB-DL 720p'
                if '480' in str(x[-2]).strip():
                    quality = '480p'
                    if 'bluray' in str(x[-2]).strip().lower():
                        quality = 'BluRay 480p'
                    if 'web-dl' in str(x[-2]).strip().lower():
                        quality = 'WEB-DL 480p'
                              
                go = True  
        if go: 
            data[count] = {
                b'name': str("Season " + str(lines[line][0][0])).encode(),
                b'quality': str(quality).encode(),
                b'count': str(len(lines[line])).encode(),
                b'capacity': '',
                b'subtype': str(0).encode(),
                b'type': str(type_link).encode(),
                b'items': links
            }
    
    data = dict(sorted(data.items(), key=lambda x: x[1][b'type'] == b'dub'))
    deserialized_data = decode_byte_strings(data)
    try:
        if 'Dubbed' in str(phpserialize.dumps(deserialized_data)):
            with connection.cursor() as cursor:
                sql_insert_meta_post = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta_post, (post_id, 'has_dubbed', str('on')))
                connection.commit()
    except Exception as e:
        print(f"Error setting has_dubbed for post_id {post_id}: {e}")
    
    connection.close()
    return phpserialize.dumps(deserialized_data)


def serials_playlinks(lines):
    data = {}
    for count, line in enumerate(lines):
        links = {}
        go = False
        type_link = ''
        for l, x in enumerate(lines[line]):
            if 'x265' not in str(str(x[1]).strip()):
                links[l] = {
                    b'play_link': str(x[-2]).strip().encode(),
                    b'fasub_link': str(re.sub(r'https://[^/]+', 'https://dl.seo2024.ir', str(x[-1]))).encode(),
                }
                if 'Dubbed' in str(x[-2]).strip():
                    type_link = 'dub'
                go = True
                
        if go:
            quality_ = ''
            if '1080' in str(str(lines[line][0][1])):
                quality_ = '1080'
            if '720' in str(str(lines[line][0][1])):
                quality_ = '720'
            if '480' in str(str(lines[line][0][1])):
                quality_ = '480'
            data[count] = {
                b'season_name': str("Season " + str(lines[line][0][0])).encode(),
                b'quality_link': str(quality_).encode(),
                b'type_link': str(type_link).encode(),
                b'items': links
            }
    
    data = dict(sorted(data.items(), key=lambda x: x[1][b'type_link'] == b'dub'))
    deserialized_data = decode_byte_strings(data)
    return phpserialize.dumps(deserialized_data)
######################

def get_links_movie(imdb, postid):
    zarid = ''
    with open('importer/zarids.txt', 'r', encoding='utf-8') as lines:
        for line in lines:
            try:
                if str(imdb).strip() == str(line.split(';')[-1].strip()):
                    zarid = line.strip()
                    break
            except Exception as e:
                # print(f"Error reading zarids.txt: {e}")
                pass
    idLine = zarid
    # print(f"IMDb: {imdb}, zarid: {zarid}, idLine: {idLine}")  # دیباگ
    
    if not idLine:
        print(f"No zarid found for IMDb {imdb}")
        return
    
    connection = get_db_connection()
    try:
        with open('linkss.txt', 'r', encoding='utf-8') as lines:
            links = []
            is_movie = False
            is_series = False
            
            # print(f"Reading linkss.txt for id: {idLine.split(';')[0]}")  # دیباگ
            target_id = str(idLine.split(';')[0]).strip()
            target_imdb = str(imdb).strip()
            # print(f"Target ID: {target_id}, Target IMDb: {target_imdb}")  # دیباگ
            
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                # print(f"Processing line: {line}")  # دیباگ
                parts = line.split(';')
                # print(f"Number of columns: {len(parts)}")  # دیباگ
                current_id = str(parts[0]).strip() if len(parts) > 0 else ''
                current_imdb = str(parts[4]).strip() if len(parts) > 4 else ''
                # print(f"Current ID: {current_id}, Current IMDb: {current_imdb}, ID Match: {current_id == target_id}, IMDb Match: {current_imdb == target_imdb}")  # دیباگ
                if len(parts) >= 4 and (current_id == target_id or current_imdb == target_imdb):
                    if len(parts) in [4, 5, 6]:  # فیلم‌ها 4، 5، یا 6 ستون
                        link = str(parts[3].strip()) if len(parts) > 3 else ''
                        if link:
                            links.append(link)
                            is_movie = True
                            # print(f"Added movie link: {link}")  # دیباگ
                    elif len(parts) in [7, 8]:  # سریال‌ها 7 یا 8 ستون
                        links.append(line)
                        is_series = True
                        # print(f"Added series link: {line}")  # دیباگ
            
            # print(f"Links found: {links}, is_movie: {is_movie}, is_series: {is_series}")  # دیباگ
            if len(links) > 0 and len(postid) > 1:
                if is_movie:  # برای فیلم‌ها
                    data = movies_dlbox(links, postid)
                    with connection.cursor() as cursor:
                        sql_check_meta_post = """
                            SELECT COUNT(*) 
                            FROM wp_postmeta 
                            WHERE post_id = %s AND meta_key = %s
                        """
                        cursor.execute(sql_check_meta_post, (postid, 'movies_dlbox'))
                        exists = cursor.fetchone()[0]

                        if exists:
                            sql_update_meta_post = """
                                UPDATE wp_postmeta
                                SET meta_value = %s
                                WHERE post_id = %s AND meta_key = %s
                            """
                            cursor.execute(sql_update_meta_post, (str(data).replace("b'", "").replace("'", ""), postid, 'movies_dlbox'))
                        else:
                            sql_insert_meta_post = """
                                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                                VALUES (%s, %s, %s)
                            """
                            cursor.execute(sql_insert_meta_post, (postid, 'movies_dlbox', str(data).replace("b'", "").replace("'", "")))

                        connection.commit()
                        print(f"Updated movies_dlbox for postid {postid}")  # دیباگ
                
                    data = movies_playlinks(links)
                    with connection.cursor() as cursor:
                        sql_check_meta_post = """
                            SELECT COUNT(*) 
                            FROM wp_postmeta 
                            WHERE post_id = %s AND meta_key = %s
                        """
                        cursor.execute(sql_check_meta_post, (postid, 'movies_playlinks'))
                        exists = cursor.fetchone()[0]

                        if exists:
                            sql_update_meta_post = """
                                UPDATE wp_postmeta
                                SET meta_value = %s
                                WHERE post_id = %s AND meta_key = %s
                            """
                            cursor.execute(sql_update_meta_post, (str(data).replace("b'", "").replace("'", ""), postid, 'movies_playlinks'))
                        else:
                            sql_insert_meta_post = """
                                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                                VALUES (%s, %s, %s)
                            """
                            cursor.execute(sql_insert_meta_post, (postid, 'movies_playlinks', str(data).replace("b'", "").replace("'", "")))

                        connection.commit()
                        # print(f"Updated movies_playlinks for postid {postid}")  # دیباگ
                
                elif is_series:  # برای سریال‌ها
                    quality_order = {"1080p": 3, "720p": 2, "480p": 1}
                    links_series = []
                    for line in links:
                        try:
                            parts = line.split(';')
                            fasl = parts[3]
                            episod = parts[2]
                            link = parts[-1]
                            quality = ''
                            if '1080' in link:
                                quality = '1080p'
                            if '720' in link:
                                quality = '720p'
                            if '480' in link:
                                quality = '480p'
                            
                            Dubbed = False
                            if 'Dubbed' in link:
                                Dubbed = True
                            
                            srt = parts[-2]
                            try:
                                fasl_num = int(fasl)
                                episod_num = int(episod)
                            except ValueError:
                                print(f"Invalid season or episode number in link: {line}")
                                continue
                            links_series.append([quality, fasl, Dubbed, episod, link, srt])
                        except Exception as e:
                            print(f"Error processing series link: {line}, Error: {e}")
                            continue

                    grouped_data = defaultdict(list)
                    for quality, fasl, Dubbed, episod, link, srt in links_series:
                        grouped_data[fasl, quality, Dubbed].append([fasl, quality, Dubbed, episod, link, srt])
                    
                    for fasl in grouped_data:
                        grouped_data[fasl].sort(key=itemgetter(1))
                    
                    sorted_keys = sorted(grouped_data.keys(), key=lambda x: (int(x[0]), -quality_order.get(x[1], 0)))
                    print(f"Sorted season keys: {[x[0] for x in sorted_keys]}")
                    sorted_grouped_data = {key: grouped_data[key] for key in sorted_keys}
                    grouped_data = sorted_grouped_data
                    
                    if len(links) > 0 and len(postid) > 1:
                        data = serials_dlbox(grouped_data, postid)
                        with connection.cursor() as cursor:
                            sql_check_meta_post = """
                                SELECT COUNT(*) 
                                FROM wp_postmeta 
                                WHERE post_id = %s AND meta_key = %s
                            """
                            cursor.execute(sql_check_meta_post, (postid, 'series_dlbox'))
                            exists = cursor.fetchone()[0]

                            if exists:
                                sql_update_meta_post = """
                                    UPDATE wp_postmeta
                                    SET meta_value = %s
                                    WHERE post_id = %s AND meta_key = %s
                                """
                                cursor.execute(sql_update_meta_post, (str(data).replace("b'", "").replace("'", ""), postid, 'series_dlbox'))
                            else:
                                sql_insert_meta_post = """
                                    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                                    VALUES (%s, %s, %s)
                                """
                                cursor.execute(sql_insert_meta_post, (postid, 'series_dlbox', str(data).replace("b'", "").replace("'", "")))

                            connection.commit()
                            print(f"Updated series_dlbox for postid {postid}")  # دیباگ
                        
                        data = serials_playlinks(grouped_data)
                        with connection.cursor() as cursor:
                            sql_check_meta_post = """
                                SELECT COUNT(*) 
                                FROM wp_postmeta 
                                WHERE post_id = %s AND meta_key = %s
                            """
                            cursor.execute(sql_check_meta_post, (postid, 'series_playlinks'))
                            exists = cursor.fetchone()[0]

                            if exists:
                                sql_update_meta_post = """
                                    UPDATE wp_postmeta
                                    SET meta_value = %s
                                    WHERE post_id = %s AND meta_key = %s
                                """
                                cursor.execute(sql_update_meta_post, (str(data).replace("b'", "").replace("'", ""), postid, 'series_playlinks'))
                            else:
                                sql_insert_meta_post = """
                                    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                                    VALUES (%s, %s, %s)
                                """
                                cursor.execute(sql_insert_meta_post, (postid, 'series_playlinks', str(data).replace("b'", "").replace("'", "")))

                            connection.commit()
                            print(f"Updated series_playlinks for postid {postid}")  # دیباگ
    
    except Exception as e:
        print(f"Error in get_links_movie for imdb {imdb}, postid {postid}: {e}")
    
    finally:
        connection.close()