import re
import m3u8
import requests
import schedule
import time
import os
from flask import Flask, jsonify, request

app = Flask(__name__)

# رابط ملف M3U
m3u_url = "http://556677.ovh:25461/get.php?username=mz5oov2d&password=ruyu4pn5&type=m3u_plus"
m3u_filename = "playlist.m3u"

def download_m3u():
    # تحميل الملف
    response = requests.get(m3u_url)
    with open(m3u_filename, 'wb') as file:
        file.write(response.content)
    print(f"تم تحديث ملف {m3u_filename} بنجاح!")

def delete_old_m3u():
    if os.path.exists(m3u_filename):
        os.remove(m3u_filename)
        print(f"تم حذف ملف {m3u_filename} القديم.")

def update_m3u():
    delete_old_m3u()
    download_m3u()

# جدولة تحديث الملف كل 24 ساعة
schedule.every(24).hours.do(update_m3u)

@app.route('/m3u')
def get_m3u_data():
    channels = parse_m3u()
    return jsonify(channels)

def parse_m3u():
    playlist = m3u8.load(m3u_filename)
    channels = []
    for segment in playlist.segments:
        channels.append({
            'title': segment.title,
            'uri': segment.uri
        })
    return channels

@app.route('/go')
def search_m3u():
    movie_name = request.args.get('movie_name')
    series_name = request.args.get('series_name')

    if movie_name:
        return search_movie(movie_name)

    if series_name:
        return search_series(series_name)

    return jsonify({"error": "يرجى تحديد إما movie_name أو series_name"})

def search_movie(movie_name):
    playlist = m3u8.load(m3u_filename)
    for segment in playlist.segments:
        if movie_name in segment.title:
            return jsonify({
                'name': segment.title,
                'url': segment.uri
            })
    return jsonify({"error": "لم يتم العثور على الفيلم"})

def search_series(series_name):
    playlist = m3u8.load(m3u_filename)
    episodes = []
    for segment in playlist.segments:
        if series_name in segment.title:
            match = re.search(r'S(\d{2}) E(\d{2})', segment.title)
            if match:
                season_number = match.group(1)
                episode_number = match.group(2)
                episodes.append({
                    'episode_name': segment.title,
                    'episode_order': int(episode_number),
                    'url': segment.uri
                })
    if episodes:
        return jsonify(episodes)
    return jsonify({"error": "لم يتم العثور على المسلسل"})

if __name__ == "__main__":
    # تشغيل التطبيق في الوضع المحلي
    app.run(debug=True, port=5000)
