# %%
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
from draws.models import *


import time as timer



# %%

scenario = Scenario.objects.get(id=9541)
conferences = Conference.objects.filter(scenario=scenario)
supergroups = SuperGroup.objects.filter(draw__season=scenario.season)
allgroups = Group.objects.filter(supergroup__in=supergroups)
sgGroups = { sg.id: [g.id for g in sg.groups.all()] for sg in supergroups }

# %%


for conference in conferences:
    conference.teams.clear()

for sg in supergroups:
    draw = sg.draw
    season = sg.draw.season

    g_name={ g.id : g.name for g in sg.groups.all() }
    scen= False
    scen = scenario

    teamObjects= sg.teams.all().values()
    t_name = {}
    t_pot = {}
    t_country = {}
    for t in sg.teams.all():
        t_name[t.id] = t.name 
        t_pot[t.id] = t.pot 
        t_country[t.id] = t.countryObj.shortname 
    teams =  list (t_country.keys()) 
    pots=sorted(list(set(t_pot.values())))
    p_teams = { p: [t for t in teams if t_pot[t]==p] for p in pots}

    maxpot = max([ t_pot[t] for t in teams])
    sg_games_against_pot = sg.gamesPerTeam/maxpot


    c_teams= { g.id: [] for g in allgroups }
    for p in pots: 
        potTeams =  p_teams[p]
        random.shuffle(potTeams)
        for t in potTeams:
            allComments=""
            candidates= sgGroups[sg.id]
            minGroupLoad = min(len(c_teams[c]) for c in candidates)
            cands = [c for c in candidates if len(c_teams[c]) == minGroupLoad]
            c, r, b, fulldraw, comment, sol = optimize_draws.optimize_draws_New( scen.id, draw.id , t, cands, c_teams, [24, 25, 26, 27])
            allComments+=comment
            if p==1 or draw.alwaysPickFirstOpenGroup:
                c=[c[0]]
            chosen = random.choice(c)
            c_teams[chosen].append(t)
            allowedString=""
            for g in c:

                allowedString+=g_name[g][-1:]
            if allComments!="":
                allComments=";"+allComments.replace('\n',' ')
            team = Team.objects.get(id=t)
            conferences.filter(name=g_name[chosen]).first().teams.add(team)


# %%
