# %%
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'
# settings.DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
# settings.DATABASES['default']['HOST'] = '0.0.0.0'
# settings.DATABASES['default']['PORT'] = '5432'
# settings.DATABASES['default']['USER'] = 'postgres'
# settings.DATABASES['default']['PASSWORD'] = 'secret123'
# settings.DATABASES['default']['NAME'] = 'mypgsqldb'
# settings.DATABASES['default']['ATOMIC_REQUESTS'] = False
# settings.DATABASES['default']['AUTOCOMMIT'] = True
# settings.DATABASES['default']['CONN_MAX_AGE'] = 0
# settings.DATABASES['default']['CONN_HEALTH_CHECKS'] = False
# settings.DATABASES['default']['OPTIONS'] = {}


os.environ["XPRESSDIR"] = "/opt/xpressmp"
os.environ["XPRESS"] = "/opt/xpressmp/bin"
os.environ["LD_LIBRARY_PATH"] = os.environ["XPRESSDIR"] + "/lib"
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["CLASSPATH"] = os.environ["XPRESSDIR"] + "/lib/xprs.jar"
os.environ["CLASSPATH"] = os.environ["XPRESSDIR"] + "/lib/xprb.jar" + os.pathsep + os.environ["CLASSPATH"]
os.environ["CLASSPATH"] = os.environ["XPRESSDIR"] + "/lib/xprm.jar" + os.pathsep + os.environ["CLASSPATH"]
os.environ["PATH"] = os.environ["XPRESSDIR"] + "/bin" + os.pathsep + os.environ["PATH"]

import django
django.setup()

from django.shortcuts import HttpResponseRedirect
from django.http import HttpResponse, JsonResponse
from django.utils import timezone
from django.urls import reverse
from django.core.files.storage import FileSystemStorage
from django.core.mail import send_mail
from django_tex.shortcuts import render_to_pdf

from celery.result import AsyncResult
import googlemaps
import timeit
import random
import json
import builtins as __builtin__
import csv

from leagues.celery import celery
from leagues.settings import EMAIL_DEFAULT_FROM, EMAIL_DEFAULT_TO
from leagues.settings import RUN_ENV, INSTANCE, DEBUG
from common.tasks import log_telegram
from common.functions import *
from scheduler.models import *
from scheduler.helpers import *
from scheduler.widgets import widget_context_kpis
from scheduler.solver.optimizer import optimize_2phases, optimize_sequentially
import scheduler.solver.optimizer as so
from draws.solver import optimize_draws

import time as timer

from qualifiers.helpers import import_globals



# %%

scenario = Scenario.objects.get(id=3)
# import_globals(scenario.season.id)
# teams = scenario.season.scheduler_teams.all()




# %%

new_teams = []
new_teams.append(("Pot 1",	1,	"Tottenham Hotspur (ENG)",	80.000,                             5,5          ))
new_teams.append(("Pot 1",	2,	"Eintracht Frankfurt (GER)",	77.000,                        5,5               ))
new_teams.append(("Pot 1",	3,	"Club Brugge (BEL)", 	54.000,                      2,5                 ))
new_teams.append(("Pot 1",	4,	"FC Basel 1893 (SUI)",	53.000,                         3,5              ))
new_teams.append(("Pot 1",	5,	"KAA Gent (BEL)", 	37.500,                               1,4        ))
new_teams.append(("Pot 1",	6,	"Fenerbahçe SK (TUR)",	30.000,                            3,5           ))
new_teams.append(("Pot 2",	7,	"AS Monaco FC (FRA)",	29.000,                                4,5       ))
new_teams.append(("Pot 2",	8,	"CFR 1907 Cluj (ROU)",	27.500,                            1,5           ))
new_teams.append(("Pot 2",	9,	"FC Midtjylland (DEN)",	25.500,                            1,5           ))
new_teams.append(("Pot 2",	10,	"PAOK FC (GRE)",	25.000,                                1,3       ))
new_teams.append(("Pot 2",	11,	"ŠK Slovan Bratislava (SVK)",	24.500,                    1,5                   ))
new_teams.append(("Pot 2",	12,	"Maccabi Tel-Aviv FC (ISR)", 	24.000,                    1,5                   ))
new_teams.append(("Pot 3",	13,	"FC Viktoria Plzeň (CZE)", 	22.000,                        2,4               ))
new_teams.append(("Pot 3",	14,	"PFC Ludogorets 1945 (BUL)",	21.000,                    1,5                   ))
new_teams.append(("Pot 3",	15,	"FK Bodø/Glimt (NOR)",	20.000,                             2,5          ))
new_teams.append(("Pot 3",	16,	"CA Osasuna (ESP)",	18.599,                                 3,3      ))
new_teams.append(("Pot 3",	17,	"KRC Genk (BEL)",	18.000,                                 1,4      ))
new_teams.append(("Pot 3",	18,	"FC Bologna (ITA)",	16.385,                                 3,3      ))
new_teams.append(("Pot 4",	19,	"FC Zorya Luhansk (UKR)",	16.000,                         1,3              ))
new_teams.append(("Pot 4",	20,	"FC Astana (KAZ)", 	14.000,                                 1,5      ))
new_teams.append(("Pot 4",	21,	"Beşiktaş (TUR)", 	14.000,                              3,5         ))
new_teams.append(("Pot 4",	22,	"FK Žalgiris Vilnius (LTU)",	11.000,                      1,5                 ))
new_teams.append(("Pot 4",	23,	"HJK Helsinki (FIN)", 	11.000,                               1,5        ))
new_teams.append(("Pot 4",	24,	"FC Flora Tallinn (EST)",	10.500,                           1,5            ))
new_teams.append(("Pot 5",	25,	"Legia Warszawa (POL)",	11.000,                               1,5        ))
new_teams.append(("Pot 5",	26,	"FC Spartak Trnava (SVK)",	10.500,                           1,4            ))
new_teams.append(("Pot 5",	27,	"NK Olimpija Ljubljana (SVN)",	9.000,                        1,5               ))
new_teams.append(("Pot 5",	28,	"HŠK Zrinjski (BIH)", 	8.500,                               1,5        ))
new_teams.append(("Pot 5",	29,	"Dnipro-1 (UKR)",	8.000,                                   1,3      ))
new_teams.append(("Pot 5",	30,	"KÍ Klaksvík (FRO)", 	8.000,                               1,5        ))
new_teams.append(("Pot 6",	31,	"Aberdeen FC (SCO)",	8.000,                               2,3        ))
new_teams.append(("Pot 6",	32,	"FK Čukarički (SRB)",	6.475,                               1,5        ))
new_teams.append(("Pot 6",	33,	"FC Lugano (SUI)",	6.335,                                   1,3      ))
new_teams.append(("Pot 6",	34,	"Breidablik (ISL)", 	6.000,                               1,5        ))
new_teams.append(("Pot 6",	35,	"FC Nordsjælland (DEN)",	5.565,                           1,5            ))
new_teams.append(("Pot 6",	36,	"Ballkani (KOS)",	3.000,                               1,5        ))




CET_minus_1 = ['ENG','POR','SCO']
CET_plus_1 = ['TUR','AZE','ISR','UKR']

# %%

for conf in Conference.objects.filter(scenario=scenario).exclude(name__in=['HARD Constraints','SOFT Constraints']):
    conf.teams.clear()
    conf.collapseInView = True
    conf.save()

Team.objects.filter(season=scenario.season).update(active=False)
for t in new_teams:    
    team_name = t[2].split('(')[0].strip()
    team_country = t[2].split('(')[1].split(')')[0].strip()
    global_coeff = t[4]
    domestic_coeff = t[5]
    pot = int(t[0].split(' ')[1].strip())
    pos = int(t[1])
    teamObj = Team.objects.filter(season=scenario.season,name=team_name)
    if teamObj:        
        
        pass
    else:
        print(t,"->", team_name)
        gteam = GlobalTeam.objects.filter(name=team_name)
        if gteam:
            new_t = Team.objects.create(season=scenario.season,
                name=team_name,
                attractivity=global_coeff,
                position=pos,
                pot=pot,
                latitude=gteam.first().latitude,
                longitude=gteam.first().longitude,
                country=gteam.first().country,
                active=True)
            print("\tCreated team from global", team_name)
            teamObj = Team.objects.filter(season=scenario.season,name=team_name)
        else:
            print("\tTeam not found", team_name)
            continue


    Conference.objects.filter(scenario=scenario,name="UECL").first().teams.add(teamObj.first())
    Conference.objects.filter(scenario=scenario,name=t[0]).first().teams.add(teamObj.first())

    # if global_coeff in [3,4,5]:
    #     Conference.objects.filter(scenario=scenario,name=f"Global Coeff {global_coeff}").first().teams.add(teamObj.first())

    # if domestic_coeff in [3,5]:
    #     Conference.objects.filter(scenario=scenario,name=f"Domestic Coeff {domestic_coeff}").first().teams.add(teamObj.first())

    if team_country in CET_minus_1:
        Conference.objects.filter(scenario=scenario,name="CET-1").first().teams.add(teamObj.first())
    elif team_country in CET_plus_1:
        Conference.objects.filter(scenario=scenario,name="CET+1").first().teams.add(teamObj.first())
    else:
        Conference.objects.filter(scenario=scenario,name="CET").first().teams.add(teamObj.first())

    teamObj.update(active=True)
    teamObj.update(attractivity=global_coeff)
    teamObj.update(position=pos)
    teamObj.update(pot=pot)




# %%
