# %%
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=10310)
# import_globals(scenario.season.id)
# teams = scenario.season.scheduler_teams.all()




# %%

new_teams = []
new_teams.append((1,  "Manchester City FC (ENG)",	145.000, "Pot 1",5,4))
new_teams.append((2,  "FC Bayern München (GER)",	136.000, "Pot 1",5,5))
new_teams.append((3,  "Liverpool FC (ENG)",	123.000, "Pot 1",5,5))
new_teams.append((4,  "Real Madrid CF (ESP)",	121.000, "Pot 1",5,5))
new_teams.append((5,  "Paris Saint-Germain (FRA)",	112.000, "Pot 1",5,5))
new_teams.append((6,  "Manchester United FC (ENG)",	104.000, "Pot 1",5,5))
new_teams.append((7,  "FC Barcelona (ESP)",	98.000, "Pot 1",5,5))
new_teams.append((8,  "FC Internazionale Milano (ITA)",	96.000, "Pot 1",4,5))
new_teams.append((9,  "Sevilla FC (ESP)",	91.000, "Pot 1",3,4))
new_teams.append((10, "Borussia Dortmund (GER)",	86.000, "Pot 2",4,4))
new_teams.append((11, "Club Atlético de Madrid (ESP)",	85.000, "Pot 2",4,4))
new_teams.append((12, "RB Leipzig (GER)",	84.000, "Pot 2",3,3))
new_teams.append((13, "SL Benfica (POR)",	82.000, "Pot 2",2,5))
new_teams.append((14, "SSC Napoli (ITA)",	81.000, "Pot 2",3,4))
new_teams.append((15, "FC Porto (POR)",	81.000, "Pot 2",3,5))
new_teams.append((16, "Arsenal FC (ENG)",	76.000, "Pot 2",4,4))
new_teams.append((17, "FC Shakhtar Donetsk (UKR)",	63.000, "Pot 2",1,5))
new_teams.append((18, "FC Salzburg (AUT)",	59.000, "Pot 2",2,5))
new_teams.append((19, "Atalanta BC (ITA)",	55.500, "Pot 3",2,3))
new_teams.append((20, "Feyenoord (NED)",	51.000, "Pot 3",2,4))
new_teams.append((21, "AC Milan (ITA)",	50.000, "Pot 3",3,5))
new_teams.append((22, "SC Braga (POR)", 	44.000, "Pot 3",2,3))
new_teams.append((23, "PSV Eindhoven (NED)",	43.000, "Pot 3",2,4))
new_teams.append((24, "S.S. Lazio (ITA)",	42.000, "Pot 3",2,3))
new_teams.append((25, "FK Crvena zvezda (SRB)",	42.000, "Pot 3",1,5))
new_teams.append((26, "F.C. Copenhagen (DEN)", 	40.500, "Pot 3",1,4))
new_teams.append((27, "BSC Young Boys (SUI)",	34.500, "Pot 3",1,4))
new_teams.append((28, "Real Sociedad de Fútbol (ESP)",	33.000, "Pot 4",2,3))
new_teams.append((29, "Olympique de Marseille (FRA)", 	33.000, "Pot 4",3,4))
new_teams.append((30, "Galatasaray A.Ş. (TUR)",	31.500, "Pot 4",1,5))
new_teams.append((31, "Celtic FC (SCO)",	31.000, "Pot 4",2,3))
new_teams.append((32, "Qarabağ FK (AZE)", 	25.000, "Pot 4",1,5))
new_teams.append((33, "Newcastle United FC (ENG)",	21.914, "Pot 4",3,3))
new_teams.append((34, "1. FC Union Berlin (GER)",	17.000, "Pot 4",2,3))
new_teams.append((35, "R. Antwerp FC (BEL)",	17.000, "Pot 4",3,3))
new_teams.append((36, "RC Lens (FRA)",	12.232, "Pot 4",2,3))


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

# %%


for i in range(1,6):
    Conference.objects.get_or_create(scenario=scenario,name=f"Global Coeff {i}")
    Conference.objects.get_or_create(scenario=scenario,name=f"Domestic Coeff {i}")
Conference.objects.get_or_create(scenario=scenario,name="CET")
Conference.objects.get_or_create(scenario=scenario,name="CET-1")
Conference.objects.get_or_create(scenario=scenario,name="CET+1")

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[1].split('(')[0].strip()
    team_country = t[1].split('(')[1].split(')')[0].strip()
    # abbreviation = t[2]
    global_coeff = t[4]
    domestic_coeff = t[5]
    pot = int(t[3].split(' ')[1].strip())
    pos = int(t[0])
    competition = "UCL"
    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:
            teamObj = Team.objects.create(season=scenario.season,
                name=team_name,
                attractivity=global_coeff+0.1*domestic_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=competition).first().teams.add(teamObj.first())
    Conference.objects.filter(scenario=scenario,name=f"{t[3]}").first().teams.add(teamObj.first())

    if global_coeff in range(1,6):
        Conference.objects.filter(scenario=scenario,name=f"Global Coeff {global_coeff}").first().teams.add(teamObj.first())

    if domestic_coeff in range(1,6):
        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+0.1*domestic_coeff)
    teamObj.update(coefficient=5-pot)
    teamObj.update(position=pos)
    teamObj.update(pot=pot)


for conf in Conference.objects.filter(scenario=scenario):
    for t in conf.teams.filter(active=False):
        conf.teams.remove(t)

for haw in HAWish.objects.filter(scenario=scenario):
    for t in haw.teams.filter(active=False):
        haw.teams.remove(t)

for enc in EncWish.objects.filter(scenario=scenario):
    for t in enc.teams1.filter(active=False):
        enc.teams1.remove(t)
    for t in enc.teams2.filter(active=False):
        enc.teams1.remove(t)

for pair in Pairing.objects.filter(scenario=scenario):
    if pair.team1.active==False or pair.team2.active==False:
        pair.delete()



# %%
