# 出典: mo-notebooks/03/shift-scheduling.ipynb

# %%
# install dependencies and select solver

SOLVER = "highs"

from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["highs"],  # modules to install
    license_uuid="default",  # license to use
)  # instantiate AMPL object and register magics

# %%
def shift_schedule(N=10, hours=40):
    """return a solved model assigning N workers to shifts"""

    workers = [f"W{i:02d}" for i in range(1, N + 1)]
    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    shifts = ["morning", "evening", "night"]
    slots = [(d, s) for d in days for s in shifts]
    blocks = [(slots[i] + slots[i + 1] + slots[i + 2]) for i in range(len(slots) - 2)]
    weekends = [(d, s) for (d, s) in slots if d in ["Sat", "Sun"]]
    workers_required = {
        (d, s): (1 if s in ["night"] or d in ["Sun"] else 2)
        for d in days
        for s in shifts
    }

    m = AMPL()
    m.read("shift_schedule.mod")

    m.set["WORKERS"] = workers
    m.set["DAYS"] = days
    m.set["SHIFTS"] = shifts
    m.set["SLOTS"] = slots
    m.set["BLOCKS"] = blocks
    m.set["WEEKENDS"] = weekends
    m.param["WorkersRequired"] = workers_required
    m.param["Hours"] = hours

    m.solve(solver=SOLVER)
    assert m.solve_result == "solved", m.solve_result

    return m


m = shift_schedule(10, 40)

# %%
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle


def visualize(m):
    workers = m.set["WORKERS"].to_list()
    slots = m.set["SLOTS"].to_list()
    days = m.set["DAYS"].to_list()

    assign = m.var["assign"].to_dict()
    needed = m.var["needed"].to_dict()
    weekend = m.var["weekend"].to_dict()

    bw = 1.0
    fig, ax = plt.subplots(1, 1, figsize=(12, 1 + 0.3 * len(workers)))
    ax.set_title("Shift Schedule")

    # x axis styling
    ax.set_xlim(0, len(slots))
    colors = ["teal", "gold", "magenta"]
    for i in range(len(slots) + 1):
        ax.axvline(i, lw=0.3)
        ax.fill_between(
            [i, i + 1], [0] * 2, [len(workers)] * 2, alpha=0.1, color=colors[i % 3]
        )
    for i in range(len(days) + 1):
        ax.axvline(3 * i, lw=1)
    ax.set_xticks([3 * i + 1.5 for i in range(len(days))])
    ax.set_xticklabels(days)
    ax.set_xlabel("Shift")

    # y axis styling
    ax.set_ylim(0, len(workers))
    for j in range(len(workers) + 1):
        ax.axhline(j, lw=0.3)
    ax.set_yticks([j + 0.5 for j in range(len(workers))])
    ax.set_yticklabels(workers)
    ax.set_ylabel("Worker")

    # show shift assignments
    for i, slot in enumerate(slots):
        day, shift = slot
        for j, worker in enumerate(workers):
            if round(assign[worker, day, shift]):
                ax.add_patch(Rectangle((i, j + (1 - bw) / 2), 1, bw, edgecolor="b"))
                ax.text(
                    i + 1 / 2, j + 1 / 2, worker, ha="center", va="center", color="w"
                )

    # display needed and weekend data
    for j, worker in enumerate(workers):
        if not needed[worker]:
            ax.fill_between(
                [0, len(slots)], [j, j], [j + 1, j + 1], color="k", alpha=0.3
            )
        if needed[worker] and not weekend[worker]:
            ax.fill_between(
                [15, len(slots)], [j, j], [j + 1, j + 1], color="k", alpha=0.3
            )


visualize(m)

# %%
import pandas as pd

# get the schedule from AMPL and convert to pandas DataFrame with defined columns
schedule = m.var["assign"].to_list()
schedule = pd.DataFrame(
    [[s[0], s[1], s[2]] for s in schedule if s[3]], columns=["worker", "day", "shift"]
)

# create and assign a worker category type
worker_type = pd.CategoricalDtype(categories=m.set["WORKERS"].to_list(), ordered=True)
schedule["worker"] = schedule["worker"].astype(worker_type)

# create and assign a day category type
day_type = pd.CategoricalDtype(categories=m.set["DAYS"].to_list(), ordered=True)
schedule["day"] = schedule["day"].astype(day_type)

# create and assign a shift category type
shift_type = pd.CategoricalDtype(categories=m.set["SHIFTS"].to_list(), ordered=True)
schedule["shift"] = schedule["shift"].astype(shift_type)

# demonstrate sorting and display of the master schedule
schedule.sort_values(by=["day", "shift", "worker"])

# %%
# sort schedule by worker
schedule = schedule.sort_values(by=["worker", "day", "shift"])

# print worker schedules
for worker, worker_schedule in schedule.groupby("worker"):
    print(f"\n Work schedule for {worker}")
    if len(worker_schedule) > 0:
        for s in worker_schedule.to_string(index=False).split("\n"):
            print(s)
    else:
        print("   no assigned shifts")

# %%
# sort by day, shift, worker
schedule = schedule.sort_values(by=["day", "shift", "worker"])

for day, day_schedule in schedule.groupby("day"):
    print(f"\nShift schedule for {day}")
    for shift, shift_schedule in day_schedule.groupby("shift"):
        print(f"   {shift} shift: ", end="")
        print(", ".join([worker for worker in shift_schedule["worker"].values]))
