import requests
import pandas as pd
from time import sleep

# مجموعة لتخزين الأحداث المطبوعة بالفعل لتجنب التكرار
printed_events = set()

def fetch_live_players(printed_events):
    fixtures_url = 'https://fantasy.premierleague.com/api/fixtures/'
    fixtures_response = requests.get(fixtures_url)

    players_url = 'https://fantasy.premierleague.com/api/bootstrap-static/'
    players_response = requests.get(players_url)

    if fixtures_response.status_code == 200 and players_response.status_code == 200:
        fixtures_data = fixtures_response.json()
        players_data = players_response.json()

        live_fixtures = [fixture for fixture in fixtures_data if not fixture['finished'] and fixture['started']]
        players_df = pd.DataFrame(players_data['elements'])
        teams_df = pd.DataFrame(players_data['teams'])

        if live_fixtures:
            for fixture in live_fixtures:
                event_id = fixture['event']
                live_url = f'https://fantasy.premierleague.com/api/event/{event_id}/live/'
                live_response = requests.get(live_url)

                if live_response.status_code == 200:
                    live_data = live_response.json()['elements']

                    for element in live_data:
                        element_info = players_df.loc[players_df['id'] == element['id']].iloc[0]
                        team_info = teams_df.loc[teams_df['id'] == element_info['team']].iloc[0]
                        player_name = element_info['web_name']
                        stats = element['stats']

                        # تحقق من الأهداف
                        if stats['goals_scored'] > 0:
                            event_key = f"{player_name}-goal-{stats['goals_scored']}"
                            if event_key not in printed_events:
                                printed_events.add(event_key)
                                print(f"Goal⚽: {player_name}, {team_info['name']}- P: {stats['goals_scored']*6}, Tot: {stats['total_points']}")

                        # تحقق من الأسيست
                        if stats['assists'] > 0:
                            event_key = f"{player_name}-assist-{stats['assists']}"
                            if event_key not in printed_events:
                                printed_events.add(event_key)
                                print(f"Assist🅰️: {player_name}, {team_info['name']}-  P: {stats['assists']*3}, Tot: {stats['total_points']}")

                        # تحقق من البطاقات الصفراء
                        if stats['yellow_cards'] > 0:
                            event_key = f"{player_name}-yellow-{stats['yellow_cards']}"
                            if event_key not in printed_events:
                                printed_events.add(event_key)
                                print(f"Yellow Card🟨: #{player_name}, #{team_info['name']}- P: -{stats['yellow_cards']*1}, Tot: {stats['total_points']}")

                        # تحقق من البطاقات الحمراء
                        if stats['red_cards'] > 0:
                            event_key = f"{player_name}-red-{stats['red_cards']}"
                            if event_key not in printed_events:
                                printed_events.add(event_key)
                                print(f"Red Card: {player_name}, {team_info['name']}, Event Points: -{stats['red_cards']*3}, Total Points: {stats['total_points']}")

    else:
        print('Failed to retrieve data.')

# نقطة بدء البرنامج
def main():
    while True:
        try:
            fetch_live_players(printed_events)
        except Exception as e:
            print(e)  # لدينا الآن الخطأ المطبوع في حال حدوث أي استثناء
        sleep(60)  # فترة الانتظار بين كل تحقق هي 60 ثانية

if __name__ == "__main__":
    main()