from flask import Flask, request, jsonify, render_template, send_file
from flask_cors import CORS
from extractor import extract
import os
import traceback

APP_DIR = "/var/www/html/Extract"

# Movies
M3U_FILE = os.path.join(APP_DIR, "playlist.m3u")
JSON_FILE = os.path.join(APP_DIR, "playlist.json")

# Series
SERIES_M3U_FILE = os.path.join(APP_DIR, "series_list.m3u")
SERIES_JSON_FILE = os.path.join(APP_DIR, "series_list.json")

app = Flask(__name__)
CORS(app)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/health")
def health():
    return jsonify({
        "ok": True,
        "status": "online",
        "service": "ALRAQI Extractor",
        "port": 9393
    })


@app.route("/extract")
def do_extract():
    url = request.args.get("url", "").strip()

    if not url:
        return jsonify({
            "ok": False,
            "error": "Missing url"
        }), 400

    try:
        result = extract(url)

        if isinstance(result, dict):
            best = result.get("best")

            if isinstance(best, dict):
                best_choice = dict(best)
                best_choice["user_agent"] = best.get(
                    "useragent",
                    best.get("userAgent", "")
                )
                result["bestChoice"] = best_choice

        return jsonify(result)

    except Exception as e:
        return jsonify({
            "ok": False,
            "error": str(e),
            "traceback": traceback.format_exc()
        }), 500


# ---------------- Movies ----------------

@app.route("/playlist.m3u")
def playlist():
    if not os.path.exists(M3U_FILE):
        return "#EXTM3U\n", 200, {
            "Content-Type": "audio/x-mpegurl; charset=utf-8"
        }

    return send_file(
        M3U_FILE,
        mimetype="audio/x-mpegurl",
        as_attachment=False
    )


@app.route("/playlist.json")
def playlist_json():
    if not os.path.exists(JSON_FILE):
        return jsonify([])

    return send_file(
        JSON_FILE,
        mimetype="application/json",
        as_attachment=False
    )


# ---------------- Series ----------------

@app.route("/series_list.m3u")
def series_playlist():
    if not os.path.exists(SERIES_M3U_FILE):
        return "#EXTM3U\n", 200, {
            "Content-Type": "audio/x-mpegurl; charset=utf-8"
        }

    return send_file(
        SERIES_M3U_FILE,
        mimetype="audio/x-mpegurl",
        as_attachment=False
    )


@app.route("/series_list.json")
def series_playlist_json():
    if not os.path.exists(SERIES_JSON_FILE):
        return jsonify([])

    return send_file(
        SERIES_JSON_FILE,
        mimetype="application/json",
        as_attachment=False
    )


if __name__ == "__main__":
    app.run(
        host="0.0.0.0",
        port=9393,
        debug=False,
        threaded=True
    )