# %%
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.optimizer import optimize_2phases
from scheduler.solver.tasks.optimize import optimize
from draws.solver.optimize_draws import ucl24_ha_matrix, ucl24_opponent_matrix


from django.template.loader import render_to_string
from django.core.files.storage import FileSystemStorage
from django.utils.translation import gettext_lazy as _

# from gurobipy import *
import pulp
from pulp import lpSum, value, XPRESS_PY, XPRESS, GUROBI, PULP_CBC_CMD
from math import sqrt,pow,sin,cos,atan2,pi, ceil
from collections import defaultdict
import timeit
import datetime
import operator
import random
import time
import copy
# from os import dup, dup2, close, path
import os
from importlib import import_module
import builtins as __builtin__
import logging
import networkx as nx
import json
import string 
import hashlib

from scheduler.models import *
from leagues.celery import celery, TASK_TIME_LIMIT
from leagues.settings import PULP_FOLDER
from scheduler.helpers import serialize_scenario, report_solverstatus
from scheduler.solver.functions import *
from scheduler.solver.tasks.optimize_localsearch import smartNeighbor
from scheduler.solver.tasks.optimize_submodels import ucl24_basicmodell, ueluecl24_basicmodell, ueluecl24_basicmodell_v2
from scheduler.helpers import copy_scenario
from draws.solver.optimize_draws import ucl24_ha_matrix

# from research.learners import AttendanceLearner
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
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

def getVal(v):
    if type(v) == int :
        return v
    else: 
        return v.value()


# basescenario = Scenario.objects.get(id=9306)
# scenario = Scenario.objects.get(id=9308)
basescenario = Scenario.objects.get(id=9414)

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

# %%
Scenario.objects.filter(season=basescenario.season,name__contains="Copy of BaseScenario").delete()
season = basescenario.season
print("START SIMULATION")
for counter in range(1,50):
    name = f"Copy of BaseScenario {counter:03d}"
    scenario = copy_scenario(basescenario, name=name, comment="")
    print(f"COPY SCENARIO {name}")

    scenario.last_modified = timezone.now()
    scenario.last_modified_by = None
    scenario.save()

    # %%
    # print("RANDOM DRAW")
    # GameRequirement.objects.filter(scenario=scenario).delete()
    # if season.optimizationParameters == 'UCL24':
    #     ucl24_ha_matrix(scenario.id)
    # elif season.optimizationParameters == "UEL24":
    #     ucl24_ha_matrix(scenario.id,"UEL")
    #     ucl24_opponent_matrix(scenario,"UECL")
    # print("DONE")

    # %%

    # # UPDATE TOPGAMES
    # encgroups = EncGroup.objects.filter(scenario=scenario)
    # Encounter.objects.filter(scenario=scenario).delete()

    # for game in GameRequirement.objects.filter(scenario=scenario):
    #     if game.team1.attractivity >= 4 or game.team2.attractivity >= 4:
    #         if game.team1.attractivity >= 4 and game.team2.attractivity >= 4:
    #             enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="Top Games"))
    #         elif game.team1.attractivity >= 4:
    #             if game.team1.countryObj.shortname == "ENG":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="England top games"))
    #             if game.team1.countryObj.shortname == "FRA":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="France top games"))
    #             if game.team1.countryObj.shortname == "GER":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="German top games"))
    #             if game.team1.countryObj.shortname == "ITA":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="Italian top games"))
    #             if game.team1.countryObj.shortname == "ESP":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="Spain top games"))
    #         elif game.team2.attractivity >= 4:
    #             if game.team2.countryObj.shortname == "ENG":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="England top games"))
    #             if game.team2.countryObj.shortname == "FRA":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="France top games"))
    #             if game.team2.countryObj.shortname == "GER":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="German top games"))
    #             if game.team2.countryObj.shortname == "ITA":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="Italian top games"))
    #             if game.team2.countryObj.shortname == "ESP":
    #                 enc = Encounter(scenario=scenario,encounterGroup=encgroups.get(name="Spain top games"))
            
    #         enc.save()
    #         enc.homeTeams.add(game.team1)
    #         enc.awayTeams.add(game.team2)

    print("STARTING OPTIMIZATION")

    try:

        sol,kpis = optimize(task=None,s2=scenario.id, user_name=user_name, user_is_staff=user_is_staff,
                    runMode='New', localsearch_time=0, RUN_ENV=RUN_ENV, solver=SOLVER)

        print("########################################")
        print("AFTER NEW RUN")
        print(kpis)
        print("########################################")


        sol,kpis = optimize(task=None,s2=scenario.id, user_name=user_name, user_is_staff=user_is_staff,
                        runMode='Improve', localsearch_time=localsearch_time, RUN_ENV=RUN_ENV, solver=SOLVER)


        print("########################################")
        print("AFTER IMPROVE")
        print(kpis)
        print("########################################")

    except:
        print("\t\tERROR")
        pass


