# %%
PROJECT_PATH = '/home/md/Work/ligalytics/leagues_stable/'
import os, sys
sys.path.insert(0, PROJECT_PATH)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "leagues.settings")
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

from leagues import settings
settings.DATABASES['default']['NAME'] = PROJECT_PATH+'/db.sqlite3'

import django
django.setup()

from scheduler.models import *
from scheduler.helpers import *
from pulp import *
import csv


baseScenario = Scenario.objects.filter(season__nicename="UCL 24 - Imported Draws",name="BaseScenario")


# %%

teams = Team.objects.filter(season=baseScenario.season,active=True)

getTeamByID = {
    t.id:t for t in teams
}

getTeamIDByName = {
    t.name:t.id for t in teams
}
# %%

days = Day.objects.filter(season=baseScenario.season)



# %%
# import team positions
getTeamPos = {}
getTeamByPos = {}
with open('fred_team_ids.csv', newline='') as csvfile:    
        reader = csv.reader(csvfile)
        next(reader, None) 
        next(reader, None) 
        for row in reader:
            # team_name = row[2]
            if row[0] != "": 
                team_pos = row[0]
                team_name = row[1]
                getTeamPos[team_name] = team_pos
                getTeamByPos[int(team_pos)] = team_name
                

# %%

# import draws

current_draw = None
current_scenario = None
gamereqs = []                
sol_solution = ""
getTeamPos = {}
with open('fred_simulation.csv', newline='') as csvfile:    
        reader = csv.reader(csvfile)
        next(reader, None) 
        # next(reader, None) 
        for row in reader:
            # team_name = row[2]
            draw = row[0]
            if not current_draw or draw != current_draw:
                if current_scenario:        
                    current_scenario.name = "Fred: "+current_draw
                    current_scenario.sol_solution = sol_solution[:-2]   
                    current_scenario.save()   
                    GameRequirement.objects.filter(scenario=current_scenario).delete()
                    GameRequirement.objects.bulk_create(gamereqs)           
                    print("SAVED SCENARIO", current_scenario.name )                                      
                print("STARTING A NEW DRAW/SCENARIO", draw)
                current_draw = draw
                current_scenario = copy_scenario(baseScenario)
                sol_solution = ""
                gamereqs = []
                

            team_name = row[1]



            # sol_solution = 825_167_198_1_Late_None_None__
            team_matches = {}
            for md in range(1,9):
                team_matches[md] = int(row[3+md])

            for g,o in team_matches.items():
                if o > 0:
                    game_hometeam = getTeamIDByName[team_name]
                    game_awayteam = getTeamIDByName[getTeamByPos[abs(o)]]
                else:
                    game_awayteam = getTeamIDByName[team_name]
                    game_hometeam = getTeamIDByName[getTeamByPos[abs(o)]]
                game_round = g
                game_day = days.filter(round=g).first().id
                game_time = "Late"
                # if o < 0:
                #     print("\t\tA",g,getTeamByPos[abs(o)],getTeamIDByName[getTeamByPos[abs(o)]])                    
                # else:
                #     print("\t\tH",g,getTeamByPos[abs(o)],getTeamIDByName[getTeamByPos[abs(o)]])
                # # print("\t\t",game_round,game_day,game_time,game_hometeam,game_awayteam)
                sol_solution += "{}_{}_{}_{}_{}_None_None__".format(game_day,game_hometeam,game_awayteam,game_round,game_time)

                current_scenario.sol_solution = sol_solution
                team1 = getTeamByID[game_hometeam]
                team2 = getTeamByID[game_awayteam]
                gamereqs.append(GameRequirement(season=current_scenario.season,scenario=current_scenario,team1=team1,team2=team2,number=1))



if current_scenario:
    current_scenario.name = "Fred: "+current_draw
    current_scenario.sol_solution = sol_solution[:-2]   
    current_scenario.save()                                         
    GameRequirement.objects.filter(scenario=current_scenario).delete()
    GameRequirement.objects.bulk_create(gamereqs)      
    print("SAVED SCENARIO", current_scenario.name )     



# %%
