# %%
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"
import random
import time

# XPRESS ENVIRONMENT
os.environ['XPRESSDIR'] = "/opt/xpressmp_8.4"
os.environ['XPRESS'] = "/opt/xpressmp_8.4/bin"
os.environ['LD_LIBRARY_PATH'] = os.environ['XPRESSDIR']+"/lib:"+os.environ['LD_LIBRARY_PATH']
os.environ['DYLD_LIBRARY_PATH'] = os.environ['XPRESSDIR']+"/lib:"
os.environ['SHLIB_PATH'] = os.environ['XPRESSDIR']+"/lib:"
os.environ['LIBPATH'] = os.environ['XPRESSDIR']+"/lib:"
# os.environ['PYTHONPATH'] =os.environ['XPRESSDIR']+"/lib:"+os.environ['PYTHONPATH']
os.environ['PYTHONPATH'] =os.environ['XPRESSDIR']+"/lib:"
os.environ['CLASSPATH'] =os.environ['XPRESSDIR']+"/lib/xprs.jar:"
os.environ['CLASSPATH'] =os.environ['XPRESSDIR']+"/lib/xprb.jar:"+os.environ['CLASSPATH']
os.environ['CLASSPATH'] =os.environ['XPRESSDIR']+"/lib/xprm.jar:"+os.environ['CLASSPATH']
os.environ['PATH'] =os.environ['XPRESSDIR']+"/bin:"+os.environ['PATH']


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

import django
django.setup()

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




scenario = Scenario.objects.get(id=34)

# %%

order = {}

order['FC Bayern München'] = 1
order['Manchester City FC'] = 2
order['Liverpool FC'] = 3
order['Real Madrid CF'] = 4
order['Chelsea FC'] = 5
order['FC Barcelona'] = 6
order['Paris Saint-Germain'] = 7
order['Juventus'] = 8
order['Club Atlético de Madrid'] = 9
order['Sevilla FC'] = 10
order['RB Leipzig'] = 11
order['Tottenham Hotspur'] = 12
order['AFC Ajax'] = 13
order['FC Porto'] = 14
order['Arsenal FC'] = 15
order['Borussia Dortmund'] = 16
order['FC Salzburg'] = 17
order['FC Shakhtar Donetsk'] = 18
order['FC Internazionale Milano'] = 19
order['SSC Napoli'] = 20
order['Eintracht Frankfurt'] = 21
order['SL Benfica'] = 22
order['Sporting Clube de Portugal'] = 23
order['Bayer 04 Leverkusen'] = 24
order['Rangers FC'] = 25
order['GNK Dinamo'] = 26
order['FK Crvena zvezda'] = 27
order['Olympique de Marseille'] = 28
order['F.C. Copenhagen'] = 29
order['Club Brugge'] = 30
order['AC Milan'] = 31
order['PSV Eindhoven'] = 32
order['Celtic FC'] = 33
order['FC Viktoria Plzeň'] = 34
order['AS Monaco'] = 35
order['Maccabi Haifa FC'] = 36







# %%


teams = Team.objects.filter(season=scenario.season,active=True).order_by('pot','country')


countries = list(set(list(teams.values_list('country', flat=True))))


# print(countries)


# %%


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

getPotByID = {
    t.id:t.pot for t in teams
}

getTeamByName = {
    t.name:t for t in teams
}

getCountryByTeamID = {
    t.id:t.country for t in teams
}




played_countries = {
    (t1, c):0 for c in countries for t1 in teams
}
random_played_countries = {
    (t1, c):0 for c in countries for t1 in teams
}
stats = {
    (t1,t2):0 for t1 in teams for t2 in teams
}
random_stats = {
    (t1,t2):0 for t1 in teams for t2 in teams
}


pots = {
    t1:{
        p:0 for p in range(1,5)
    }
    for t1 in teams
}
simulations_undirected = 0
simulations_directed = 0
maxVal = 1
minVal = 99999999
maxCVal = 1
minCVal = 9999999
maxRVal = 1
minRVal = 9999999
maxCRVal = 1
minCRVal = 9999999

old_c = "START"
for i in range(16):
    with open(f'thread_{i}_pot_by_pot.csv', newline='') as csvfile:    
    # with open('verteilung_random.csv', newline='') as csvfile:    
        reader = csv.reader(csvfile)
        next(reader, None) 
        for row in reader:
            if int(row[0]) != old_c:
                old_c = int(row[0])
                simulations_undirected +=1

            team = getTeamByID[int(row[1])]
            Aopps = [getTeamByID[int(t)] for t in row[2].split(";")][:2]
            for o in Aopps:
                stats[team,o] += 1
                pots[team][getPotByID[o.id]] += 1
                played_countries[team,o.country] += 1
            Bopps = [getTeamByID[int(t)] for t in row[2].split(";")][2:4]
            for o in Bopps:
                stats[team,o] += 1
                pots[team][getPotByID[o.id]] += 1
                played_countries[team,o.country] += 1
            Copps = [getTeamByID[int(t)] for t in row[2].split(";")][4:6]
            for o in Copps:
                stats[team,o] += 1
                pots[team][getPotByID[o.id]] += 1
                played_countries[team,o.country] += 1
            Dopps = [getTeamByID[int(t)] for t in row[2].split(";")][6:]
            for o in Dopps:
                stats[team,o] += 1
                pots[team][getPotByID[o.id]] += 1
                played_countries[team,o.country] += 1
            
            if stats[team,o] > maxVal:
                maxVal = stats[team,o]
        
            if played_countries[team,o.country] > maxCVal:
                maxCVal = played_countries[team,o.country]

# with open(f'test.csv', newline='') as csvfile:    
# # with open('verteilung_random.csv', newline='') as csvfile:    
#     reader = csv.reader(csvfile)
#     next(reader, None) 
#     for row in reader:
#         if int(row[0]) != old_c:
#             old_c = int(row[0])
#             simulations_undirected +=1

#         team = getTeamByID[int(row[1])]
#         Aopps = [getTeamByID[int(t)] for t in row[2].split(";")][:2]
#         for o in Aopps:
#             stats[team,o] += 1
#             pots[team][getPotByID[o.id]] += 1
#             played_countries[team,o.country] += 1
#         Bopps = [getTeamByID[int(t)] for t in row[2].split(";")][2:4]
#         for o in Bopps:
#             stats[team,o] += 1
#             pots[team][getPotByID[o.id]] += 1
#             played_countries[team,o.country] += 1
#         Copps = [getTeamByID[int(t)] for t in row[2].split(";")][4:6]
#         for o in Copps:
#             stats[team,o] += 1
#             pots[team][getPotByID[o.id]] += 1
#             played_countries[team,o.country] += 1
#         Dopps = [getTeamByID[int(t)] for t in row[2].split(";")][6:]
#         for o in Dopps:
#             stats[team,o] += 1
#             pots[team][getPotByID[o.id]] += 1
#             played_countries[team,o.country] += 1
        
#         if stats[team,o] > maxVal:
#             maxVal = stats[team,o]
    
#         if played_countries[team,o.country] > maxCVal:
#             maxCVal = played_countries[team,o.country]

# %%




# old_c = "START"

# # with open('verteilung_draw.csv', newline='') as csvfile:    
# with open('draw_options_HA_2country.csv', newline='') as csvfile:    
#     reader = csv.reader(csvfile)
#     next(reader, None) 
#     for row in reader:
#         if int(row[0]) != old_c:
#             old_c = int(row[0])
#             simulations_directed +=1


#         team = getTeamByID[int(row[1])]
#         Aopps = [getTeamByID[int(t)] for t in row[2].split(";")][:1]
#         for o in Aopps:
#             random_stats[team,o] += 1
#             # pots[team][getPotByID[o.id]] += 1
#             random_played_countries[team,o.country] += 1
#         Bopps = [getTeamByID[int(t)] for t in row[2].split(";")][2:3]
#         for o in Bopps:
#             random_stats[team,o] += 1
#             # pots[team][getPotByID[o.id]] += 1
#             random_played_countries[team,o.country] += 1
#         Copps = [getTeamByID[int(t)] for t in row[2].split(";")][4:5]
#         for o in Copps:
#             random_stats[team,o] += 1
#             # pots[team][getPotByID[o.id]] += 1
#             random_played_countries[team,o.country] += 1
#         Dopps = [getTeamByID[int(t)] for t in row[2].split(";")][6:7]
#         for o in Dopps:
#             random_stats[team,o] += 1
#             # pots[team][getPotByID[o.id]] += 1
#             random_played_countries[team,o.country] += 1

#         if random_stats[team,o] > maxRVal:
#             maxRVal = random_stats[team,o]


#         if random_played_countries[team,o.country] > maxCRVal:
#             maxCRVal = random_played_countries[team,o.country]


diff = {}
mindval = 999999
maxdval = 0
# simulations_undirected = 1
simulations_directed = 1

for key in random_stats.keys():
    diff[key] = stats[key]/simulations_undirected - 2*random_stats[key]/simulations_directed
    if diff[key] > maxdval:
        maxdval = diff[key]
    if diff[key] > 0 and diff[key] < mindval:
        mindval = diff[key]



for key, val in stats.items():
    if val > 0 and val < minVal:
        minVal = val


for key, val in random_stats.items():
    if val > 0 and val < minRVal:
        minRVal = val


for key, val in played_countries.items():
    if val > 0 and val < minCVal:
        minCVal = val


for key, val in random_played_countries.items():
    if val > 0 and val < minCRVal:
        minCRVal = val



# for t in pots:
#     print(t,pots[t])


def heatmap_color_for(value):
    if value <= 0.5:
        g = 256
        r = 2 * max(0,value) * 256
    if value > 0.5:
        g = 2*(1-min(1,value))*256
        r = 256
    return f"rgb({r},{g},{0})"



sol = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">'
sol += " \
<style>     \
    table, th, td {     \
            border: 1px solid black;     \
            border-collapse: collapse;     \
            text-align: center;     \
            min-width:40px;     \
            padding:3px;     \
            margin: 3px;     \
            font-family : Arial;\
    }     \
    h1 {\
        font-family : Arial;\
    }\
\
    #etable td:nth-child(10),#etable th:nth-child(10) { border-right: 5px solid black; }\
    #etable td:nth-child(19),#etable th:nth-child(19) { border-right: 5px solid black; }\
    #etable td:nth-child(28),#etable th:nth-child(28) { border-right: 5px solid black; }\
    tr:nth-child(9) { border-bottom: 5px solid black; }\
    tr:nth-child(18) { border-bottom: 5px solid black; }\
    tr:nth-child(27) { border-bottom: 5px solid black; }\
</style> \
"
sol += "</head><body>"
sol += "<h1>Probabilities of games - undirected vs directed</h1>"
sol += "<ul><li>Table 1: Probability of two teams to be drawn against each other (symmetric)</li>"
sol += "<li>Table 2: Probability of a home or away encounter (asymmetric)</li>"
sol += "<li>Table 3: Difference of the two options from above. Moving from undirected to directed</li></ul>"
sol += "Each options data is based on approximately 5000 random draws. Both options are restricted to at most 2 opponents from the same country."
sol += "<hr>"
sol += "<h2>Table 1: Probabilities of games - undirected</h2>"
sol += "Home/Away games are assigned in the calendar phase, therefore this table is symmetric."
sol += "<table id='etable' style='border:5px solid black'>\n"
sol += "<thead>\n"
sol += "<tr>"
sol += f"<th>{simulations_undirected}</th>"
sol += "<th colspan=9 style='border-right: 5px solid black;'>Pot A</th>"
sol += "<th colspan=9 style='border-right: 5px solid black;'>Pot B</th>"
sol += "<th colspan=9 style='border-right: 5px solid black;'>Pot C</th>"
sol += "<th colspan=9>Pot D</th>"
sol += "</tr>"
sol += "<tr>\n"
sol += f"<th></th>\n"
# for o in order:
for t in teams:
    # t = getTeamByName[o]
    sol += f"<th>({t.country}) {t.shortname}</th>\n"
sol += "</tr>\n"
sol += "</thead>\n"
sol += "<tbody>\n"
# for o1 in order:
for t1 in teams:
    # t1 = getTeamByName[o1]
    sol += "<tr>\n"
    sol += f"<td>({t1.country}) {t1.shortname}</td>"
    # for o2 in order:
    for t2 in teams:
        # t2 = getTeamByName[o2]
        color = heatmap_color_for((stats[t1,t2]-minVal)/((maxVal-minVal) or 1))
        if stats[t1,t2] == 0:
            color = 'grey'
        val = f"{round(round(stats[t1,t2]/simulations_undirected,2)*100)}%"
        # val = stats[t1,t2]
        sol += f"<td style='background-color:{color}'>{val}</td>"
    sol += "</tr>\n"

sol += "</tbody>\n"
sol += "</table>\n"

sol += "<br>"
sol += "<br>"
sol += "<br>"
sol += "<hr>"

sol += "<h2>Table 2: Probabilities of games - directed</h2>"
sol += "Home/Away games are assigned during the draw, therefore this table is asymmetric."
sol += "<table id='etable' style='border:5px solid black'>\n"
sol += "<thead>\n"
sol += "<tr>"
sol += "<th></th>"
sol += "<th colspan=9 style='border-right: 5px solid black;'>Pot A</th>"
sol += "<th colspan=9 style='border-right: 5px solid black;'>Pot B</th>"
sol += "<th colspan=9 style='border-right: 5px solid black;'>Pot C</th>"
sol += "<th colspan=9>Pot D</th>"
sol += "</tr>"
sol += "<tr>\n"
sol += f"<th></th>\n"
# for o in order:
for t in teams:
    # t = getTeamByName[o]
    sol += f"<th>({t.country}) {t.shortname}</th>\n"
sol += "</tr>\n"
sol += "</thead>\n"
sol += "<tbody>\n"
# for o1 in order:
for t1 in teams:
    # t1 = getTeamByName[o1]
    sol += "<tr>\n"
    sol += f"<td>({t1.country}) {t1.shortname}</td>"
    # for o2 in order:
    for t2 in teams:
        # t2 = getTeamByName[o2]
        color = heatmap_color_for((random_stats[t1,t2]-minRVal)/((maxRVal-minRVal) or 1))
        if random_stats[t1,t2] == 0:
            color = 'grey'
        val = f"{round(round(random_stats[t1,t2]/simulations_directed,2)*100)}%"
        # val = stats[t1,t2]
        sol += f"<td style='background-color:{color}'>{val}</td>"
    sol += "</tr>\n"

sol += "</tbody>\n"
sol += "</table>\n"


sol += "<br>"
sol += "<br>"
sol += "<br>"
sol += "<hr>"

sol += "<h2>Table 3: Difference of probabilities (moving from undirected to directed)</h2>"
sol += "<table style='border:5px solid black'>\n"
sol += "<thead>\n"
sol += "<tr>\n"
sol += f"<th></th>\n"
# for o in order:
for t in teams:
    # t = getTeamByName[o]
    sol += f"<th>({t.country}) {t.shortname}</th>\n"
sol += "</tr>\n"
sol += "</thead>\n"
sol += "<tbody>\n"
# for o1 in order:
for t1 in teams:
    # t1 = getTeamByName[o1]
    sol += "<tr>\n"
    sol += f"<td>({t1.country}) {t1.shortname}</td>"
    # for o2 in order:
    for t2 in teams:
        # t2 = getTeamByName[o2]
        color = heatmap_color_for((abs(diff[t1,t2])-mindval)/((maxdval-mindval) or 1))
        if stats[t1,t2] == 0:
            color = 'grey'
        val = f"{diff[t1,t2]}%"
        # val = stats[t1,t2]
        sol += f"<td style='background-color:{color}'>{round(round(diff[t1,t2],2)*100)}%</td>"
    sol += "</tr>\n"

sol += "</tbody>\n"
sol += "</table>\n"

# sol += "<br>"
# sol += "<br>"
# sol += "<br>"
# sol += "<hr>"

# sol += "<h2>Average number of games against other countries - undirected</h2>"
# sol += "<table style='border:5px solid black'>\n"
# sol += "<thead>\n"
# sol += "<tr>"
# sol += "<tr>\n"
# sol += f"<th></th>\n"
# for c in countries:
#     sol += f"<th>{c}</th>\n"
# sol += "</tr>\n"
# sol += "</thead>\n"
# sol += "<tbody>\n"
# # for o1 in order:
# for t1 in teams:
#     # t1 = getTeamByName[o1]
#     sol += "<tr>\n"
#     sol += f"<td>{t1.shortname}</td>"
#     for c in countries:        
#         # color = heatmap_color_for((played_countries[t1,c]-minCVal)/(maxCVal-minCVal))
#         color = 'lightsteelblue'
#         if played_countries[t1,c] == 0:
#             color = 'grey'
#         # val = f"{round(round(played_played_countries[t1][c]/simulations,2)*100)}%"
#         val = f"{round(played_countries[t1,c]/(simulations_undirected),2)}"
#         # val = stats[t1,t2]
#         sol += f"<td style='background-color:{color}'>{val}</td>"
#     sol += "</tr>\n"

# sol += "</tbody>\n"
# sol += "</table>\n"


# sol += "<br>"
# sol += "<br>"
# sol += "<br>"
# sol += "<hr>"

# sol += "<h2>Average number of games against other countries - directed</h2>"
# sol += "<table style='border:5px solid black'>\n"
# sol += "<thead>\n"
# sol += "<tr>"
# sol += "<tr>\n"
# sol += f"<th></th>\n"
# for c in countries:
#     sol += f"<th>{c}</th>\n"
# sol += "</tr>\n"
# sol += "</thead>\n"
# sol += "<tbody>\n"
# # for o1 in order:
# for t1 in teams:
#     # t1 = getTeamByName[o1]
#     sol += "<tr>\n"
#     sol += f"<td>{t1.shortname}</td>"
#     for c in countries:        
#         # color = heatmap_color_for((played_countries[t1,c]-minCVal)/(maxCVal-minCVal))
#         color = 'lightsteelblue'
#         if random_played_countries[t1,c] == 0:
#             color = 'grey'
#         # val = f"{round(round(played_played_countries[t1][c]/simulations,2)*100)}%"
#         val = f"{round(random_played_countries[t1,c]/(simulations_directed),2)}"
#         # val = stats[t1,t2]
#         sol += f"<td style='background-color:{color}'>{val}</td>"
#     sol += "</tr>\n"

sol += "</tbody>\n"
sol += "</table>\n"



with open(f'probabilities.html', 'w') as f:
    f.write(sol)







# %%
