import os
import json
from players.serializers import PlayerSerializer
from players.models import Player, PlayerStats
from django.db import transaction
from players.choices import POSITION_CHOICES, TEAM_CHOICES

def get_players_data():
    file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', 'players_data.json')

    with open(file_path, 'r') as f:
        players_data = json.load(f)

    # Filter for active players
    active_players_data = {player_id: player for player_id, player in players_data.items() 
                           if player.get('status') == 'Active'
                           and player.get('age') != None
                           and player.get('search_rank') != None
                           and player.get('search_rank') < 310
                           and player.get('position') in [position[0] for position in POSITION_CHOICES]
                           and player.get('team') in [team[0] for team in TEAM_CHOICES]}
    
    return active_players_data


def update_players_db(players_data):
    # Get the list of all player_id in players_data
    players_ids = [pid for pid in players_data.keys()]

    # Update or create players from players_data
    for player_id, player_data in players_data.items():
        try:
            player_instance = Player.objects.filter(player_id=player_id).first()
            serializer = PlayerSerializer(instance=player_instance, data=player_data)

            if serializer.is_valid():
                if player_instance:
                    serializer.update(player_instance, serializer.validated_data)
                else:
                    serializer.create(serializer.validated_data)
            else:
                print(f"Serializer is not valid for player_id {player_id}: {serializer.errors}")  # Add this line to print errors
        except Exception as e:
            print(e)

    try:
        # Delete players that are not in players_data
        Player.objects.exclude(player_id__in=players_ids).delete()
    except Exception as e:
        print(e)


def update_player_stats(player_id, stats):
    player = Player.objects.get(player_id=player_id)
    season_year = stats['season_year']
    week = stats['week']

    # Try to get an existing PlayerStats instance with the given player, season_year, and week
    player_stats, created = PlayerStats.objects.update_or_create(
        player=player,
        season_year=season_year,
        week=week,
        defaults=stats,
    )

    if created:
        print(f'Successfully created PlayerStats instance for player {player_id}, season year {season_year}, and week {week}.')
    else:
        print(f'Successfully updated PlayerStats instance for player {player_id}, season year {season_year}, and week {week}.')