import requests
import re
import pymysql.cursors
import os
from concurrent.futures import ThreadPoolExecutor
import time
from urllib.parse import urlparse, urlunparse

# کش لینک‌ها
existing_links = set()
try:
    with open('trailers/trailer.txt', 'r', encoding='utf-8') as file:
        existing_links = set(line.strip() for line in file)
except FileNotFoundError:
    pass

# کش برای لینک‌های تریلر
trailer_cache = {}

def combine_files():
    base_path = os.path.join(os.path.dirname(__file__), '..', 'importer')
    zarids_path = os.path.join(base_path, 'zarids.txt')
    imovieids_path = os.path.join(base_path, 'imovieids.txt')
    clean_path = 'trailers/clean.txt'
    
    # حالا clean_lines رو عیناً کامل می‌خونیم (کل خط)
    clean_lines = set()
    try:
        with open(clean_path, 'r', encoding='utf-8') as clean_file:
            for line in clean_file:
                stripped = line.strip()
                if stripped:
                    clean_lines.add(stripped)
        print(f"Loaded {len(clean_lines)} lines from clean.txt for exact filtering")
    except FileNotFoundError:
        print(f"Warning: {clean_path} not found, proceeding without filtering")
    
    # دیکشنری برای مچ کردن zarid با imdb
    id_to_imdb = {}
    try:
        with open(imovieids_path, 'r', encoding='utf-8') as f:
            for line in f:
                stripped = line.strip()
                if stripped and ';' in stripped:
                    local_id, imdb = stripped.split(';', 1)
                    id_to_imdb[local_id.strip()] = imdb.strip()
    except FileNotFoundError:
        print(f"Warning: {imovieids_path} not found")
    
    try:
        with open('trailers/passed.txt', 'w', encoding='utf-8') as output_file:
            # zarids.txt → می‌سازیم zarfilm:ID;imdb
            try:
                with open(zarids_path, 'r', encoding='utf-8') as input_file:
                    for line in input_file:
                        zarid = line.strip()
                        if not zarid:
                            continue
                        imdb = id_to_imdb.get(zarid, '')
                        if imdb:
                            full_line = f"zarfilm:{zarid};{imdb}"
                        else:
                            full_line = f"zarfilm:{zarid};"
                        
                        if full_line not in clean_lines:
                            output_file.write(full_line + "\n")
            except FileNotFoundError:
                print(f"Warning: {zarids_path} not found")
            
            # imovieids.txt → می‌سازیم imoviee:ID;imdb
            try:
                with open(imovieids_path, 'r', encoding='utf-8') as input_file:
                    for line in input_file:
                        stripped = line.strip()
                        if not stripped:
                            continue
                        full_line = f"imoviee:{stripped}"
                        if full_line not in clean_lines:
                            output_file.write(full_line + "\n")
            except FileNotFoundError:
                print(f"Warning: {imovieids_path} not found")
                
    except Exception as e:
        print(f"Error writing to trailers/passed.txt: {e}")
        
def save_link(url):
    try:
        existing_links.add(url)
        with open('trailers/trailer.txt', 'a', encoding='utf-8') as file:
            file.write(url + "\n")
    except Exception as e:
        print(f"Error saving link {url}: {e}")

def check_link_exists(url):
    return url in existing_links

def link_trailer(id):
    if id in trailer_cache:
        return trailer_cache[id]

    base_path = os.path.join(os.path.dirname(__file__), '..')
    logedin_path = os.path.join(base_path, 'logedin.txt')

    try:
        with open(logedin_path, 'r', encoding='utf-8') as logedin_file:
            cookie_value = logedin_file.read().strip()
    except FileNotFoundError:
        print(f"Error: {logedin_path} not found")
        return ''
    except Exception as e:
        print(f"Error reading {logedin_path}: {e}")
        return ''

    cookies = {
        'wordpress_logged_in_7a04687845b0293923d85c8b5afee67b': cookie_value,
    }

    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',
        'Connection': 'keep-alive',
        '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/131.0.0.0 Safari/537.36',
        'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
    }

    try:
        response = requests.get('https://zhomis.info/play/' + str(id) + '/trailer/', cookies=cookies, headers=headers)
        response.raise_for_status()
        
        link = re.findall(r'https:(.*?\.mp4.*?)["\']', response.text)
        if not link:
            print(f"No trailer link found for ID: {id}")
            return ''
        
        original_link = 'https:' + link[0]
        print(f"Original link for debugging: {original_link}")
        
        if check_link_exists(original_link):
            print(f"Link already exists: {original_link}")
            return ''
        
        path = '/'.join(original_link.split('/')[3:])
        path_parts = path.split('/')
        if len(path_parts) >= 2:
            second_last_part = path_parts[-2]
            if second_last_part.startswith('%20'):
                path_parts[-2] = second_last_part[3:]
            path = '/'.join(path_parts)
        
        new_link = f'https://dlmanager2.ir/zr/trailers/{path}'
        
        save_link(original_link)
        trailer_cache[id] = new_link
        print(f"New trailer link: {new_link}")
        return new_link

    except requests.RequestException as e:
        print(f"Error fetching trailer for ID {id}: {e}")
        return ''
    except Exception as e:
        print(f"Unexpected error processing trailer for ID {id}: {e}")
        return ''
    
def update_trailer(imdb_id, link):
    if not link:
        return
    
    parsed = urlparse(link)
    cleaned_path = parsed.path
    if cleaned_path.startswith('/zr/trailers/'):
        cleaned_path = cleaned_path[len('/zr/trailers/'):]
    cleaned_link = f'https://dlmanager2.ir/zr/trailers/{cleaned_path}'

    connection = pymysql.connect(
        host='127.0.0.1',
        user='sql_seo2024_ir',
        password='1bd0d20735dfd8',
        database='sql_seo2024_ir',
        cursorclass=pymysql.cursors.DictCursor
    )
    try:
        with connection.cursor() as cursor:
            sql = "SELECT post_id FROM wp_postmeta WHERE meta_key = %s AND meta_value = %s"
            cursor.execute(sql, ('imdbid_movie', imdb_id))
            meta = cursor.fetchone()

            if meta:
                sql = "SELECT meta_id FROM wp_postmeta WHERE post_id = %s AND meta_key = %s"
                cursor.execute(sql, (meta['post_id'], 'trailer_movie'))
                postmeta_result = cursor.fetchone()
                
                if postmeta_result:
                    sql = "UPDATE wp_postmeta SET meta_value = %s WHERE meta_id = %s"
                    cursor.execute(sql, (cleaned_link, postmeta_result['meta_id']))
                else:
                    sql = "INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES (%s, %s, %s)"
                    cursor.execute(sql, (meta['post_id'], 'trailer_movie', cleaned_link))
        
        connection.commit()
        print(f"Updated trailer for IMDb ID {imdb_id} with link: {cleaned_link}")
    
    except pymysql.MySQLError as e:
        print(f"Database error for IMDb ID {imdb_id}: {e}")
    except Exception as e:
        print(f"Error updating trailer for IMDb ID {imdb_id}: {e}")
    finally:
        connection.close()

def process_line(line):
    try:
        line = line.strip()
        if not line:
            return
        
        if ';' not in line:
            print(f"Invalid format (no ;): {line}")
            return
        
        source_part, rest = line.split(';', 1)
        parts = rest.split(';')
        imdb_id = parts[0].strip() if parts else ''
        
        if not imdb_id:
            print(f"No IMDb ID found in line: {line}")
            return
        
        if source_part.startswith('zarfilm:'):
            zhomis_id_str = source_part[len('zarfilm:'):]
            try:
                zhomis_id = int(zhomis_id_str.strip())
            except ValueError:
                print(f"Invalid zarfilm ID: {zhomis_id_str}")
                return
            
            link = link_trailer(zhomis_id)
            if link:
                update_trailer(imdb_id, link)
                
    except Exception as e:
        print(f"Error processing line '{line}': {e}")
        # Main execution
try:
    combine_files()
    with open('trailers/passed.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        with ThreadPoolExecutor(max_workers=10) as executor:
            executor.map(process_line, lines)
except Exception as e:
    print(f"Critical error in main execution: {e}")