import json
import requests
import pandas as pd
from fantasy_data.services import load_gameweeks_data, load_fixtures_data,load_info
from django.conf import settings
import logging
FASTAPI_SERVICE_URL = "http://127.0.0.1:8002"
DREAM_TEAM_FOLDER = settings.DREAM_TEAM_FOLDER
 
logger = logging.getLogger("fpl_data") 
info = load_info()
def get_all_gameweeks_data():
    return load_gameweeks_data()

def get_gameweek_stats(id):
    data = load_gameweeks_data()
    
    return data[id - 1]

def get_gameweek_fixtures(id):
    data = load_fixtures_data()
    
    return [fix for fix in data if fix['event'] == id]
def get_gameweek_timeline():
    data = pd.DataFrame( load_gameweeks_data())
    next_gw = data[data['is_next']].iloc[0]
    return next_gw.to_dict()

def get_dream_teams():

    try:
        curr_gw = info["gw"] if info else 1
        if curr_gw == 1:
            raise Exception("Not Found")
        logger.info(f"current gw :  {curr_gw}  ")

        gw = curr_gw - 1
        ai_path = f"{DREAM_TEAM_FOLDER}ai_dream_team.json"
        dream_path = f"{DREAM_TEAM_FOLDER}actual_dream_team.json"
        with open(ai_path, "r") as f:
            ai_team = json.load(f)
        with open(dream_path, "r") as f:
            dream_team = json.load(f)
        ai_actual_score = 0
        ai_gw_team = ai_team[str(gw)]["team"]
        response = requests.get(f"{FASTAPI_SERVICE_URL}/gw_data/{gw}")

        player_gw_data = response.json()
        players_df =pd.json_normalize(player_gw_data)


        for i in range(len(ai_gw_team)):
            player_in_team = ai_gw_team[i]
            player = players_df[players_df['id'] == player_in_team["id"]]
            player_in_team["event_points"] = int(player["total_points"])
 #           logger.info(f" { player_in_team['web_name'] } scored { int(player['total_points'])} in  GW {gw}")
            ai_actual_score += int(player["total_points"])
#            logger.info(f"new score = {ai_actual_score}")
            ai_gw_team[i] = player_in_team 
        
        ai_team[str(gw)]["team"] =ai_gw_team
        ai_team[str(gw)]['total'] = ai_actual_score

        comparison = {}
        comparison["ai"] = ai_team[str(gw)]
        comparison["dream"] = dream_team[str(gw)]
        return comparison

    except:
        raise Exception("Not Found")