# %%
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"
import random
import time

# XPRESS ENVIRONMENT
os.environ['XPRESSDIR'] = "/opt/xpressmp_8.4"
os.environ['XPRESS'] = "/opt/xpressmp_8.4/bin"
os.environ['LD_LIBRARY_PATH'] = os.environ['XPRESSDIR']+"/lib:"+os.environ['LD_LIBRARY_PATH']
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['PYTHONPATH']
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.environ['CLASSPATH']
os.environ['CLASSPATH'] =os.environ['XPRESSDIR']+"/lib/xprm.jar:"+os.environ['CLASSPATH']
os.environ['PATH'] =os.environ['XPRESSDIR']+"/bin:"+os.environ['PATH']


from leagues import settings
settings.DATABASES['default']['NAME'] = PROJECT_PATH+'/db.sqlite3'

import django
django.setup()

from scheduler.models import *
from pulp import *
import csv

import xpress as xp
xp.controls.outputlog = 1



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

# %%


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


getTeamByID = {
    t.id:t for t in teams
}


countries = teams.values_list('country', flat=True).distinct()
teams_from_country = {
    c:[t for t in teams if t.country==c] for c in countries 
}

pot = {}
for i in teams.values_list('pot',flat=True).distinct():
    pot[i] = teams.filter(pot=i)


# directed version
# requirement = {
#     1:[1,-1,2,-2,3,-3,4,-4],
#     2:[1,-1,2,-2,3,-3,4,-4],
#     3:[1,-1,2,-2,3,-3,4,-4],
#     4:[1,-1,2,-2,3,-3,4,-4],
# }
# undirected version
requirement = {
    1:{
        1:2,
        2:2,
        3:2,
        4:2,
    },
    2:{
        1:2,
        2:2,
        3:2,
        4:2,
    },
    3:{
        1:2,
        2:2,
        3:2,
        4:2,
    },
    4:{
        1:2,
        2:2,
        3:2,
        4:2,
    },
}

def check_feasible(fixed_games):
    model = xp.problem(name='Draws', sense=xp.minimize)
    x = {}
    for t1 in teams:
        for t2 in teams:
            if t1.country != t2.country:
                x[t1.id, t2.id] = xp.var(ub=1, vartype=xp.integer)

    model.addVariable(x)

    # REQUIREMENTS
    for t in teams:
        for r,val in requirement[t.pot].items():
            model.addConstraint(xp.Sum(x[t.id,t2.id] for t2 in pot[r] if (t.id,t2.id) in x.keys()) == val)
        for c in countries:
            if c != t.country:
                model.addConstraint(xp.Sum(x[t.id,t2.id] for t2 in teams_from_country[c]) <= 3)

    # FIXATIONS
    for (t1,t2) in fixed_games:
        # print("FIXING",t1,t2)
        model.addConstraint(x[t1,t2] == 1)


    for (t1,t2) in x.keys():
        model.addConstraint(x[t1,t2] == x[t2,t1])

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

    if model.getProbStatus() != 6:
        # print("INFEASIBLE FOUND")
        return False
    else:
        return True


def random_matrix():
    model = xp.problem(name='Draws', sense=xp.minimize)
    x = {}
    for t1 in teams:
        for t2 in teams:
            if t1.country != t2.country:
                x[t1.id, t2.id] = xp.var(ub=1, vartype=xp.integer)

    model.addVariable(x)

    # REQUIREMENTS
    for t in teams:
        for r,val in requirement[t.pot].items():
            model.addConstraint(xp.Sum(x[t.id,t2.id] for t2 in pot[r] if (t.id,t2.id) in x.keys()) == val)
        for c in countries:
            if c != t.country:
                model.addConstraint(xp.Sum(x[t.id,t2.id] for t2 in teams_from_country[c]) <= 3)


    for (t1,t2) in x.keys():
        model.addConstraint(x[t1,t2] == x[t2,t1])


    model.setObjective(xp.Sum(random.uniform(0,1)*x[key] for key in x.keys()))

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

    if model.getProbStatus() != 6:
        # print("INFEASIBLE FOUND")
        return False
    else:
        solution = []
        for key in x.keys():
            if model.getSolution(x[key]) > 0:
                solution.append((key[0],key[1]))


        return solution

# %%

for k in range(1,1001):
    print("SIMULATION",k)

    teams = Team.objects.filter(season=scenario.season,active=True)
    countries = teams.values_list('country', flat=True).distinct()
    teams_from_country = {
        c:[t for t in teams if t.country==c] for c in countries 
    }

    pot = {}
    for i in teams.values_list('pot',flat=True).distinct():
        pot[i] = teams.filter(pot=i)


    # directed version
    # requirement = {
    #     1:[1,-1,2,-2,3,-3,4,-4],
    #     2:[1,-1,2,-2,3,-3,4,-4],
    #     3:[1,-1,2,-2,3,-3,4,-4],
    #     4:[1,-1,2,-2,3,-3,4,-4],
    # }
    # undirected version
    requirement = {
        1:{
            1:2,
            2:2,
            3:2,
            4:2,
        },
        2:{
            1:2,
            2:2,
            3:2,
            4:2,
        },
        3:{
            1:2,
            2:2,
            3:2,
            4:2,
        },
        4:{
            1:2,
            2:2,
            3:2,
            4:2,
        },
    }




    solution = random_matrix()
    if not check_feasible(solution):
        print("INFEASIBLE")
        exit()



    opps = {
        t:{
            p:[] for p in range(1,5)
        }
        for t in teams
    }

    for (s1,s2) in solution:
        t1 = getTeamByID[s1]
        t2 = getTeamByID[s2]
        opps[t1][t2.pot].append(t2.id)


    with open('verteilung_random.csv', "a") as f:
        for t in teams.order_by('pot'):
            f.write(f"{k},{t.id},{';'.join([str(a) for a in opps[t][1]])},{';'.join([str(a) for a in opps[t][2]])},{';'.join([str(a) for a in opps[t][3]])},{';'.join([str(a) for a in opps[t][4]])}\n")













# # %%

# %%


teams = list(range(1,19))
days = list(range(1,18))

model = xp.problem(name='Draws', sense=xp.minimize)
x = {}
for t1 in teams:
    for t2 in teams:
        if t1 != t2:
            for d in days:
                x[t1,t2,d] = xp.var(ub=1, vartype=xp.integer)

model.addVariable(x)

# REQUIREMENTS
for t1 in teams:
    for t2 in teams:
        if t1 != t2:
            model.addConstraint(xp.Sum(x[t1,t2,d] for d in days) == 1)
    for d in days:
        model.addConstraint(xp.Sum(x[t1,t2,d] for t2 in teams if t2 != t1) == 1)



model.setObjective(xp.Sum(random.uniform(0,1)*x[key] for key in x.keys()))

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


if model.getProbStatus() != 6:
    print("INFEASIBLE FOUND")
else:
    for key in x.keys():
        if model.getSolution(x[key]) > 0:
            print(key)

# %%
