"""Greedy construction: fill the roster day by day, one shift at a time, giving each open slot to the eligible staff
member who adds the least cost, and leaving the slot open when every candidate costs more than the gap would.

Rules it keeps while building (a staff member is eligible only if all hold): one shift a day, days off, which shift may
follow which, the most shifts of each type, the most minutes, the longest run of shifts, the most weekends, and the
shortest break (a new run starts only after enough days off). Rules it can only aim for: the minimum minutes (a top-up
pass at the end adds shifts to anyone still short) and the shortest run (anyone whose run is still too short is asked
first the next day). Whatever it misses is scored as a broken rule by roster.measures, never hidden.

Deterministic: ties go to the staff member furthest below contracted minutes, then to the earlier staff member.
"""
from roster import OFF, is_weekend, staff_violations


def build(inst, w):
    n, days = inst.n, inst.days
    row = [[OFF] * days for _ in range(n)]
    minutes = [0] * n
    count = [[0] * len(inst.shift_ids) for _ in range(n)]
    run = [0] * n            # length of the run of shifts ending yesterday
    run_from_start = [True] * n
    off_len = [0] * n        # length of the run of days off ending yesterday
    worked_ever = [False] * n
    weekends = [set() for _ in range(n)]
    assigned = {k: 0 for k in inst.cover}

    def ot(e, extra=0):
        return max(0, minutes[e] + extra - inst.staff[e].min_minutes) / 60

    def eligible(e, d, k):
        s = inst.staff[e]
        if row[e][d] != OFF or d in s.days_off:
            return False
        if d > 0 and row[e][d - 1] != OFF and k in inst.forbid_next[row[e][d - 1]]:
            return False
        if count[e][k] >= s.max_shifts[k] or minutes[e] + inst.length[k] > s.max_minutes:
            return False
        if run[e] + 1 > s.max_cons:
            return False
        if is_weekend(d) and (d // 7) not in weekends[e] and len(weekends[e]) >= s.max_weekends:
            return False
        if run[e] == 0 and worked_ever[e] and off_len[e] < s.min_off:
            return False
        return True

    def marginal(e, k):
        extra = inst.length[k]
        cur = [ot(i) for i in range(n)]
        new = cur[:]
        new[e] = ot(e, extra)
        return w["W_O"] * (new[e] - cur[e]) + w["W_F"] * ((max(new) - min(new)) - (max(cur) - min(cur)))

    def assign(e, d, k):
        row[e][d] = k
        minutes[e] += inst.length[k]
        count[e][k] += 1
        assigned[(d, k)] += 1
        if is_weekend(d):
            weekends[e].add(d // 7)

    for d in range(days):
        # anyone whose run is still shorter than the minimum works again today, on an open slot if possible
        for e in range(n):
            s = inst.staff[e]
            if run[e] and run[e] < s.min_cons and not run_from_start[e]:
                opts = [k for k in range(len(inst.shift_ids)) if eligible(e, d, k)]
                if opts:
                    prev = row[e][d - 1]
                    opts.sort(key=lambda k: (assigned[(d, k)] >= inst.cover[(d, k)][0], k != prev, k))
                    assign(e, d, opts[0])
        for k in range(len(inst.shift_ids)):
            req = inst.cover[(d, k)][0]
            gap_cost = w["W_C"] * inst.length[k] / 60
            while assigned[(d, k)] < req:
                cands = [e for e in range(n) if eligible(e, d, k)]
                if not cands:
                    break
                scored = sorted((marginal(e, k), minutes[e] - inst.staff[e].min_minutes, e) for e in cands)
                best_cost, _, e = scored[0]
                if best_cost >= gap_cost:
                    break
                assign(e, d, k)
        for e in range(n):
            if row[e][d] != OFF:
                if run[e] == 0:
                    run_from_start[e] = d == 0
                run[e] += 1
                off_len[e] = 0
                worked_ever[e] = True
            else:
                run[e] = 0
                off_len[e] += 1

    # top-up pass: anyone below contracted minutes gets the added shift that most reduces their own broken rules
    for e in range(n):
        s = inst.staff[e]
        while minutes[e] < s.min_minutes:
            base = sum(u for _r, u in staff_violations(inst, e, row[e]))
            best = None
            for d in range(days):
                if row[e][d] != OFF or d in s.days_off:
                    continue
                for k in range(len(inst.shift_ids)):
                    if count[e][k] >= s.max_shifts[k] or minutes[e] + inst.length[k] > s.max_minutes:
                        continue
                    row[e][d] = k
                    v = sum(u for _r, u in staff_violations(inst, e, row[e]))
                    row[e][d] = OFF
                    short = assigned[(d, k)] < inst.cover[(d, k)][0]
                    cand = (v, not short, d, k)
                    if v < base and (best is None or cand < best):
                        best = cand
            if best is None:
                break
            _v, _s, d, k = best
            assign(e, d, k)
    return row
