import requests
import pandas as pd

# روابط API لجلب البيانات
bootstrap_url = "https://fantasy.premierleague.com/api/bootstrap-static/"
fixtures_url = "https://fantasy.premierleague.com/api/fixtures/"

# جلب البيانات الأساسية
try:
    bootstrap_response = requests.get(bootstrap_url)
    bootstrap_response.raise_for_status()
    bootstrap_data = bootstrap_response.json()
except requests.RequestException as e:
    print(f"Error fetching bootstrap data: {e}")
    exit()

# جلب بيانات المباريات
try:
    fixtures_response = requests.get(fixtures_url)
    fixtures_response.raise_for_status()
    fixtures_data = fixtures_response.json()
except requests.RequestException as e:
    print(f"Error fetching fixtures data: {e}")
    exit()

# استخراج معلومات الفرق واللاعبين والجولة الحالية
teams_df = pd.DataFrame(bootstrap_data['teams'])
players_df = pd.DataFrame(bootstrap_data['elements'])
events_df = pd.DataFrame(bootstrap_data['events'])

# تحديد الجولة الحالية
current_event = events_df[events_df['is_current'] == True]

if not current_event.empty:
    event_id = current_event.iloc[0]['id']
    event_name = current_event.iloc[0]['name']
    print(f"نتائج الجولة الجارية: {event_name}")

    # جلب بيانات الإحصائيات الخاصة بالجولة الجارية
    event_data_url = f'https://fantasy.premierleague.com/api/event/{event_id}/live/'
    try:
        event_response = requests.get(event_data_url)
        event_response.raise_for_status()
        event_data = event_response.json()
    except requests.RequestException as e:
        print(f"Error fetching event data: {e}")
        exit()

    # تحضير بيانات اللاعبين في الجولة الجارية
    player_stats = []
    for player in event_data['elements']:
        try:
            player_info = players_df[players_df['id'] == player['id']].iloc[0]
            stats = player['stats']

            player_info_dict = {
                'name': player_info['web_name'],
                'team': teams_df[teams_df['id'] == player_info['team']].iloc[0]['name'],
                'goals': stats.get('goals_scored', 0),
                'assists': stats.get('assists', 0),
                'points': stats.get('total_points', 0)
            }
            player_stats.append(player_info_dict)
        except (KeyError, IndexError):
            continue

    # تحويل البيانات إلى DataFrame لعرضها
    stats_df = pd.DataFrame(player_stats)

    # تحضير بيانات المباريات
    match_results = []
    for match in fixtures_data:
        if match['event'] == event_id:
            try:
                result = {
                    'home_team': teams_df.loc[match['team_h']]['name'],
                    'away_team': teams_df.loc[match['team_a']]['name'],
                    'home_goals': match['team_h_score'],
                    'away_goals': match['team_a_score'],
                    'finished': match['finished'],
                }
                match_results.append(result)
            except KeyError:
                continue

    # تحويل بيانات المباريات إلى DataFrame
    results_df = pd.DataFrame(match_results)

    # عرض النتائج الجارية بالتنسيق المطلوب
    if not results_df.empty:
        for index, match in results_df.iterrows():
            print(f"{match['home_team']} {match['home_goals']}-{match['away_goals']} {match['away_team']}")
            match_players = stats_df[(stats_df['team'] == match['home_team']) | (stats_df['team'] == match['away_team'])]
            for i, player in match_players.iterrows():
                if player['goals'] > 0 or player['assists'] > 0:
                    if player['goals'] > 0:
                        print(f"⚽️ : {player['name']} ({player['points']} pts)")
                    if player['assists'] > 0:
                        print(f"🅰 : {player['name']} ({player['points']} pts)")
            # إضافة الهاشتاجات لكل مباراة بشكل منفصل
            home_team_abbr = match['home_team'][:3].upper()
            away_team_abbr = match['away_team'][:3].upper()
            print(f"#FPL #GW{event_id} #{home_team_abbr}{away_team_abbr}")
    else:
        print("لا توجد نتائج متاحة للجولة الجارية.")
else:
    print("لا توجد جولة جارية حالياً.")          نتائج الجولة الجارية: Gameweek 15
Bournemouth 1.0-0.0 Spurs
#FPL #GW15 #BOUSPU
Brighton 4.0-2.0 Nott'm Forest
🅰 : Anderson (5 pts)
⚽️ : Gibbs-White (13 pts)
🅰 : Gibbs-White (13 pts)
🅰 : Hudson-Odoi (5 pts)
⚽️ : Wood (8 pts)
⚽️ : Milenković (7 pts)
#FPL #GW15 #BRINOT
Everton 2.0-2.0 Man Utd
🅰 : Amad (5 pts)
⚽️ : B.Fernandes (9 pts)
🅰 : Garnacho (4 pts)
⚽️ : Højlund (6 pts)
#FPL #GW15 #EVEMAN
Newcastle 2.0-3.0 Southampton
⚽️ : Barnes (7 pts)
⚽️ : Isak (8 pts)
🅰 : J.Murphy (7 pts)
#FPL #GW15 #NEWSOU
Ipswich nan-nan Aston Villa
⚽️ : Duran (8 pts)
#FPL #GW15 #IPSAST
Leicester nan-nan Brentford
⚽️ : Collins (7 pts)
🅰 : Flekken (3 pts)
⚽️ : Mbeumo (13 pts)
🅰 : Mbeumo (13 pts)
🅰 : Nørgaard (5 pts)
⚽️ : Schade (6 pts)
⚽️ : Wissa (7 pts)
#FPL #GW15 #LEIBRE
Liverpool nan-nan Chelsea
#FPL #GW15 #LIVCHE
West Ham nan-nan Crystal Palace
🅰 : Hughes (11 pts)                                                ⚽️ : Muñoz (7 pts)                                                 ⚽️ : Lacroix (7 pts)                                               #FPL #GW15 #WESCRY                                                 
[Program finished]  انظر هذا سكريبيا يعرض في بعض الاحيان نتائج مبهمه وكذلك يقوم بالتكرار ارجو ان تصححه تصحيحا متقنا وباحترافيه