import requests
import time
from datetime import datetime, timedelta

# قاعدة URL لطلبات API
base_url = "https://www.sofascore.com/api/v1"

# جلب البيانات الحية للأحداث
def get_live_events():
    url = f"{base_url}/sport/football/events/live"
    response = requests.get(url)
    return response.json()

# جلب الأحداث الخاصة بمباراة معينة
def get_event_incidents(event_id):
    url = f"{base_url}/event/{event_id}/incidents"
    response = requests.get(url)
    return response.json()

# تحويل التوقيت إلى توقيت محلي باستخدام المنطقة الزمنية
def convert_to_local_time(utc_timestamp):
    local_time = datetime.utcfromtimestamp(utc_timestamp) + timedelta(hours=1)
    return local_time.strftime('%Y-%m-%d %H:%M:%S')

# عرض البيانات بشكل منظم
def display_live_data(events, displayed_incidents, start_time):
    for event in events.get('events', []):
        event_id = event.get('id', None)
        home_team = event.get('homeTeam', {})
        away_team = event.get('awayTeam', {})
        home_team_name = home_team.get('name', 'Unknown Team')
        home_team_score = home_team.get('score', '0')
        away_team_name = away_team.get('name', 'Unknown Team')
        away_team_score = away_team.get('score', '0')
        match_info = f"{home_team_name} {home_team_score} - {away_team_score} {away_team_name}"
        print(f"\n{match_info}")

        start_timestamp = event.get('startTimestamp', None)
        if start_timestamp:
            match_start_time = convert_to_local_time(start_timestamp)
        else:
            match_start_time = 'Unknown Start Time'
        print(f"🎉 Match started at: {match_start_time}")

        incidents = get_event_incidents(event_id)
        for incident in incidents.get('incidents', []):
            incident_id = incident.get('id', None)
            incident_time_seconds = incident.get('timeSeconds', 0)
            incident_time = datetime.utcfromtimestamp(start_timestamp + incident_time_seconds) if start_timestamp else None

            if incident_id and incident_id not in displayed_incidents and incident_time and incident_time >= start_time:
                displayed_incidents.add(incident_id)
                incident_type = incident.get('incidentType', 'Unknown Type')
                time_elapsed = incident.get('time', 'Unknown Time')

                if incident_type == 'goal':
                    player_name = incident.get('player', {}).get('name', 'Unknown Player')
                    print(f"🥅 Goal! {player_name} {time_elapsed}'")

                elif incident_type == 'card':
                    card_type = incident.get('incidentClass', 'Unknown Card').capitalize()  # Changed to incidentClass for card details
                    player_name = incident.get('player', {}).get('name', 'Unknown Player')
                    print(f"🟧 {card_type} Card! {player_name} {time_elapsed}'")
                
                elif incident_type == 'substitution':
                    player_in = incident.get('playerIn', {}).get('name', 'Unknown Player In')
                    player_out = incident.get('playerOut', {}).get('name', 'Unknown Player Out')
                    print(f"🔁 Substitution: {player_out} out, {player_in} in {time_elapsed}'")

                elif incident_type == 'injuryTime':
                    print(f"⏱️ Injury Time: {incident.get('length', 0)} minutes added at {time_elapsed}'")

                elif incident_type == 'period':
                    period_text = incident.get('text', 'Unknown Period')
                    print(f"⚽ Period: {period_text} ({time_elapsed}')")

        print("-" * 30)

# تشغيل السكريبت باستمرار
if __name__ == "__main__":
    displayed_incidents = set()
    start_time = datetime.utcnow()
    try:
        while True:
            live_events = get_live_events()
            display_live_data(live_events, displayed_incidents, start_time)
            print("\n--- Fetching updates in 60 seconds ---\n")
            time.sleep(10)  # الانتظار لمدة 60 ثانية قبل تحديث البيانات
    except KeyboardInterrupt:
        print("Script stopped by user.")  ارجو ان تعدل على هذا السكريبت بحيث لا يقوم بتكرار طباعه بدايه المباراه بوقتها وتصحيح الوقت الحقيقي لكل مباراه لانه يعرف اوقات خاطئه كذلك ارجو ان ينظم الاحداث ويجعلها اكثر وضوح استعمل ذكائك بحيث يعرضها مثل التي تكون في الصفحات لانه اخيرا في هذا سكريبت ساقوم بعد ذلك بتطويره ليقوم بالنشر مباشره في مواقع التواصل