# %%
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 scheduler.models import *
import pulp
from pulp import lpSum, value, XPRESS, GUROBI, PULP_CBC_CMD
from django.db.models import Q
from django.template.loader import render_to_string

from qualifiers.models import *
from common.models import GlobalTeam, GlobalCountry
from scheduler.models import Season, Scenario, Team, DayObj, CountryClash, Country

from qualifiers.draws import groupTeams, optimize_inversions4
from scheduler.solver.tasks.optimize import optimize
from scheduler.solver.tasks.optimize_submodels import ueluecl24_basicmodell_v2

import random
import time
import json
import csv
import networkx as nx
import matplotlib.pyplot as plt
from datetime import timedelta

from django.contrib.sessions.models import Session


scenario = Scenario.objects.get(id=9051)
# scenario = Scenario.objects.get(id=9368)
# scenario = Scenario.objects.get(id=1)
season = scenario.season

s2 = scenario.id
user_name = 'md'
user_is_staff = True
runMode = 'New'
localsearch_time = 0
RUN_ENV = 'local'
SOLVER = 'xpress'


# Conference.objects.filter(scenario=scenario,name__in=["UEL","UECL"]).update(reopt=True)

sol = optimize(task=None, s2=s2, user_name=user_name, user_is_staff=user_is_staff,
                runMode=runMode, localsearch_time=localsearch_time, RUN_ENV=RUN_ENV, solver=SOLVER)



# ueluecl24_basicmodell_v2(SOLVER,scenario,[],[],maxTime=3600)


# %%

# hawishes = HAWish.objects.filter(scenario=scenario)

# # elemHaWishes ={e['id'] : [] for e in hawishes}
# # elemHaWishTeams={}
# # elemHaWishDays ={}
# # elemHaWishFirstDay ={}
# # elemHaWishNum ={}

# cntr =1
# for e in hawishes:
#     elemTeams = [[t] for t in e.get_teams()] if e.forEachTeam else [e.get_teams()]
#     elemRounds = [[d] for d in e.get_rounds()] if e.forEachDay else [e.get_rounds()]

#     if e.homeAway == "HOME":
#         if e.minGames > 0:
#             for teamset in elemTeams:
#                 for roundset in elemRounds:
#                     model += lpSum([x[r,t.id,t2.id] for t in teamset for r in roundset for t2 in teams if (r,t.id,t2.id) in x.keys()]) >= e.minGames - seedViolation[seed.id]


    


# #     elemHaWishes[e['id']]=[]
# #     allElemDays=[]
# #     thisDaySet=[]
# #     lastDaySet = []
# #     # print("elemDays",elemDays)
# #     for d in elemDays :
# #         # print (e)
# #         if (e['forEachDay'] or e['forOneDay']) and e['timeframe']!=1:
# #             thisDaySet=[]
# #             # day1=  parse(getDayById[d[0]]['day'])
# #             day1= getDateTimeDay[d[0]]
# #             if  e['timeframe']>1:
# #                 day2=day1 + datetime.timedelta(days=e['timeframe']-1)
# #                 for d3 in days:
# #                     # dt = parse(getDayById[d3]['day'])
# #                     dt= getDateTimeDay[d3]
# #                     if day1<=dt and dt<=day2 :
# #                         thisDaySet.append(d3)
# #             else:
# #                 r1 = getDayById[d[0]]['round']
# #                 for d3 in days:
# #                     dt= getDateTimeDay[d3]
# #                     # dt = parse(getDayById[d3]['day'])
# #                     if day1<=dt and r1 <= getRoundByDay[d3] and getRoundByDay[d3]< r1 + (-e['timeframe']) :
# #                         thisDaySet.append(d3)
# #                 # print (" ROUND HA WISH ", e['reason'], thisDaySet, e['timeframe'])
# #         else:
# #             thisDaySet=d

# #         # only create wish id new day set is superset
# #         if len([d for  d in thisDaySet if d not in lastDaySet])>0:
# #             for t in elemTeams:
# #                 cntr+=1
# #                 elemHaWishes[e['id']].append(cntr)
# #                 elemHaWishTeams[cntr]=t
# #                 elemHaWishDays[cntr]=thisDaySet.copy()
# #                 elemHaWishFirstDay[cntr]=d[0]
# #                 elemHaWishNum[cntr]=1
# #                 if e['maxGames'] ==0:
# #                     elemHaWishNum[cntr]=len(elemHaWishDays[cntr])*len(elemHaWishTeams[cntr])
# #                 if e['minGames'] > 0:
# #                     elemHaWishNum[cntr]=e['minGames']
# #             lastDaySet = thisDaySet.copy()
# #             allElemDays+= thisDaySet  

# #     hawRounds[e['id']]=[]
# #     for d3 in set(allElemDays):
# #         hawRounds[e['id']]+=getRoundsByDay[d3]
# #     hawRounds[e['id']]=sorted(list(set(hawRounds[e['id']])))
# #     hawRoundsString[e['id']]= ""
# #     for r in hawRounds[e['id']]:
# #         hawRoundsString[e['id']]+= str(r)+"_"
# #     if hawRoundsString[e['id']]!="":
# #         hawRoundsString[e['id']]=hawRoundsString[e['id']][:-1]
# #     e['nWishes'] = sum ( elemHaWishNum[ee] for ee in elemHaWishes[e['id']] )

# #     if e['forOneDay']:
# #         e['nWishes'] = e['forOneDayNum'] * len(elemTeams)
        
# # nElemHaWishes= sum(w['nWishes'] for w in hawishes) 

# # %%
