import requests
import pandas as pd
import json
import os
from django.conf import settings
import logging
logger = logging.getLogger("fpl_data")  # Get the logger for the current module

POSITIONS = {1:"GK",2:"DEF",3:"MID",4:"FWD",5:"MNG"}
FPL_API_URL = 'https://fantasy.premierleague.com/api/bootstrap-static/'
DATA_STORAGE_PATH = settings.FPL_DATA_FILE

def fetch_fpl_data():
    """
    Fetches data from the FPL API.  Handles errors and logs them.
    """
    try:
        response = requests.get(FPL_API_URL)
        response.raise_for_status()  # Raise an exception for bad status codes
        data = response.json()
        logger.info(f"FPL API response: {data}") 
        # Extracting teams and players data
        teams = data['teams']
        players = pd.json_normalize(data['elements'])
        # DATA PROCESSING
        players = players[players['can_select']]
        players['now_cost'] = players['now_cost'] / 10
        players['selected_by_percent'] = players['selected_by_percent'] +  " %"
        players['element_type'] = players['element_type'].map(lambda elem: POSITIONS[elem])
        players['team'] = players['team'].map(lambda team: teams[team-1]['name'])
        # Sorting players by total points and filtering
        leaderboard = players[['web_name','now_cost','form','selected_by_percent','element_type',"team","transfers_in_event","transfers_out_event",'total_points']].sort_values(by='total_points', ascending=False)
        # Renaming columns for better readability
        leaderboard = leaderboard.rename(columns={'web_name': 'Player Name', 'now_cost': 'Price', 'form': 'Form','selected_by_percent': 'Selection %','element_type':'Position','team':'Team','transfers_in_event': 'Transfers In','transfers_out_event': 'Transfers Out','total_points': 'Total Points'})
        # Converting the DataFrame to a list of dictionaries
        leaderboard = leaderboard.to_dict(orient='records')
        
        logger.info("FPL data fetched and updated successfully.")
        return leaderboard

    except requests.exceptions.RequestException as e:
        print(f"Error fetching FPL data: {e}")
        logger.error(f"Error decoding JSON: {e}")
        return None

    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        logger.error(f"An unexpected error occurred: {e}")
        return None


def save_fpl_data(data):
    """
    Saves the FPL data to a JSON file.  Handles errors and logs them.
    """
    if data is None:
        logger.warning("No data to save.")
        return

    try:
        # Ensure the directory exists
        os.makedirs(os.path.dirname(DATA_STORAGE_PATH), exist_ok=True) #make directory
        # Saving the data to a JSON file
        with open(DATA_STORAGE_PATH, 'w') as f:
            json.dump(data, f, indent=4)
        print("Data fetched and saved successfully.")
        logger.info("FPL data saved successfully.")
    except (IOError, OSError) as e:
        logger.error(f"Error saving FPL data to {DATA_STORAGE_PATH}: {e}")
    except TypeError as e:
        logger.error(f"Type error while saving FPL data: {e}")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")

def load_fpl_data():
    """
    Loads the FPL data from the JSON file.  Handles errors, logs them, and returns None on failure.
    """
    try:
        with open(DATA_STORAGE_PATH, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        logger.warning(f"FPL data file not found at {DATA_STORAGE_PATH}.  Returning None.")
        return None
    except json.JSONDecodeError:
        logger.error(f"Error decoding JSON from {DATA_STORAGE_PATH}.  Returning None.")
        return None
    except (IOError, OSError) as e:
        logger.error(f"Error reading FPL data from {DATA_STORAGE_PATH}: {e}")
        return None
    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return None

if __name__ == "__main__":
    """
    This block is only executed when this script is run directly (e.g., for testing).
    It's good practice to include such a block for testing purposes.
    """
    data = fetch_fpl_data()
    if data:
        save_fpl_data(data)
    else:
        print("Failed to fetch data.") 
