import pandas as pd
import os
import requests
from fantasy_data.services import load_players_data

PLAYER_SUMMARY_URL = 'https://fantasy.premierleague.com/api/element-summary/'
def get_players_data():
    players =  pd.DataFrame(load_players_data())
    players = players[players['can_select']]
    players = players.sort_values(by=['total_points'], ascending=False)
    
    return players.to_dict(orient='records')
def get_unavailable_players_data():
    players =  pd.DataFrame(load_players_data())
    players = players[players['status'].isin(['i','s'])]
    players = players.sort_values(by=['status','total_points'], ascending=[True,False])
    return players.to_dict(orient='records')
def get_player_stats(id):
    data= load_players_data()  
    return data[id - 1]
def get_player_history(id):
    url = PLAYER_SUMMARY_URL + str(id) + "/"
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes
        data = response.json()
        # next_fixtures = data['fixtures']
        # history = pd.DataFrame(data['history'])
        # history.fillna(-1.0, inplace=True)
        # history = history.loc[:, ~history.columns.isin(['round'])]
        return data
    except requests.exceptions.RequestException as e:
        print(f"Error fetching player stats: {e}")
        return None