from flask import Flask, jsonify, request
import mysql.connector
import requests

app = Flask(__name__)

# إعدادات الاتصال بقاعدة البيانات
db_config = {
    'user': 'xonegold_api',
    'password': 'ahmedxonegold@2712',
    'host': 'localhost',
    'database': 'xonegold_dramalive',
    'collation': 'utf8mb4_unicode_520_ci'
}

def log_message(message):
    print(message)

def fetch_and_store_series_data(total_pages):
    log_message("🔁 بدء جلب بيانات المسلسلات...")
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor()

    for page in reversed(range(total_pages)):
        log_message(f"📄 جلب الصفحة {page}")
        url = f'https://app.arabypros.com/api/poster/by/filtres/24/created/{page}/4F5A9C3D9A86FA54EACEDDD635185/d506abfd-9fe2-4b71-b979-feff21bcad13/'
        response = requests.get(url)
        series_data = response.json()

        for series in series_data:
            cursor.execute("""
                INSERT INTO series (id, title, description, year, imdb, rating, duration, classification, image, cover, trailer_url)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                ON DUPLICATE KEY UPDATE title=VALUES(title), description=VALUES(description), year=VALUES(year),
                imdb=VALUES(imdb), rating=VALUES(rating), duration=VALUES(duration), classification=VALUES(classification),
                image=VALUES(image), cover=VALUES(cover), trailer_url=VALUES(trailer_url)
            """, (
                series['id'],
                series['title'],
                series['description'],
                series['year'],
                series['imdb'],
                series['rating'],
                series['duration'],
                series['classification'],
                series['image'],
                series.get('cover', None),
                series.get('trailer', {}).get('url')
            ))

            # المواسم
            seasons_url = f'https://app.arabypros.com/api/season/by/serie/{series["id"]}/4F5A9C3D9A86FA54EACEDDD635185/d506abfd-9fe2-4b71-b979-feff21bcad13/'
            seasons = requests.get(seasons_url).json()

            for season in seasons:
                cursor.execute("""
                    INSERT INTO seasons (id, series_id, title)
                    VALUES (%s, %s, %s)
                    ON DUPLICATE KEY UPDATE title=VALUES(title)
                """, (
                    season['id'],
                    series['id'],
                    season['title']
                ))

                for episode in season.get('episodes', []):
                    cursor.execute("""
                        INSERT INTO episodes (id, season_id, title, description, duration)
                        VALUES (%s, %s, %s, %s, %s)
                        ON DUPLICATE KEY UPDATE title=VALUES(title), description=VALUES(description), duration=VALUES(duration)
                    """, (
                        episode['id'],
                        season['id'],
                        episode['title'],
                        episode['description'],
                        episode['duration']
                    ))

                    # روابط التشغيل للحلقة
                    sources_url = f'https://app.arabypros.com/api/episode/source/by/{episode["id"]}/4F5A9C3D9A86FA54EACEDDD635185/d506abfd-9fe2-4b71-b979-feff21bcad13/'
                    sources = requests.get(sources_url).json()

                    for source in sources:
                        cursor.execute("""
                            INSERT INTO episode_sources (id, episode_id, title, url, quality)
                            VALUES (%s, %s, %s, %s, %s)
                            ON DUPLICATE KEY UPDATE url=VALUES(url), quality=VALUES(quality)
                        """, (
                            source['id'],
                            episode['id'],
                            source['title'],
                            source['url'],
                            source['quality']
                        ))

        conn.commit()  # ✅ تخزين البيانات بعد كل صفحة

    log_message("✅ تمت عملية إدخال المسلسلات بالكامل.")
    cursor.close()
    conn.close()

def fetch_and_store_movie_data(total_pages):
    log_message("🔁 بدء جلب بيانات الأفلام...")
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor()

    for page in reversed(range(total_pages)):
        log_message(f"📄 جلب الصفحة {page}")
        url = f'https://app.arabypros.com/api/poster/by/filtres/1/created/{page}/4F5A9C3D9A86FA54EACEDDD635185/d506abfd-9fe2-4b71-b979-feff21bcad13/'
        response = requests.get(url)
        movie_data = response.json()

        for movie in movie_data:
            cursor.execute("""
                INSERT INTO movies (id, title, description, year, imdb, rating, duration, classification, image, cover, trailer_url)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                ON DUPLICATE KEY UPDATE title=VALUES(title), description=VALUES(description), year=VALUES(year),
                imdb=VALUES(imdb), rating=VALUES(rating), duration=VALUES(duration), classification=VALUES(classification),
                image=VALUES(image), cover=VALUES(cover), trailer_url=VALUES(trailer_url)
            """, (
                movie['id'],
                movie['title'],
                movie['description'],
                movie['year'],
                movie['imdb'],
                movie['rating'],
                movie['duration'],
                movie['classification'],
                movie['image'],
                movie.get('cover', None),
                movie.get('trailer', {}).get('url')
            ))

            # روابط التشغيل للفيلم
            sources_url = f'https://app.arabypros.com/api/movie/source/by/{movie["id"]}/4F5A9C3D9A86FA54EACEDDD635185/d506abfd-9fe2-4b71-b979-feff21bcad13/'
            sources = requests.get(sources_url).json()

            for source in sources:
                cursor.execute("""
                    INSERT INTO movie_sources (id, movie_id, title, url, quality)
                    VALUES (%s, %s, %s, %s, %s)
                    ON DUPLICATE KEY UPDATE url=VALUES(url), quality=VALUES(quality)
                """, (
                    source['id'],
                    movie['id'],
                    source['title'],
                    source['url'],
                    source['quality']
                ))

        conn.commit()  # ✅ تخزين البيانات بعد كل صفحة

    log_message("✅ تمت عملية إدخال الأفلام بالكامل.")
    cursor.close()
    conn.close()

@app.route('/start', methods=['GET'])
def start_fetching():
    movie_pages = int(request.args.get('movie_pages', 600))
    series_pages = int(request.args.get('series_pages', 85))
    fetch_and_store_series_data(series_pages)
    fetch_and_store_movie_data(movie_pages)
    return jsonify({"status": "تم جلب وتخزين البيانات بنجاح"}), 200

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