# %%
import json
from datetime import datetime, time, date
from serializers import ProblemSerializer


from competitions import get_teams_from_staffel
from schluesselzahlen import get_schluesselzahlen
from rahmentermine import get_rahmentermine


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"

""" read json """
with open("data/competitions.json", "r", encoding="utf-8") as f:
    competitions = json.load(f)
    
prob = ProblemSerializer(data=competitions)
prob.is_valid()

# %%
""" Create pulp model for solving a schedule for a given set of teams and rahmentermine """


rounds1 = list(range(1, len(rahmentermine)//2+1))
rounds2 = list(range(len(rahmentermine)//2+1, len(rahmentermine)+1))
rounds = rounds1 + rounds2





# %%

from pulp import LpVariable, LpProblem, LpMinimize, lpSum, LpStatus, value, LpInteger, XPRESS

model = LpProblem("Spielplan", LpMinimize)

# Create a variable for each team and each rahmentermin
x = {}
for team, attr in teams.items():
    for round in rounds:
        x[(team, round)] = LpVariable(
            f"team_{attr['MANNSCHAFT']}_{round}",
            lowBound=0,
            upBound=1,
            cat=LpInteger,
        )

# Create home variables """
home = {}
for team, attr in teams.items():
    for round in rounds:
        home[(team, round)] = LpVariable(
            f"home_{attr['MANNSCHAFT']}_{round}",
            lowBound=0,
            upBound=1,
            cat=LpInteger,
        )
        
# Create pattern variables
assignPattern = {}
for team, attr in teams.items():
    for p in pattern:
        assignPattern[(team, p)] = LpVariable(
            f"pattern_{attr['MANNSCHAFT']}_{p}",
            lowBound=0,
            upBound=1,
            cat=LpInteger,
        )

""" Each team exactly one pattern """
for team in teams:
    model += (lpSum(assignPattern[(team, p)] for p in pattern) == 1, f"team_{team}_one_pattern")

""" Patterns cannot be used more than once """    
for p in pattern:
    model += (lpSum(assignPattern[(team, p)] for team in teams) <= 1, f"pattern_{p}_used_once")
    
""" Couple patterns with home variables """
for round in rounds1:    
    for team, attr in teams.items():
        model += (lpSum(assignPattern[(team, p)] for p in pattern if pattern[p][round-1] == "H") == home[(team, round)], f"coupling_pattern_home_{attr['MANNSCHAFT']}_{round}")

# %%
model.solve(XPRESS(msg=1))
        
        
""" print patterns """
for team, attr in teams.items():
    for p in pattern:
        if value(assignPattern[(team, p)]) == 1:
            print(f"{attr['MANNSCHAFT']} is assigned pattern {p}")


        


