# %%
import requests
import json
from collections import defaultdict

prod_url = 'https://uefadigitalapi.developer.azure-api.net'
prod_primary_key = '9b849959b7aa40b9b1f966254c22fc6e'
prod_secondary_key = '116b2865175141e6955e6c83fe4651ae'
pre_url = 'https://uefadigitalapipre.developer.azure-api.net'
pre_primary_key = 'b6bdd59422614fa9932c03fb16666067'
pre_secondary_key = '4e61efa534f94f38a4c96ba9bc00f444'

# %%

competitionId = 1 # Champions League
seasonYear = 2025



# %%



"""" FINISHED GAMES """


uefa_match_url = f"https://api.digital.uefa.com/match/v5/matches?offset=0&limit=500&order=DESC&competitionId={competitionId}&seasonYear={seasonYear}&seasonsRange=ALL&&phase=ALL"
headers = {"Cache-Control":"no-cache","Ocp-Apim-Subscription-Key":prod_primary_key}
res = requests.get(uefa_match_url, headers=headers)
finished_json = res.json()

# # %%


# %%
"""
Match live score
Try it 
Provide details about the score of a collection of matches given a number of conditions.
"""


# uefa_match_url = f"https://api.digital.uefa.com/match/v5/livescore&competitionId={competitionId}"
# headers = {"Cache-Control":"no-cache","Ocp-Apim-Subscription-Key":prod_primary_key}
# res = requests.get(uefa_match_url, headers=headers)
# res.json()



# %%

standings = defaultdict(lambda: defaultdict(lambda:0))
upcoming = []

for game in finished_json:
    if game['round']['metaData']['name'] != 'League Phase':
        continue
    
    matchday = game['matchday']['name']
    homeTeam = game['homeTeam']['teamCode']
    awayTeam = game['awayTeam']['teamCode']
    
    if homeTeam not in standings:
        standings[homeTeam]['external_id'] = game['homeTeam']['id']    
        standings[homeTeam]['name'] = game['homeTeam']['internationalName']    
        standings[homeTeam]['country'] = game['homeTeam']['countryCode']    
    if awayTeam not in standings:
        standings[awayTeam]['external_id'] = game['awayTeam']['id']
        standings[awayTeam]['name'] = game['awayTeam']['internationalName']
        standings[awayTeam]['country'] = game['awayTeam']['countryCode']
        
    if game['status'] == "FINISHED":
        homeScore = game['score']['total']['home']
        awayScore = game['score']['total']['away']
        
        standings[homeTeam]['games_played'] += 1
        standings[awayTeam]['games_played'] += 1
        standings[homeTeam]['goals_scored'] += homeScore
        standings[awayTeam]['goals_scored'] += awayScore
        standings[homeTeam]['goals_conceded'] += awayScore
        standings[awayTeam]['goals_conceded'] += homeScore
        standings[homeTeam]['goal_difference'] += homeScore - awayScore
        standings[awayTeam]['goal_difference'] += awayScore - homeScore
        if homeScore > awayScore:
            standings[homeTeam]['wins'] += 1
            standings[awayTeam]['losses'] += 1
            standings[homeTeam]['points'] += 3
        elif awayScore > homeScore:
            standings[awayTeam]['wins'] += 1
            standings[homeTeam]['losses'] += 1
            standings[awayTeam]['points'] += 3
        else:
            standings[homeTeam]['draws'] += 1
            standings[awayTeam]['draws'] += 1
            standings[homeTeam]['points'] += 1
            standings[awayTeam]['points'] += 1
        
    else:
        kickoff = game['kickOffTime']['dateTime']
        upcoming.append((matchday,kickoff,homeTeam,awayTeam))
        
    
standings = dict(sorted(standings.items(), key=lambda x: (x[1]['points'],x[1]['goal_difference'],x[1]['goals_scored']), reverse=True))
upcoming = sorted(upcoming, key=lambda x: (x[0],x[1]))
    
# %%

