import pymysql, time, requests, json  # اضافه کردن json
from .tt_scrapper import scrapper, add_background, scrapper_serial
import urllib.parse
from .add_crew import add_to_db
from multiprocessing import Pool
from .background import get_background
from collections import defaultdict
from .macher import get_links_movie
from .comments import comment_adder


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 tag_director(slug, postID, imdb_id):
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            check_slug_query = "SELECT term_id FROM wp_terms WHERE slug = %s"
            cursor.execute(check_slug_query, (slug,))
            result = cursor.fetchone()
            
            if result:
                term_id = result[0]
                check_term_taxonomy_query = "SELECT term_taxonomy_id, count FROM wp_term_taxonomy WHERE term_id = %s"
                cursor.execute(check_term_taxonomy_query, str(term_id))
                taxonomy_result = cursor.fetchone()
                if taxonomy_result:
                    term_taxonomy_id = taxonomy_result[0]
                    current_count = taxonomy_result[1]
                    new_count = current_count + 1
                    update_count_query = "UPDATE wp_term_taxonomy SET count = %s WHERE term_taxonomy_id = %s"
                    cursor.execute(update_count_query, (new_count, term_taxonomy_id))
                    sql_insert_meta = """
                    INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                    VALUES (%s, %s)
                    """
                    cursor.execute(sql_insert_meta, (str(postID), str(term_taxonomy_id)))
                    connection.commit()
            else:
                insert_term_query = """
                INSERT INTO wp_terms (name, slug, term_group) 
                VALUES (%s, %s, %s)
                """
                term_name = slug
                term_group = 0
                cursor.execute(insert_term_query, (term_name.replace('-', ' '), slug, term_group))
                new_term_id = cursor.lastrowid
                sql_insert_meta = """
                INSERT INTO wp_term_taxonomy (term_id, taxonomy, description, count)
                VALUES (%s, %s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (str(new_term_id), str('director'), '0', '0'))
                sql_insert_termmeta = """
                INSERT INTO wp_termmeta (term_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_termmeta, (str(postID), 'imdb_id', str(imdb_id)))
                sql_insert_meta = """
                INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                VALUES (%s, %s)
                """
                cursor.execute(sql_insert_meta, (str(postID), str(new_term_id)))
                connection.commit()
    except Exception as e:
        print(f"Error in tag_director for postID {postID}: {e}")
    finally:
        connection.close()


def tag_adder(slug, kind, postID):
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            decode = urllib.parse.quote(slug)
            print(decode)
            check_slug_query = "SELECT term_id FROM wp_terms WHERE slug = %s"
            cursor.execute(check_slug_query, (decode,))
            result = cursor.fetchone()
            if result:
                term_id = result[0]
                check_term_taxonomy_query = "SELECT term_taxonomy_id, count FROM wp_term_taxonomy WHERE term_id = %s"
                cursor.execute(check_term_taxonomy_query, (term_id,))
                taxonomy_result = cursor.fetchone()
                if taxonomy_result:
                    term_taxonomy_id = taxonomy_result[0]
                    current_count = taxonomy_result[1]
                    new_count = current_count + 1
                    update_count_query = "UPDATE wp_term_taxonomy SET count = %s WHERE term_taxonomy_id = %s"
                    cursor.execute(update_count_query, (new_count, term_taxonomy_id))
                    sql_insert_meta = """
                    INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                    VALUES (%s, %s)
                    """
                    cursor.execute(sql_insert_meta, (str(postID), str(term_taxonomy_id)))
                    connection.commit()
            else:
                insert_term_query = """
                INSERT INTO wp_terms (name, slug, term_group) 
                VALUES (%s, %s, %s)
                """
                term_name = slug
                term_name_decode = urllib.parse.quote(slug)
                term_group = 0
                cursor.execute(insert_term_query, (term_name, term_name_decode, term_group))
                new_term_id = cursor.lastrowid
                sql_insert_meta = """
                INSERT INTO wp_term_taxonomy (term_id, taxonomy, description, count)
                VALUES (%s, %s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (str(new_term_id), str(kind), '', '1'))
                new_term_id = cursor.lastrowid
                sql_insert_meta = """
                INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                VALUES (%s, %s)
                """
                cursor.execute(sql_insert_meta, (str(postID), str(new_term_id)))
                connection.commit()
    except Exception as e:
        print(f"Error in tag_adder for postID {postID}: {e}")
    finally:
        connection.close()


def tag_adder_sal(slug, postID):
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            decode = urllib.parse.quote(slug)
            check_slug_query = "SELECT term_id FROM wp_terms WHERE slug = %s"
            cursor.execute(check_slug_query, (decode,))
            result = cursor.fetchall()
            if result:
                xx = result[-1]
                term_id = xx[0]
                check_term_taxonomy_query = "SELECT term_taxonomy_id, count FROM wp_term_taxonomy WHERE term_id = %s"
                cursor.execute(check_term_taxonomy_query, (term_id,))
                taxonomy_result = cursor.fetchone()
                if taxonomy_result:
                    term_taxonomy_id = taxonomy_result[0]
                    current_count = taxonomy_result[1]
                    new_count = current_count + 1
                    update_count_query = "UPDATE wp_term_taxonomy SET count = %s WHERE term_taxonomy_id = %s"
                    cursor.execute(update_count_query, (new_count, term_taxonomy_id))
                    sql_insert_meta = """
                    INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                    VALUES (%s, %s)
                    """
                    cursor.execute(sql_insert_meta, (str(postID), str(term_taxonomy_id)))
                    connection.commit()
    except Exception as e:
        print(f"Error in tag_adder_sal for postID {postID}: {e}")
    finally:
        connection.close()


def add_crew_(post_id, response):
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            for couner, x in enumerate(response['cast']):
                try:
                    hashed = urllib.parse.quote(response['actorsList'])
                    id_imdb_cast = add_to_db(couner, hashed)
                    id_cast_in_db = "SELECT term_id FROM wp_termmeta WHERE meta_value = %s"
                    cursor.execute(id_cast_in_db, (id_imdb_cast,))
                    result_cast = cursor.fetchone()
                    if result_cast:
                        sql_insert_meta = """
                        INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                        VALUES (%s, %s)
                        """
                        cursor.execute(sql_insert_meta, (str(post_id), str(result_cast[0])))
                        connection.commit()
                except Exception as e:
                    print(f"Error adding crew for post_id {post_id}: {e}")
    except Exception as e:
        print(f"Error in add_crew_ for post_id {post_id}: {e}")
    finally:
        connection.close()


def import_movie(response, code_imdb, data_, type):
    print(data_['en_second'])
    post_author = 1
    post_title = str(response['title'])
    post_status = 'publish'
    post_type = type
    print(type)

    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = """
            INSERT INTO wp_posts (
                post_author, post_date, post_date_gmt, post_title, post_status, post_type, post_content, post_excerpt, to_ping, pinged, post_content_filtered
            ) VALUES (%s, NOW(), NOW(), %s, %s, %s, %s, '', '', '', '')
            """
            cursor.execute(sql, (post_author, post_title, post_status, post_type, data_['doble']))
            connection.commit()
            post_id = cursor.lastrowid
            update_sql = """
            UPDATE wp_posts 
            SET guid = %s, post_name = %s
            WHERE ID = %s
            """
            new_guid = f"https://seo2024.ir/?post_type=movies&p={post_id}"
            cursor.execute(update_sql, (new_guid, post_id, post_id))
            connection.commit()
            
            try:
                poster_name = str(str(response['main_poster']).split('/')[-1]).split('.jpg')[0]
                id_poster = "SELECT ID FROM wp_posts WHERE post_title = %s"
                cursor.execute(id_poster, (poster_name,))
                result_poster = cursor.fetchone()
                if result_poster:
                    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, '_thumbnail_id', str(result_poster[0])))
                    connection.commit()
            except Exception as e:
                print(f"Error setting thumbnail for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'fa_plot_movie', data_['plot']))
                connection.commit()
            except Exception as e:
                print(f"Error setting fa_plot_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'fa_title_movie', data_['fa_second_title']))
                connection.commit()
            except Exception as e:
                print(f"Error setting fa_title_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'runtime_movie', response['duration_time']))
                connection.commit()
            except Exception as e:
                print(f"Error setting runtime_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'metacritic_rate', response['score']))
                connection.commit()
            except Exception as e:
                print(f"Error setting metacritic_rate for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'age_movie', response['age']))
                connection.commit()
            except Exception as e:
                print(f"Error setting age_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'vote_movie', response['votes']))
                connection.commit()
            except Exception as e:
                print(f"Error setting vote_movie for post_id {post_id}: {e}")
            
            try:
                director_name = response['director']['names'][0] if isinstance(response['director']['names'], list) else response['director']['names'].get('name', '') if isinstance(response['director']['names'], dict) else ''
                if director_name:
                    sql_insert_meta = """
                    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                    VALUES (%s, %s, %s)
                    """
                    cursor.execute(sql_insert_meta, (post_id, 'director_movie', director_name))
                    connection.commit()
            except Exception as e:
                print(f"Error setting director_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'imdb_rate_movie', response['rating']))
                connection.commit()
            except Exception as e:
                print(f"Error setting imdb_rate_movie for post_id {post_id}: {e}")
            
            try:
                genre = data_['genre']
                genre = ','.join(genre)
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'genre_movie', genre))
                connection.commit()
            except Exception as e:
                print(f"Error setting genre_movie for post_id {post_id}: {e}")
            
            try:
                languages = data_['languages']
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'language_movie', languages))
                connection.commit()
            except Exception as e:
                print(f"Error setting language_movie for post_id {post_id}: {e}")
            
            if type == 'movies':
                try:
                    sql_insert_meta = """
                    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                    VALUES (%s, %s, %s)
                    """
                    cursor.execute(sql_insert_meta, (post_id, 'release_movie', str(data_['sal'])))
                    connection.commit()
                except Exception as e:
                    print(f"Error setting release_movie for post_id {post_id}: {e}")
                
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'title_movie', response['title']))
                connection.commit()
            except Exception as e:
                print(f"Error setting title_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'top250movie', response['top250']))
                connection.commit()
            except Exception as e:
                print(f"Error setting top250movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'en_plot_movie', response['en_plot_movie']))
                connection.commit()
            except Exception as e:
                print(f"Error setting en_plot_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'imdbid_movie', response['imdb_id']))
                connection.commit()
            except Exception as e:
                print(f"Error setting imdbid_movie for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'movie_update_text', data_['updates_line']))
                connection.commit()
            except Exception as e:
                print(f"Error setting movie_update_text for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'summary_awards', response['summary_awards']))
                connection.commit()
            except Exception as e:
                print(f"Error setting summary_awards for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, '_edit_lock', str(int(time.time())) + str(post_author)))
                connection.commit()
            except Exception as e:
                print(f"Error setting _edit_lock for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, '_edit_last', str(post_author)))
                connection.commit()
            except Exception as e:
                print(f"Error setting _edit_last for post_id {post_id}: {e}")
            
            try:
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'playonline_active', str('on')))
                connection.commit()
            except Exception as e:
                print(f"Error setting playonline_active for post_id {post_id}: {e}")
            
            try:
                fa_country = response['fa_country']
                fa_country = ','.join(fa_country)
                sql_insert_meta = """
                INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (post_id, 'country_movie', fa_country))
                connection.commit()
            except Exception as e:
                print(f"Error setting country_movie for post_id {post_id}: {e}")
            
            if type == 'movies':
                try:
                    for x in data_['genre']:
                        with open('importer/movies_mapper.txt', 'r', encoding="utf-8") as lines:
                            for line in lines:
                                if str(x).strip() == str(line.split(";")[0]).strip():
                                    sql_insert_meta = """
                                    INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                                    VALUES (%s, %s)
                                    """
                                    cursor.execute(sql_insert_meta, (str(post_id), str(str(line.split(";")[1]).strip())))
                                    connection.commit()
                except Exception as e:
                    print(f"Error setting movie genres for post_id {post_id}: {e}")
            
            if type == 'series':
                try:
                    for x in data_['genre']:
                        with open('importer/series_mapper.txt', 'r', encoding="utf-8") as lines:
                            for line in lines:
                                if str(x).strip() == str(line.split(";")[0]).strip():
                                    sql_insert_meta = """
                                    INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                                    VALUES (%s, %s)
                                    """
                                    cursor.execute(sql_insert_meta, (str(post_id), str(str(line.split(";")[1]).strip())))
                                    connection.commit()
                except Exception as e:
                    print(f"Error setting series genres for post_id {post_id}: {e}")
            
            try:
                for x in response['fa_country']:
                    try:
                        tag_adder(str(x), 'country', post_id)
                    except Exception as e:
                        print(f"Error adding country tag for post_id {post_id}: {e}")
            except Exception as e:
                print(f"Error processing fa_country for post_id {post_id}: {e}")
            
            try:
                try:
                    tag_adder_sal(str(data_['sal']), post_id)
                except Exception as e:
                    print(f"Error adding sal tag for post_id {post_id}: {e}")
            except Exception as e:
                print(f"Error processing sal for post_id {post_id}: {e}")
            
            try:
                tag_adder(data_['language'], 'language', post_id)
            except Exception as e:
                print(f"Error adding language tag for post_id {post_id}: {e}")
            
            try:
                director_names = response['director']['names'] if isinstance(response['director']['names'], list) else [response['director']['names']] if isinstance(response['director']['names'], dict) else []
                director_ids = response['director']['idimdb'] if isinstance(response['director']['idimdb'], list) else [response['director']['idimdb']] if response['director']['idimdb'] else []
                for count, x in enumerate(director_names):
                    name = x if isinstance(x, str) else x.get('name', '') if isinstance(x, dict) else ''
                    director_id = director_ids[count] if count < len(director_ids) else ''
                    if name:
                        try:
                            tag_director(name.lower().replace(' ', '-'), post_id, director_id)
                        except Exception as e:
                            print(f"Error adding director tag for post_id {post_id}: {e}")
            except Exception as e:
                print(f"Error processing directors for post_id {post_id}: {e}")
            
            try:
                for couner, x in enumerate(response['cast']):
                    hashed = urllib.parse.quote(response['actorsList'])
                    id_imdb_cast = add_to_db(couner, hashed)

                data = {
                    'post_id': post_id,
                    'actors': response['cast']
                }
                response2 = requests.post('https://seo2024.ir/wp-json/zarfilm/post/actors', json=data)
                
                try:
                    x = response2.json()

                except Exception as e:
                    print(' error actors')
                    print(response2.text)


                # for couner, x in enumerate(response['cast']):
                #     try:
                #         hashed = urllib.parse.quote(response['actorsList'])
                #         id_imdb_cast = add_to_db(couner, hashed)
                #         print('id_imdb_cast', id_imdb_cast)
                #         id_cast_in_db = "SELECT term_id FROM wp_termmeta WHERE meta_value = %s"
                #         cursor.execute(id_cast_in_db, (id_imdb_cast,))
                #         result_cast = cursor.fetchone()
                #         print(couner, id_imdb_cast, result_cast)

                #         if result_cast:
                #             sql_insert_meta = """
                #             INSERT INTO wp_term_relationships (object_id, term_taxonomy_id)
                #             VALUES (%s, %s)
                #             """
                #             cursor.execute(sql_insert_meta, (str(post_id), str(result_cast[0])))
                #             connection.commit()
                    # except Exception as e:
                        # print(f"Error adding cast for post_id {post_id}: {e}")
            except Exception as e:
                print(f"Error processing cast for post_id {post_id}: {e}")
            
            connection.commit()
            add = open('passed.txt', 'a')
            add.write(str(response['title']) + ';' + str(code_imdb) + '\n')
            add.close()
            
            get_links_movie(data_['imdb'], str(post_id))
            comment_adder(data_, str(post_id))
            
            return post_id
    
    except Exception as e:
        print(f"Error in import_movie for imdb {code_imdb}: {e}")
        return None
    
    finally:
        connection.close()


def adder_background(postId, bacgroundId):
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql_insert_meta = """
            INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
            VALUES (%s, %s, %s)
            """
            cursor.execute(sql_insert_meta, (postId, 'movie_thumb_bg', str(bacgroundId)))
            connection.commit()
    except Exception as e:
        print(f"Error in adder_background for postId {postId}: {e}")
    finally:
        connection.close()


def get_name(imdb):
    cookies = {
        '_ga': 'GA1.1.1790658831.1726349050',
        '_ga_CGBBXNR0VP': 'GS1.1.1726349050.1.1.1726349068.42.0.0',
    }
    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'en-US,en;q=0.9,fa;q=0.8',
        'cache-control': 'max-age=0',
        'priority': 'u=0, i',
        'sec-ch-ua': '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'none',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
    }
    params = {
        'i': str(imdb),
        'apikey': 'efa8d5ee',
    }
    try:
        response = requests.get('https://www.omdbapi.com/', params=params, cookies=cookies, headers=headers).json()
        if response.get('Response') == 'True' and 'Title' in response:
            return response['Title']
        else:
            return 'Unknown'
    except Exception as e:
        return 'Unknown'
# بقیه توابع importer.py بدون تغییر

import time
import requests
import json

def main_importer(data, imdb):
    print(f"DEBUG: main_importer started - imdb: {imdb}, data: {data}")

    # 1. چک وجود پست (این قسمت بدون تغییر)
    connection = get_db_connection()
    post_id = None
    try:
        with connection.cursor() as cursor:
            query = """
            SELECT post_id
            FROM wp_postmeta
            WHERE meta_key = 'imdbid_movie'
            AND meta_value = %s
            """
            cursor.execute(query, (imdb,))
            result = cursor.fetchone()
            post_id = result[0] if result else None
            print(f"DEBUG: Post exists check - post_id: {post_id}, imdb: {imdb}")
    finally:
        connection.close()

    if post_id:
        print(f"DEBUG: Post exists for IMDb {imdb} with post_id {post_id}, updating links")
        get_links_movie(imdb, str(post_id))
        return post_id

    # ───────────────────────────────────────────────
    # مهم‌ترین تغییر: تلاش چندباره برای scrapper_serial
    # ───────────────────────────────────────────────
    response = None
    max_attempts = 4
    backoff_seconds = [1.5, 2.5, 4.0]  # تأخیر بین تلاش‌ها

    for attempt in range(1, max_attempts + 1):
        try:
            print(f"DEBUG: تلاش {attempt}/{max_attempts} برای scrapper_serial → IMDb {imdb}")
            response = scrapper_serial(imdb)

            if isinstance(response, dict):
                if 'main_movietype' in response:
                    print(f"DEBUG: scrapper موفق در تلاش {attempt} → main_movietype: {response['main_movietype']}")
                    break
                else:
                    print(f"DEBUG: تلاش {attempt} → دیکشنری برگشت ولی کلید main_movietype وجود ندارد")
            else:
                print(f"DEBUG: تلاش {attempt} → پاسخ دیکشنری نیست → نوع: {type(response)}")

        except Exception as e:
            print(f"DEBUG: scrapper_serial خطا در تلاش {attempt}: {type(e).__name__} → {str(e)}")

        if attempt < max_attempts:
            sleep_time = backoff_seconds[attempt-1] if attempt-1 < len(backoff_seconds) else 5.0
            print(f"DEBUG: منتظر {sleep_time} ثانیه قبل از تلاش بعدی...")
            time.sleep(sleep_time)

    # اگر بعد از چند تلاش هنوز پاسخ معتبر نداریم → fallback
    if not response or not isinstance(response, dict) or 'main_movietype' not in response:
        print(f"DEBUG: scrapper_serial بعد از {max_attempts} تلاش موفق نشد → رفتن به fallback OMDB")
        response = None  # برای اطمینان

        try:
            omdb_response = requests.get(
                'https://www.omdbapi.com/',
                params={'i': imdb, 'apikey': 'efa8d5ee'},
                cookies={'_ga': 'GA1.1.1790658831.1726349050', '_ga_CGBBXNR0VP': 'GS1.1.1726349050.1.1.1726349068.42.0.0'},
                headers={
                    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
                    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
                },
                timeout=12
            ).json()

            print(f"DEBUG: OMDB status: {omdb_response.get('Response')}")

            if omdb_response.get('Response') == 'True':
                title = omdb_response.get('Title', 'Unknown')
                movietype = omdb_response.get('Type', 'movie').capitalize()
                type_ = 'series' if movietype in ['Series', 'TV Series'] else 'movies'

                genre = omdb_response.get('Genre', 'Unknown').split(', ') if omdb_response.get('Genre') else ['Unknown']
                country = omdb_response.get('Country', 'Unknown').split(', ') if omdb_response.get('Country') else ['Unknown']
                actors = omdb_response.get('Actors', 'Unknown')
                actors_list = [{'imdb': '', 'name': a.strip(), 'role': '', 'image': ''} for a in actors.split(', ') if a.strip()]

                response = {
                    'title': title,
                    'main_movietype': movietype,
                    'imdb_id': imdb,
                    'languages': [omdb_response.get('Language', 'Unknown')],
                    'en_genre': genre,
                    'fa_genre': genre,
                    'director': {'names': [omdb_response.get('Director', 'Unknown')], 'idimdb': ['']},
                    'cast': actors_list,
                    'actorsList': json.dumps(actors_list, ensure_ascii=False),
                    'en_country': country,
                    'fa_country': country,
                    'main_poster': omdb_response.get('Poster', ''),
                    'duration_time': omdb_response.get('Runtime', 'N/A'),
                    'rating': omdb_response.get('imdbRating', 'N/A'),
                    'votes': omdb_response.get('imdbVotes', '0'),
                    'age': omdb_response.get('Rated', 'Not Rated'),
                    'score': '0',
                    'summary_awards': '',
                    'top250': 0,
                    'en_plot_movie': omdb_response.get('Plot', 'No plot available'),
                    'fa_plot_movie': data.get('plot', 'بدون خلاصه داستان')
                }
            else:
                raise ValueError("OMDB Response False")

        except Exception as omdb_err:
            print(f"DEBUG: OMDB هم شکست خورد: {omdb_err}")
            # حداقل داده ممکن
            response = {
                'title': data.get('en_second', 'Unknown').replace('دانلود', '').strip(),
                'main_movietype': 'Movie',  # پیش‌فرض محافظه‌کارانه
                'imdb_id': imdb,
                'languages': ['Unknown'],
                'en_genre': ['Unknown'],
                'fa_genre': ['ناشناخته'],
                'director': {'names': ['Unknown'], 'idimdb': ['']},
                'cast': [],
                'actorsList': '[]',
                'en_country': ['Unknown'],
                'fa_country': ['ناشناخته'],
                'main_poster': '',
                'duration_time': 'N/A',
                'rating': 'N/A',
                'votes': '0',
                'age': 'Not Rated',
                'score': '0',
                'summary_awards': '',
                'top250': 0,
                'en_plot_movie': 'No plot available',
                'fa_plot_movie': data.get('plot', 'بدون خلاصه داستان')
            }

    # اگر هنوز response نداریم → خارج شو
    if not response:
        print("DEBUG: هیچ response معتبری دریافت نشد. خروج.")
        return None

    print(f"DEBUG: Response main_movietype نهایی: {response.get('main_movietype', 'نامشخص')}")

    # تعیین نوع پست
    main_type = response.get('main_movietype', '').strip()

    if main_type in ['Movie', 'TV Movie', 'Video', 'Short', 'TV Episode', 'TV Short', 'TV Special', 'Unknown']:
        type_ = 'movies'
    elif main_type in ['TV Series', 'Series', 'TVSeries', 'TV Mini Series']:
        type_ = 'series'
    else:
        # اگر نوع نامشخص بود، از داده‌های OMDB یا پیش‌فرض استفاده کن
        type_ = 'movies'   # یا 'series' بسته به سیاست سایتت

    print(f"DEBUG: نوع تشخیص داده شده → {type_}")

    # آماده‌سازی نهایی و import
    try:
        response['title'] = str(data.get('en_second', 'Unknown')).replace('دانلود', '').strip()
        response['imdb_id'] = imdb

        print(f"DEBUG: شروع import_movie → type: {type_}")
        post_id = import_movie(response, imdb, data, type_)

        if not post_id:
            print(f"DEBUG: import_movie شکست خورد برای IMDb {imdb}")
            return None

        print(f"DEBUG: add_crew_ برای post_id {post_id}")
        add_crew_(post_id, response)

        # اگر background فعال است، اینجا فعالش کن
        # url = get_background(imdb)
        # if url:
        #     background_id = add_background(url, post_id)
        #     adder_background(post_id, background_id)

        print(f"DEBUG: با موفقیت ایمپورت شد → IMDb {imdb} → post_id {post_id}")
        return post_id

    except Exception as e:
        print(f"DEBUG: خطا در مرحله نهایی ایمپورت IMDb {imdb}: {type(e).__name__} → {str(e)}")
        return None