# %%
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 *
from pulp import *
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

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

from django.contrib.sessions.models import Session


scenario = Scenario.objects.get(id=9704)




from scheduler.solver.tasks.optimize import optimize

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

teams = Team.objects.filter(season=scenario.season,active=True).distinct()


gamereqs = GameRequirement.objects.filter(scenario=scenario)


# 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)


def create_graph(pot=None):
    def hex_to_rgb(value):
        value = value.lstrip('#')
        lv = len(value)
        return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))


    hex_colors = {
        1: "#ffff99",
        2: "#99ccff",
        3: "#FFcc99",
        4: "#CCFFCC",
        5: "#CCCCFF",
        6: "#9999FF",
    }

    rgb_colors = {}
    for c in hex_colors:
        rgb_colors[c] = hex_to_rgb(hex_colors[c])

    G = nx.Graph()
    node_colors = {}
    node_label = {}
    for t in teams:
        node_label[t] = f"{t.shortname}"
        if pot is None:
            node_color = rgb_colors[t.pot]
            node_colors[node_label[t]] = hex_colors[t.pot]
        else:
            node_color = rgb_colors[pot[t]]
            node_colors[node_label[t]] = hex_colors[pot[t]]
        G.add_node(node_label[t],
                viz = {"color": {"a":0, "r": node_color[0], "g": node_color[1], "b": node_color[2]}, 'size':20})

    # for n in nx.nodes(G):
    #     G.nodes[n]["viz"] = {} 
    #     G.nodes[n]["viz"]["color"] = colors[]

    for gq in gamereqs:
        if gq.team1 in teams and gq.team2 in teams:
            G.add_edge(node_label[gq.team1],node_label[gq.team2], capacity = 1.0)

    SubG = [G.subgraph(c).copy() for c in nx.connected_components(G)]

    # nx.draw(SubG[0], with_labels=True, font_weight='bold')
    sub = SubG[0]

    nx.draw(sub, with_labels=True,
                            node_size=400, font_size=6, node_color=[node_colors[g] for g in list(sub.nodes())])
    pos = nx.nx_agraph.graphviz_layout(sub)
    nx.draw_networkx_edge_labels(
        sub, pos=pos, edge_labels={e: "" for e in list(sub.edges())}, font_color='black', font_size=6
    )
    nx.write_gexf(sub, "9704.gexf")


    distance = {}

    max_path = 0
    for t in teams:
        path = nx.shortest_path(G, source=t.shortname)
        for p in path:
            
            
            if len(path[p]) <= 2:
                length = 0
            elif len(path[p]) == 3:
                length = 1
            else:
                length = 2
            
            distance[(teams.get(shortname=t.shortname),teams.get(shortname=p))] = length
    
            



    # cut_value, partition = nx.minimum_cut(G, "Manch", "y")

    return distance

# %%


distance = create_graph()

# %%

# import xpress as xp

# xp.controls.outputlog = 1
# model = xp.problem(name='Draws', sense=xp.minimize)
# model.setControl('maxtime' , 600)


# distance = {(t1,t2): 1 for t1 in teams for t2 in teams}
# for g in gamereqs:
#     if (g.team1,g.team2) in distance.keys():
#         distance[(g.team1,g.team2)] = 0

# groups = range(1,3)

# x = {}
# y = {}
# for g in groups:
#     for t in teams:
#         x[t,g] = xp.var(vartype=xp.binary)        
# for t1,t2 in distance.keys():
#     y[t1,t2] = xp.var(vartype=xp.binary)


# model.addVariable(x)
# model.addVariable(y)

# for t1,t2 in y.keys():
#     for g in groups:
#         model.addConstraint(y[t1,t2] >= x[t1,g] + x[t2,g] - 1)

# for t in teams:
#     model.addConstraint(xp.Sum(x[t,g] for g in groups) == 1)

# for g in groups:
#     model.addConstraint(xp.Sum(x[t,g] for t in teams) == len(teams)/len(groups))

# model.setObjective(xp.Sum(y[t1,t2]*distance[(t1,t2)] for (t1,t2) in y.keys()))

# start_time = time.time()
# model.solve()
# comp_time = time.time()-start_time


# teams = Team.objects.filter(season=scenario.season,active=True).distinct()

# import xpress as xp

# xp.controls.outputlog = 1
# model = xp.problem(name='Draws', sense=xp.minimize)
# model.setControl('maxtime' , 600)


# groups = range(1,5)

# x = {}
# y = {}
# for g in groups:
#     for t in teams:
#         x[t,g] = xp.var(vartype=xp.binary)        
#     for gr in gamereqs:
#         y[gr.team1,gr.team2,g] = xp.var(vartype=xp.binary)

# model.addVariable(x)
# model.addVariable(y)

# for t1,t2,g in y.keys():
#     model.addConstraint(y[t1,t2,g] >= (x[t1,g] - x[t2,g]))
#     model.addConstraint(y[t1,t2,g] >= (x[t2,g] - x[t1,g]))

# for t in teams:
#     model.addConstraint(xp.Sum(x[t,g] for g in groups) == 1)

# for g in groups:
#     model.addConstraint(xp.Sum(x[t,g] for t in teams) == len(teams)/len(groups))

# model.setObjective(xp.Sum(y[key] for key in y.keys()))

# start_time = time.time()
# model.solve()
# comp_time = time.time()-start_time



# # %%
# pot = {}
# group_list = {g:[] for g in groups}
# for g in groups:
#     print("GROUP",g)
#     for t in teams:
#         if model.getSolution(x[t,g]) > 0:
#             print("\t",t.id)
#             group_list[g].append(t.id)
#             pot[t] = g
#     print("")



# # %%



# # %%

# print(group_list)


# # %%

# create_graph(pot)