import re
import json
from flask import Flask, request, jsonify

app = Flask(__name__)

def parse_m3u_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    return content

def get_movie_info(content, movie_name):
    # Decode URL encoded movie_name
    movie_name = movie_name.replace('%20', ' ')
    # Regular expression to match movie info
    pattern = re.compile(r'#EXTINF:-1 tvg-id="" tvg-name="([^"]*%s[^"]*)"[^,]*,(.*)\n(.*)' % re.escape(movie_name))
    match = pattern.search(content)
    if match:
        return {
            "name": match.group(2),
            "url": match.group(3)
        }
    return None

def get_series_info(content, series_name):
    # Decode URL encoded series_name
    series_name = series_name.replace('%20', ' ')
    # Regular expression to match series info
    pattern = re.compile(r'#EXTINF:-1 tvg-id="" tvg-name="([^"]*%s[^"]* S(\d+) E(\d+))"[^,]*,(.*)\n(.*)' % re.escape(series_name))
    matches = pattern.findall(content)
    if matches:
        episodes = []
        for match in matches:
            episodes.append({
                "episode_name": match[3],
                "episode_order": int(match[2]),  # Extract episode number
                "url": match[4]
            })
        return episodes
    return None

@app.route('/go')
def m3u_go():
    content = parse_m3u_file('playlist.m3u')
    movie_name = request.args.get('movie_name')
    series_name = request.args.get('series_name')

    if movie_name:
        movie_info = get_movie_info(content, movie_name)
        if movie_info:
            return jsonify(movie_info)
        else:
            return jsonify({"error": "Movie not found"}), 404

    elif series_name:
        series_info = get_series_info(content, series_name)
        if series_info:
            return jsonify(series_info)
        else:
            return jsonify({"error": "Series not found"}), 404

    else:
        return jsonify({"error": "Invalid request"}), 400

if __name__ == '__main__':
    app.run(debug=True)
