from pathlib import Path
import requests
from bs4 import BeautifulSoup
import re

def load_cookies():
    """خواندن کوکی از فایل logedin.txt"""
    cookie_file = Path('logedin.txt')
    if not cookie_file.exists():
        raise FileNotFoundError("Error: logedin.txt not found!")
    with cookie_file.open('r', encoding='utf-8') as f:
        return {'wordpress_logged_in_7a04687845b0293923d85c8b5afee67b': f.readline().strip()}

def setup_headers():
    """تنظیم هدرهای درخواست HTTP"""
    return {
        '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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
    }

def clear_output_file():
    """حذف فایل linkss2.txt اگر وجود داشته باشد"""
    output_file = Path('linkss2.txt')
    if output_file.exists():
        output_file.unlink()

def filter_links_by_quality(links, season, episode, quality, is_dubbed, is_series=True):
    """فیلتر کردن لینک‌ها (در صورت نیاز، الان فیلتر کیفیت غیرفعال است)"""
    return links[-1] if links else None

def scrape_mkv_links(id, name, imdb, cookies, headers):
    """اسکرپ کردن لینک‌های دانلود MKV/MP4 با حفظ کامل کوئری استرینگ"""
    url = f'https://hostinoo.lol/?p={id}'
    try:
        response = requests.get(url, cookies=cookies, headers=headers, timeout=20)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')

        output_lines = []

        # پیدا کردن تمام لینک‌های MKV/MP4 در کل صفحه (بدون .vtt)
        all_links = [
            a['href'] for a in soup.find_all('a', href=True)
            if any(x in a['href'] for x in ['.mkv', '.mp4'])
        ]

        for href in all_links:
            # استخراج فصل و اپیزود
            try:
                season = int(re.search(r'S(\d+)', href).group(1))
            except:
                season = 0
            try:
                episode = int(re.search(r'E(\d+)', href).group(1))
            except:
                episode = 0

            # لینک VTT خودکار (بدون کوئری استرینگ)
            vtt_link = href.split('.mkv')[0] + '.vtt' if '.mkv' in href else href.split('.mp4')[0] + '.vtt'

            output_lines.append(f"{id};{name};{episode};{season};{imdb};{vtt_link};{href}")


        if output_lines:
            with Path('linkss2.txt').open('a', encoding='utf-8') as f:
                for line in output_lines:
                    f.write(f"{line}\n")
            print(f"{len(output_lines)} links written for ID {id}")
        else:
            print(f"No links found for ID {id}")

    except requests.RequestException as e:
        print(f"Error loading /?p={id}: {e}")

def main():
    """تابع اصلی برای پردازش IDها و اسکرپ کردن لینک‌ها"""
    try:
        cookies = load_cookies()
        headers = setup_headers()
        clear_output_file()

        id_file = Path('zarfilm_ids_container.txt')
        if not id_file.exists():
            raise FileNotFoundError("Error: zarfilm_ids_container.txt not found!")

        with id_file.open('r', encoding='utf-8') as f:
            ids = [line.strip() for line in f if line.strip()]

        for id in ids:
            print(f"Processing ID: {id}")
            try:
                response = requests.get(f'https://hostinoo.lol/?p={id}', cookies=cookies, headers=headers, timeout=20)
                response.raise_for_status()
                soup = BeautifulSoup(response.text, 'html.parser')

                # نام سریال/فیلم
                name_tag = soup.find('h1', class_='entry-title') or soup.find('h1') or soup.find('title')
                name = name_tag.text.strip() if name_tag else f"دانلود {id}"
                name = re.sub(r'^(دانلود|فیلم|سریال)\s+', '', name, flags=re.IGNORECASE).strip()
                name = f"دانلود {name}" if not name.startswith('دانلود') else name

                # IMDb
                imdb_link = soup.find('a', href=re.compile(r'imdb.com/title/tt\d+'))
                imdb = re.search(r'tt\d+', imdb_link['href']).group() if imdb_link else 'tt0000000'

                scrape_mkv_links(id, name, imdb, cookies, headers)

            except requests.RequestException as e:
                print(f"Error loading /?p={id} for name and IMDb: {e}")

    except Exception as e:
        print(f"Unexpected error: {e}")

if __name__ == "__main__":
    main()
