# utils/filemoon.py
import requests
import re
from urllib.parse import urljoin

# 🔴 استيراد من نفس المجلد (utils)
from .packer import cPacker
from .parser import cParser

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36"

def get_video_url(url):
    """استخراج رابط الفيديو من FileMoon"""
    url = url.replace('filemoon.sx', 'filemoon.in')
    
    headers = {"User-Agent": UA}
    oParser = cParser()
    
    try:
        # جلب الصفحة
        resp = requests.get(url, headers=headers, timeout=15)
        html = resp.text

        # البحث عن iframe
        pattern = r'<iframe[^>]*src=["\']([^"\']+)["\']'
        match = re.search(pattern, html)
        if match:
            iframe_url = match.group(1)
            if iframe_url.startswith("//"):
                iframe_url = "https:" + iframe_url

            iframe_headers = {"User-Agent": UA, "Referer": url}
            resp2 = requests.get(iframe_url, headers=iframe_headers, timeout=15)
            html = resp2.text

        # فك P.A.C.K.E.R
        pattern = r'(eval\(function\(p,a,c,k,e(?:.|\s)+?)</script>'
        matches = re.findall(pattern, html)
        
        for match in matches:
            html = cPacker().unpack(match)

        # البحث عن رابط m3u8
        patterns = [
            r'sources:\s*\[\s*{\s*file:\s*"([^"]+\.m3u8[^"]*)"',
            r'file:\s*"([^"]+\.m3u8[^"]*)"',
        ]
        
        for pattern in patterns:
            match = re.search(pattern, html, re.IGNORECASE)
            if match:
                return match.group(1)
        
        return None
        
    except Exception as e:
        raise Exception(f"Failed to extract video: {str(e)}")

def fix_query_params(url):
    """إصلاح معلمات الاستعلام بدون أسماء"""
    if '?=' not in url:
        return url
    
    parts = url.split('?')
    if len(parts) != 2:
        return url
    
    base = parts[0]
    query = parts[1]
    
    params = query.split('&')
    fixed = []
    
    names = ['t', 's', 'e', 'f', 'p']
    idx = 0
    
    for param in params:
        if param.startswith('='):
            value = param[1:]
            if idx < len(names):
                fixed.append(f"{names[idx]}={value}")
                idx += 1
            else:
                fixed.append(param)
        elif '=' in param:
            fixed.append(param)
        elif param:
            if idx < len(names):
                fixed.append(f"{names[idx]}={param}")
                idx += 1
    
    return f"{base}?{'&'.join(fixed)}"