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




# %%

new_teams = []
new_teams.append(("Pot 1",1, "Roma",    "AS Roma (ITA) ",	97.000,     5,5, "UEL"))
new_teams.append(("Pot 1",2, "Ajax",    "AFC Ajax (NED)",	89.000,       5,5  , "UEL"))
new_teams.append(("Pot 1",3, "Villa",    "Villarreal CF (ESP)",	82.000,     5,5 , "UEL"))
new_teams.append(("Pot 1",4, "Bayer",    "Bayer 04 Leverkusen (GER)",	72.000,  4,4   , "UEL"))
new_teams.append(("Pot 1",5, "GNK",    "GNK Dinamo (CRO) ",	55.000,    2,5 , "UEL"))
new_teams.append(("Pot 1",6, "Ranger",    "Rangers FC (SCO)",	54.000,    4,5 , "UEL"))
new_teams.append(("Pot 1",7, "Sporti",    "Sporting Clube de Portugal (POR)",	52.500,   4,5  , "UEL"))
new_teams.append(("Pot 1",8, "Slavia",    "SK Slavia Praha (CZE)",	52.000,    2,5 , "UEL"))
new_teams.append(("Pot 1",9, "WestHam",    "West Ham United FC (ENG)",	50.000,   4,4  , "UEL"))
new_teams.append(("Pot 2",10, "Alkmaa",    "AZ Alkmaar (NED)",	47.500,    2,3 , "UEL"))
new_teams.append(("Pot 2",11, "Stade",    "Stade Rennais FC (FRA) ",	44.000,  3,5   , "UEL"))
new_teams.append(("Pot 2",12, "Olymp",    "Olympiacos FC (GRE)",	39.000,    2,5 , "UEL"))
new_teams.append(("Pot 2",13, "Betis",    "Real Betis Balompié (ESP)",	37.000,  3,4   , "UEL"))
new_teams.append(("Pot 2",14, "Linz",    "LASK Linz (AUT)",	36.000,    1,4 , "UEL"))
new_teams.append(("Pot 2",15, "Kyiv",    "FC Dynamo Kyiv (UKR)",	35.000,  3,5   , "UEL"))
new_teams.append(("Pot 2",16, "Lille",    "LOSC Lille (FRA)",	30.000,   3,4  , "UEL"))
new_teams.append(("Pot 2",17, "Feren",    "Ferencvárosi TC (HUN)",	27.000,   1,5  , "UEL"))
new_teams.append(("Pot 2",18, "Molde",    "Molde FK (NOR)",	24.000,    1,5 , "UEL"))
new_teams.append(("Pot 3",19, "Bright",    "Brighton & Hove Albion (ENG)",	21.914,   3,3  , "UEL"))
new_teams.append(("Pot 3",20, "Aston",    "Aston Villa FC (ENG)",	21.914,   4,4  , "UEL"))
new_teams.append(("Pot 3",21, "Fiore",    "ACF Fiorentina (ITA)",	20.000,    4,4 , "UEL"))
new_teams.append(("Pot 3",22, "Tiras",    "FC Sheriff Tiraspol (MDA) ",	19.500,   1,5  , "UEL"))
new_teams.append(("Pot 3",23, "St.Gil",    "Union Saint-Gilloise (BEL)",	19.000,   1,4  , "UEL"))
new_teams.append(("Pot 3",24, "Rapid",    "SK Rapid Wien (AUT)",	18.500,    2,5 , "UEL"))
new_teams.append(("Pot 3",25, "Freib",    "SC Freiburg (GER)",	16.496,    4,4 , "UEL"))
new_teams.append(("Pot 3",26, "Sparta",    "AC Sparta Praha (CZE)",	14.000,   2,5  , "UEL"))
new_teams.append(("Pot 3",27, "Haifa",    "Maccabi Haifa FC (ISR)",	13.000,   2,5  , "UEL"))
new_teams.append(("Pot 4",28, "Sturm",    "SK Sturm Graz (AUT)",	12.500,   1,5  , "UEL"))
new_teams.append(("Pot 4",29, "Toul",    "Toulouse FC (FRA)",	12.232,    3,4 , "UEL"))
new_teams.append(("Pot 4",30, "Athen",    "AEK Athens FC (GRE)",	11.000,   1,4  , "UEL"))
new_teams.append(("Pot 4",31, "Topola",    "FK TSC Bačka Topola (SRB)",	6.475,    1,5  , "UEL"))
new_teams.append(("Pot 4",32, "Serve",    "Servette FC (SUI) ",	6.335,     1,4 , "UEL"))
new_teams.append(("Pot 4",33, "Panat",    "Panathinaikos FC (GRE) ",	5.045,    1,5  , "UEL"))
new_teams.append(("Pot 4",34, "Raków",    "Raków Czestochowa (POL) ",	5.000,    1,3  , "UEL"))
new_teams.append(("Pot 4",35, "Aris",    "Aris Limassol FC (CYP)",	4.895,    1,5  , "UEL"))
new_teams.append(("Pot 4",36, "Häcke",    "BK Häcken (SWE)",	4.750,    1,5  , "UEL"))

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



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

# %%


for conf in Conference.objects.filter(scenario=scenario):
    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[3].split('(')[0].strip()
    team_country = t[3].split('(')[1].split(')')[0].strip()
    abbreviation = t[4]
    global_coeff = t[5]
    domestic_coeff = t[6]
    pot = int(t[0].split(' ')[1].strip())
    pos = int(t[1])
    competition = t[7]
    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"{competition}-{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)
    if teamObj.first().shortname == "":
        teamObj.update(shortname=abbreviation)




# %%
