from flask import Flask, request, jsonify
from bs4 import BeautifulSoup
import requests
import re

app = Flask(__name__)

# إعداد جلسة (Session) لطلبات HTTP
session = requests.Session()

def search_series_links(series_name):
    base_url = "https://anafasts.com:2096"
    search_url = f"{base_url}/?op=search&k={series_name}"
    
    # استخدام الجلسة (Session) لإرسال الطلب
    response = session.get(search_url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.content, "html.parser")
        videoboxes = soup.find_all("div", class_="videobox")
        episodes_links = []
        
        for videobox in videoboxes:
            link = videobox.find("a", class_="title")["href"]
            episode_name = videobox.find("a", class_="title").text.strip()
            episode_number_match = re.search(r"S\d+E(\d+)", episode_name)
            
            if episode_number_match:
                episode_number = int(episode_number_match.group(1))
            else:
                episode_number = None
            
            episodes_links.append({
                "episode_name": episode_name,
                "episode_order": episode_number,
                "url": link
            })
        
        episodes_links.sort(key=lambda x: x["episode_order"] if x["episode_order"] is not None else float('inf'))
        return episodes_links
    else:
        return []

@app.route('/go', methods=['GET'])
def go():
    series_name = request.args.get('series_name')
    if not series_name:
        return jsonify({"error": "Missing 'series_name' parameter"}), 400
    
    data = search_series_links(series_name)
    return jsonify(data)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)
