"""Plant 1 Safety and Skills Day scheduler.

Run:  uv run --with ortools --with openpyxl solver.py

Reads rules.md and the input workbooks every run (nothing from the data is
hard-coded), enumerates every slot order, solves each one lexicographically
to proven optimality with OR-Tools CP-SAT, keeps the best, and writes
plan.xlsx and training-day-schedule.xlsx. Input files are only read.
"""

import csv
import itertools
import re
import sys
import time
from collections import Counter, defaultdict
from datetime import datetime
from pathlib import Path

import openpyxl
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter
from ortools.sat.python import cp_model

HERE = Path(__file__).resolve().parent
RULES = HERE / "rules.md"
F_SESS = HERE / "mrmw-training-sessions.xlsx"
F_ROSTER = HERE / "mrmw-plant1-roster.xlsx"
F_SURVEY = HERE / "mrmw-training-survey.xlsx"
F_FLOOR = HERE / "mrmw-floor-coverage.xlsx"
F_MAP = HERE / "name-map.csv"
OUT_PLAN = HERE / "plan.xlsx"
OUT_SCHED = HERE / "training-day-schedule.xlsx"

FLOOR = "Floor"
OUT = "Out"


def die(msg):
    print("ERROR: " + msg, file=sys.stderr)
    sys.exit(1)


def need(pattern, text, what, flags=0):
    m = re.search(pattern, text, flags)
    if not m:
        die(f"could not read {what} from rules.md (pattern {pattern!r})")
    return m


def parse_date(s):
    return datetime.strptime(s.strip().rstrip("."), "%m/%d/%Y")


def fmt_date(d):
    return f"{d.month}/{d.day}"


def split_list(v):
    return [p.strip() for p in str(v or "").split(";") if p.strip()]


def header_rows(ws):
    """Return (header, data_rows) where header is the first row whose first
    cell is a non-empty column title followed by other titles."""
    rows = list(ws.iter_rows(values_only=True))
    for i, r in enumerate(rows):
        filled = [c for c in r if c is not None]
        if len(filled) >= 2 and all(isinstance(c, str) for c in filled):
            return [str(c).strip() if c else "" for c in r], rows[i + 1:]
    die(f"no header row in sheet {ws.title}")


def col(header, *keys):
    for i, h in enumerate(header):
        hl = h.lower()
        if all(k.lower() in hl for k in keys):
            return i
    die(f"no column matching {keys} in header {header}")


# --------------------------------------------------------------------------
# Read rules.md
# --------------------------------------------------------------------------
def read_rules():
    text = RULES.read_text(encoding="utf-8")
    sec = {}
    cur = None
    for line in text.splitlines():
        if line.startswith("## "):
            cur = line[3:].strip()
            sec[cur] = []
        elif cur:
            sec[cur].append(line)
    hard_key = next((k for k in sec if k.lower().startswith("hard rules")), None)
    wish_key = next((k for k in sec if k.lower().startswith("wishes")), None)
    surv_key = next((k for k in sec if k.lower().startswith("survey")), None)
    if not hard_key or not wish_key:
        die("rules.md needs '## Hard rules' and '## Wishes' sections")
    hard = [l.strip() for l in sec[hard_key] if re.match(r"\s*\d+\.", l)]
    wishes = [l.strip() for l in sec[wish_key] if re.match(r"\s*\d+\.", l)]
    survey_rules = [l.strip()[2:] for l in sec.get(surv_key, []) if l.strip().startswith("- ")]
    hard_txt = "\n".join(hard)

    R = {"hard": hard, "wishes": wishes, "survey": survey_rules, "text": text}
    m = need(r"(\d{1,2}/\d{1,2}/\d{4})", text, "training date")
    R["day"] = parse_date(m.group(1))
    R["min_size"] = int(need(r"at least (\d+) people", hard_txt, "minimum session size").group(1))
    m = need(r"forklift card expires before (\d{1,2}/\d{1,2}/\d{4}) is in (S\d+)", hard_txt, "forklift rule", re.I)
    R["fork_cut"], R["fork_sess"] = parse_date(m.group(1)), m.group(2)
    R["fork_rule"] = rule_no(hard, m.group(0))
    m = need(r"refresher is due on or before (\d{1,2}/\d{1,2}/\d{4}) is in (S\d+)", hard_txt, "lockout/tagout rule", re.I)
    R["loto_cut"], R["loto_sess"] = parse_date(m.group(1)), m.group(2)
    R["loto_rule"] = rule_no(hard, m.group(0))
    R["sess_not_slot"] = []  # (session, slot, rule#)
    for m in re.finditer(r"(S\d+)\b[^.\n]*? is not in slot (\d+)", hard_txt):
        R["sess_not_slot"].append((m.group(1), int(m.group(2)), rule_no(hard, m.group(0))))
    R["person_not_slot"] = []  # (name, slot, rule#)
    for m in re.finditer(r"^\d+\.\s+(.+?) is not in any session in slot (\d+)", hard_txt, re.M):
        R["person_not_slot"].append((m.group(1).strip(), int(m.group(2)), rule_no(hard, m.group(0))))
    R["min_sessions"] = int(need(r"in a session in at least (\d+) of", hard_txt, "minimum sessions per person").group(1))
    pts = []
    for w in wishes:
        m = need(r"(\d+) points?", w, "wish points")
        pts.append(int(m.group(1)))
    if len(pts) != 3:
        die("expected three wishes in rules.md")
    R["points"] = pts
    return R


def rule_no(lines, frag):
    for l in lines:
        if frag.split("\n")[0][:40] in l:
            return int(l.split(".")[0])
    return None


# --------------------------------------------------------------------------
# Read workbooks
# --------------------------------------------------------------------------
def read_sessions():
    wb = openpyxl.load_workbook(F_SESS, read_only=True, data_only=True)
    ws = wb["Sessions"] if "Sessions" in wb.sheetnames else wb.worksheets[0]
    h, rows = header_rows(ws)
    ci, ct, ctr, cg, ccap = col(h, "session id"), col(h, "title"), col(h, "trainer"), col(h, "good for"), col(h, "cap")
    sessions = {}
    for r in rows:
        if not r or not r[ci]:
            continue
        sid = str(r[ci]).strip()
        sessions[sid] = {
            "id": sid,
            "title": str(r[ct]).strip(),
            "trainers": split_list(r[ctr]),
            "good": split_list(r[cg]),
            "cap": int(r[ccap]) if r[ccap] not in (None, "") else None,
        }
    ws2 = next(w for w in wb.worksheets if w is not ws)
    slots, rooms = [], []
    for r in ws2.iter_rows(values_only=True):
        r = list(r) + [None] * 4
        if isinstance(r[0], str) and re.match(r"Slot\s*\d+$", r[0].strip()):
            slots.append({"n": int(re.findall(r"\d+", r[0])[0]), "time": str(r[1]).strip()})
        if r[2] and isinstance(r[3], (int, float)):
            rooms.append({"name": str(r[2]).strip(), "seats": int(r[3])})
    slots.sort(key=lambda s: s["n"])
    if not slots or not rooms:
        die("could not read slots/rooms from the sessions workbook")
    return sessions, slots, rooms


def read_roster(R):
    wb = openpyxl.load_workbook(F_ROSTER, read_only=True, data_only=True)
    h, rows = header_rows(wb.worksheets[0])
    cn, cd, ctl = col(h, "name"), col(h, "department"), col(h, "title")
    cf, cl, co = col(h, "forklift"), col(h, "lockout"), col(h, "out on")
    people = []
    for r in rows:
        if not r or not r[cn]:
            continue
        people.append({
            "name": str(r[cn]).strip(),
            "dept": str(r[cd]).strip(),
            "title": str(r[ctl] or "").strip(),
            "fork": r[cf] if isinstance(r[cf], datetime) else None,
            "loto": r[cl] if isinstance(r[cl], datetime) else None,
            "out": str(r[co]).strip() if r[co] not in (None, "") else None,
        })
    return people, h[co]


def read_floor():
    wb = openpyxl.load_workbook(F_FLOOR, read_only=True, data_only=True)
    h, rows = header_rows(wb.worksheets[0])
    cd, cm = col(h, "department"), col(h, "minimum")
    return {str(r[cd]).strip(): int(r[cm]) for r in rows if r and r[cd] and r[cm] is not None}


def read_survey(sessions, roster_names):
    title_to_id = {s["title"].lower(): sid for sid, s in sessions.items()}
    wb = openpyxl.load_workbook(F_SURVEY, read_only=True, data_only=True)
    h, rows = header_rows(wb.worksheets[0])
    cid, ccomp, cname = col(h, "id"), col(h, "completion"), col(h, "your name")
    cpick, cnote = col(h, "which sessions"), col(h, "anything")
    resp = {}
    for r in rows:
        if not r or r[cid] is None:
            continue
        picks, writeins = [], []
        for p in split_list(r[cpick]):
            sid = title_to_id.get(p.lower())
            if sid and sid not in picks:
                picks.append(sid)
            elif not sid:
                writeins.append(p)
        resp[int(r[cid])] = {"id": int(r[cid]), "when": r[ccomp], "survey_name": str(r[cname]).strip(),
                             "picks": picks, "writeins": writeins, "note": r[cnote]}
    # name map
    with open(F_MAP, newline="", encoding="utf-8-sig") as f:
        rows = list(csv.DictReader(f))
    keys = {k.lower(): k for k in rows[0].keys()}
    K = lambda *ws: next(keys[k] for k in keys if all(w in k for w in ws))
    k_id, k_sn, k_rn = K("response"), K("survey name"), K("roster name")
    k_chk, k_conf = K("needs", "check"), K("confirmed")
    used, skipped = {}, []  # roster name -> response
    for m in rows:
        rid = int(m[k_id])
        rn = (m[k_rn] or "").strip()
        chk = (m[k_chk] or "").strip().lower()
        conf = (m[k_conf] or "").strip().lower()
        rr = resp.get(rid)
        if rr is None:
            skipped.append((rid, m[k_sn], "no matching survey response"))
            continue
        if not rn:
            skipped.append((rid, rr["survey_name"], "no roster name in name-map.csv"))
            continue
        if chk == "yes" and conf != "yes":
            skipped.append((rid, rr["survey_name"], "needs a person check and is not confirmed"))
            continue
        if rn not in roster_names:
            skipped.append((rid, rr["survey_name"], f"roster name '{rn}' not on roster"))
            continue
        rr = dict(rr, roster=rn, how=m.get(K("how")))
        if rn in used:
            a, b = used[rn], rr
            later, earlier = (b, a) if b["when"] >= a["when"] else (a, b)
            later["replaced"] = earlier["id"]
            used[rn] = later
            skipped.append((earlier["id"], earlier["survey_name"], f"earlier reply; later reply {later['id']} used"))
        else:
            used[rn] = rr
    unmapped = sorted(set(resp) - {int(m[k_id]) for m in rows})
    for rid in unmapped:
        skipped.append((rid, resp[rid]["survey_name"], "not in name-map.csv"))
    return used, skipped


# --------------------------------------------------------------------------
# Slot orders
# --------------------------------------------------------------------------
def slot_orders(sids, n_slots, per_slot):
    """Every ordered split of the sessions into n_slots groups of per_slot."""
    out = []

    def rec(rest, acc):
        if not rest:
            out.append(tuple(acc))
            return
        for grp in itertools.combinations(rest, per_slot):
            rec([s for s in rest if s not in grp], acc + [grp])

    rec(list(sids), [])
    return out


# --------------------------------------------------------------------------
# Model
# --------------------------------------------------------------------------
class Data:
    pass


def build(D, order, guarded=False):
    """Build the CP-SAT model for one slot order. With guarded=True each hard
    rule is switched by an assumption literal so infeasibility can be traced
    to rules."""
    m = cp_model.CpModel()
    slot_of = {s: t for t, grp in enumerate(order) for s in grp}
    lits = {}

    def G(rule):
        if not guarded:
            return []
        if rule not in lits:
            lits[rule] = m.NewBoolVar(f"rule{rule}")
        return [lits[rule]]

    W = D.working
    x = {(p, s): m.NewBoolVar(f"x{p}_{s}") for p in W for s in D.sids}
    # Rule 2: at most one session per slot (otherwise on the floor)
    for p in W:
        for grp in order:
            m.Add(sum(x[p, s] for s in grp) <= 1).OnlyEnforceIf(G(2))
    # Rule 4: at least N sessions
    for p in W:
        m.Add(sum(x[p, s] for s in D.sids) >= D.R["min_sessions"]).OnlyEnforceIf(G(4))
    # Rooms: each session one room, each room one session per slot (rule 1)
    rn = [r["name"] for r in D.rooms]
    y = {(s, r): m.NewBoolVar(f"y{s}_{r}") for s in D.sids for r in rn}
    for s in D.sids:
        m.AddExactlyOne(y[s, r] for r in rn)
    for grp in order:
        for r in rn:
            m.AddExactlyOne(y[s, r] for s in grp)
    size = {s: sum(x[p, s] for p in W) for s in D.sids}
    # Rule 5: min size and cap (room seats or session cap, whichever lower)
    for s in D.sids:
        m.Add(size[s] >= D.R["min_size"]).OnlyEnforceIf(G(5))
        for r in D.rooms:
            cap = min(r["seats"], D.sessions[s]["cap"] or r["seats"])
            m.Add(size[s] <= cap).OnlyEnforceIf(G(5) + [y[s, r["name"]]])
    # Rule 6: trainers attend what they teach
    for s in D.sids:
        for t in D.sessions[s]["trainers"]:
            m.Add(x[t, s] == 1).OnlyEnforceIf(G(6))
    # Rule 7: floor coverage
    for t, grp in enumerate(order):
        for dept, mn in D.floor.items():
            members = [p for p in W if D.dept[p] == dept]
            if mn > 0:
                # floor count = members - (#members in any session of this slot)
                m.Add(len(members) - sum(x[p, s] for p in members for s in grp) >= mn).OnlyEnforceIf(G(7))
    # Rules 8, 9: required sessions
    for p, s, rule in D.required:
        m.Add(x[p, s] == 1).OnlyEnforceIf(G(rule))
    # Rule 10-type: session not in a slot (order level)
    for s, slot, rule in D.R["sess_not_slot"]:
        if slot_of[s] == slot - 1:
            if guarded:
                m.AddBoolAnd([G(rule)[0].Not()])
            else:
                m.AddBoolOr([])  # infeasible
    # Rule 11-type: person not in any session in a slot
    for name, slot, rule in D.R["person_not_slot"]:
        for s in order[slot - 1]:
            m.Add(x[name, s] == 0).OnlyEnforceIf(G(rule))

    picks = sum(x[p, s] for p in W for s in D.picks.get(p, []))
    fit = sum(x[p, s] for p in W for s in D.sids if D.dept[p] in D.sessions[s]["good"])
    diffs = []
    for t, grp in enumerate(order):
        hi = m.NewIntVar(0, len(W), f"hi{t}")
        lo = m.NewIntVar(0, len(W), f"lo{t}")
        m.AddMaxEquality(hi, [size[s] for s in grp])
        m.AddMinEquality(lo, [size[s] for s in grp])
        diffs.append(hi - lo)
    imbalance = sum(diffs)
    return m, x, y, picks, fit, imbalance, lits


def make_solver(workers=8):
    sv = cp_model.CpSolver()
    sv.parameters.num_workers = workers
    sv.parameters.max_time_in_seconds = 20.0  # safety only; status is checked
    return sv


def solve_order(D, order):
    """Lexicographic: max picks, then max fit, then min imbalance."""
    m, x, y, picks, fit, imb, _ = build(D, order)
    sv = make_solver()
    vals = []
    proven = True
    for i, (expr, sense) in enumerate([(picks, "max"), (fit, "max"), (imb, "min")]):
        (m.Maximize if sense == "max" else m.Minimize)(expr)
        st = sv.Solve(m)
        if st == cp_model.INFEASIBLE:
            return None
        if st not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
            die(f"solver returned {sv.StatusName(st)} for order {order}")
        proven &= st == cp_model.OPTIMAL
        v = int(round(sv.ObjectiveValue()))
        vals.append(v)
        m.Add(expr == v)
        # hint the next stage with this solution
        m.ClearHints()
        for k, var in list(x.items()) + list(y.items()):
            m.AddHint(var, sv.Value(var))
    assign = {p: [next((s for s in grp if sv.Value(x[p, s])), FLOOR) for grp in order] for p in D.working}
    rooms = {s: next(r["name"] for r in D.rooms if sv.Value(y[s, r["name"]])) for s in D.sids}
    return {"order": order, "picks": vals[0], "fit": vals[1], "imb": vals[2], "proven": proven,
            "assign": assign, "rooms": rooms}


def diagnose(D, order):
    m, *_, lits = build(D, order, guarded=True)
    m.AddAssumptions(list(lits.values()))
    sv = make_solver()
    st = sv.Solve(m)
    if st != cp_model.INFEASIBLE:
        return []
    core = set(sv.SufficientAssumptionsForInfeasibility())
    return sorted(r for r, l in lits.items() if l.Index() in core)


# --------------------------------------------------------------------------
# Explanations
# --------------------------------------------------------------------------
def miss_reason(D, best, p, s):
    order, assign = best["order"], best["assign"]
    t = next(i for i, g in enumerate(order) if s in g)
    here = assign[p][t]
    size = Counter(v for a in assign.values() for v in a)
    if here != FLOOR:
        if p in D.sessions[here]["trainers"]:
            return f"teaching {here} in the same slot", "Teaching another session in that slot"
        if (p, here) in D.req_set:
            return f"required {here} in the same slot", "Required session in the same slot"
        if here in D.picks.get(p, []):
            return f"picked {here} in the same slot", "Two picks share a slot"
        if size[here] <= D.R["min_size"]:
            return f"kept in {here} to hold it at the {D.R['min_size']}-person minimum", "Needed to fill another session to the minimum"
    for name, slot, rule in D.R["person_not_slot"]:
        if name == p and slot == t + 1:
            return f"not allowed in a session in slot {slot} (hard rule {rule})", f"Hard rule {rule} (no session in slot {slot})"
    cap = D.cap_in_room(s, best["rooms"][s])
    if size[s] >= cap:
        return f"{s} full ({cap} seats)", "Session full"
    if here == FLOOR:
        on_floor = sum(1 for q in D.working if D.dept[q] == D.dept[p] and assign[q][t] == FLOOR)
        mn = D.floor.get(D.dept[p], 0)
        if on_floor <= mn:
            return f"needed on the floor in slot {t+1} ({D.dept[p]} minimum {mn})", "Floor coverage"
    return "trade-off with other picks", "Trade-off with other picks"


# --------------------------------------------------------------------------
# Output
# --------------------------------------------------------------------------
HDR_FONT = Font(bold=True, color="FFFFFF")
HDR_FILL = PatternFill("solid", fgColor="305496")


def style_header(ws, widths):
    for c in ws[1]:
        c.font, c.fill = HDR_FONT, HDR_FILL
        c.alignment = Alignment(wrap_text=True, vertical="center")
    for i, w in enumerate(widths, 1):
        ws.column_dimensions[get_column_letter(i)].width = w
    ws.freeze_panes = "A2"


def write_plan(D, best):
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Assignments"
    ws.append(["Name"] + [f"Slot {sl['n']}" for sl in D.slots])
    for p in D.people:
        n = p["name"]
        ws.append([n] + ([OUT] * len(D.slots) if p["out"] else best["assign"][n]))
    ws2 = wb.create_sheet("Sessions")
    ws2.append(["Session ID", "Slot", "Room"])
    for s in D.sids:
        t = next(i for i, g in enumerate(best["order"]) if s in g)
        ws2.append([s, D.slots[t]["n"], best["rooms"][s]])
    wb.save(OUT_PLAN)


def write_schedule(D, best, notes_by_person, picks_by_person, choices):
    wb = openpyxl.Workbook()
    order, assign, rooms = best["order"], best["assign"], best["rooms"]
    nS = len(D.slots)
    room_order = [r["name"] for r in D.rooms]

    # --- Assignments tab (written first so formulas reference it) ---
    wa = wb.active
    wa.title = "Assignments"
    head = ["Name", "Department", "Survey picks"]
    for sl in D.slots:
        head += [f"Slot {sl['n']} session", f"Slot {sl['n']} room"]
    head += ["Picks honored", "Note"]
    wa.append(head)
    slot_col = {}
    for t in range(nS):
        slot_col[t] = get_column_letter(4 + 2 * t)
    for p in D.people:
        n = p["name"]
        row = [n, p["dept"], ", ".join(D.picks.get(n, [])) or ("(no usable reply)" if not p["out"] else "")]
        for t in range(nS):
            if p["out"]:
                row += [OUT, ""]
            else:
                v = assign[n][t]
                row += [v, rooms[v] if v != FLOOR else ""]
        pk = D.picks.get(n, [])
        row.append(f"{picks_by_person.get(n, 0)} of {len(pk)}" if pk and not p["out"] else "")
        row.append("; ".join(notes_by_person.get(n, [])))
        wa.append(row)
    last = wa.max_row
    style_header(wa, [20, 22, 16] + [12, 14] * nS + [10, 80])

    # --- Schedule tab ---
    ws = wb.create_sheet("Schedule", 0)
    ws.append(["Slot", "Time", "Room", "Session ID", "Session", "Trainer(s)", "Headcount", "Cap", "Constraint Check"])
    for t, grp in enumerate(order):
        for s in sorted(grp, key=lambda s: room_order.index(rooms[s])):
            r = ws.max_row + 1
            c = slot_col[t]
            ws.append([D.slots[t]["n"], D.slots[t]["time"], rooms[s], s, D.sessions[s]["title"],
                       "; ".join(D.sessions[s]["trainers"]),
                       f'=COUNTIF(Assignments!${c}$2:${c}${last},D{r})',
                       D.cap_in_room(s, rooms[s]),
                       f'=IF(OR(G{r}<{D.R["min_size"]},G{r}>H{r}),"CHECK","OK")'])
    ws.append([])
    ws.append(["Floor coverage check", "", "Department", "Minimum on floor"] +
              [f"Slot {sl['n']} on floor" for sl in D.slots] + ["Check"])
    hdr = ws.max_row
    for cell in ws[hdr]:
        cell.font = Font(bold=True)
    for dept, mn in D.floor.items():
        r = ws.max_row + 1
        cells = [f'=COUNTIFS(Assignments!$B$2:$B${last},C{r},Assignments!${slot_col[t]}$2:${slot_col[t]}${last},"{FLOOR}")'
                 for t in range(nS)]
        first, lastc = get_column_letter(5), get_column_letter(4 + nS)
        ws.append(["", "", dept, mn] + cells + [f'=IF(MIN({first}{r}:{lastc}{r})<D{r},"CHECK","OK")'])
    style_header(ws, [6, 15, 15, 11, 48, 28, 11, 8, 16])

    # --- Notes tab ---
    wn = wb.create_sheet("Notes")
    wn.append(["Section", "Item", "How the solver reads it"])
    interp = D.interp
    for line in D.R["hard"]:
        k = int(line.split(".")[0])
        wn.append(["Hard rule", line, interp.get(k, "Enforced as written.")])
    for i, line in enumerate(D.R["wishes"], 1):
        wn.append([f"Wish {i}", line, D.wish_interp[i - 1]])
    for line in D.R["survey"]:
        wn.append(["Survey rule", line, ""])
    for c in choices:
        wn.append(["Choice / result", c, ""])
    style_header(wn, [16, 90, 90])
    for row in wn.iter_rows(min_row=2):
        for c in row:
            c.alignment = Alignment(wrap_text=True, vertical="top")
    wb.save(OUT_SCHED)


# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def main():
    t0 = time.time()
    D = Data()
    D.R = R = read_rules()
    D.sessions, D.slots, D.rooms = read_sessions()
    D.sids = sorted(D.sessions, key=lambda s: int(s[1:]))
    D.people, out_col = read_roster(R)
    D.floor = read_floor()
    names = [p["name"] for p in D.people]
    if len(set(names)) != len(names):
        die("duplicate names on the roster")
    D.dept = {p["name"]: p["dept"] for p in D.people}
    D.working = [p["name"] for p in D.people if not p["out"]]
    D.cap_in_room = lambda s, room: min(next(r["seats"] for r in D.rooms if r["name"] == room),
                                        D.sessions[s]["cap"] or 10 ** 9)

    for d in D.floor:
        if d not in set(D.dept.values()):
            die(f"floor coverage department '{d}' not on roster")
    for s in D.sids:
        for tr in D.sessions[s]["trainers"]:
            if tr not in D.dept:
                die(f"trainer '{tr}' for {s} is not on the roster")
            if tr not in D.working:
                die(f"trainer '{tr}' for {s} is out on the training day (hard rules 3 and 6 conflict)")
    for name, *_ in R["person_not_slot"]:
        if name not in D.dept:
            die(f"rules.md names '{name}', who is not on the roster")
    if len(D.sids) != len(D.slots) * len(D.rooms):
        die(f"hard rule 1: {len(D.sids)} sessions cannot fill {len(D.slots)} slots x {len(D.rooms)} rooms exactly")

    # required sessions
    D.required, D.req_note = [], defaultdict(list)
    for p in D.people:
        if p["out"]:
            continue
        if p["fork"] and p["fork"] < R["fork_cut"]:
            D.required.append((p["name"], R["fork_sess"], R["fork_rule"]))
            D.req_note[p["name"]].append(f"Required {R['fork_sess']}: forklift card expires {fmt_date(p['fork'])}")
        if p["loto"] and p["loto"] <= R["loto_cut"]:
            D.required.append((p["name"], R["loto_sess"], R["loto_rule"]))
            D.req_note[p["name"]].append(f"Required {R['loto_sess']}: lockout/tagout due {fmt_date(p['loto'])}")
    D.req_set = {(p, s) for p, s, _ in D.required}

    # survey
    used, skipped = read_survey(D.sessions, set(names))
    D.picks = {n: r["picks"] for n, r in used.items() if n in D.working and r["picks"]}
    total_picks = sum(len(v) for v in D.picks.values())

    # ---- solve every slot order ----
    orders = slot_orders(D.sids, len(D.slots), len(D.rooms))
    results, blocked = [], {}
    for od in orders:
        res = solve_order(D, od)
        if res is None:
            blocked[od] = diagnose(D, od)
        else:
            results.append(res)
    if not results:
        print(f"No plan fits. All {len(orders)} slot orders are infeasible; no rule was loosened.")
        cnt = Counter(tuple(v) for v in blocked.values())
        for rules, n in cnt.most_common():
            txt = " + ".join(f"hard rule {r}" for r in rules) or "unknown"
            print(f"  {n} orders blocked by {txt}")
            for r in rules:
                line = next((l for l in R["hard"] if l.startswith(f"{r}.")), "")
                print(f"      {line}")
        sys.exit(2)

    key = lambda r: (r["picks"], r["fit"], -r["imb"])
    results.sort(key=key, reverse=True)
    best = results[0]
    tie_picks = sum(1 for r in results if r["picks"] == best["picks"])
    tie_all = sum(1 for r in results if key(r) == key(best))
    all_proven = all(r["proven"] for r in results)

    # ---- self-check of hard rules on the chosen plan ----
    A = best["assign"]
    size = Counter(v for a in A.values() for v in a if v != FLOOR)
    for s in D.sids:
        assert R["min_size"] <= size[s] <= D.cap_in_room(s, best["rooms"][s]), s
        for tr in D.sessions[s]["trainers"]:
            assert s in A[tr]
    for p in D.working:
        assert sum(v != FLOOR for v in A[p]) >= R["min_sessions"]
    for p, s, _ in D.required:
        assert s in A[p]
    for t in range(len(D.slots)):
        for dept, mn in D.floor.items():
            assert sum(1 for p in D.working if D.dept[p] == dept and A[p][t] == FLOOR) >= mn

    # ---- per-person notes ----
    notes, honored = defaultdict(list), {}
    miss_groups = defaultdict(list)
    for p in D.people:
        n = p["name"]
        if p["out"]:
            notes[n].append(f"{OUT} on {fmt_date(R['day'])} ({p['out']})")
            if n in used:
                notes[n].append("survey reply not used (out that day)")
            continue
        for s in D.sids:
            if n in D.sessions[s]["trainers"]:
                notes[n].append(f"LOCKED - Trainer {s}")
        notes[n].extend(D.req_note.get(n, []))
        for name, slot, rule in R["person_not_slot"]:
            if name == n:
                notes[n].append(f"No session in slot {slot} (hard rule {rule})")
        if n in used:
            r = used[n]
            if r["survey_name"] != n:
                notes[n].append(f"Survey name '{r['survey_name']}' matched")
            if r.get("replaced"):
                notes[n].append(f"Answered twice; used later reply #{r['id']}")
            for w in r["writeins"]:
                notes[n].append(f"Write-in '{w}' not a session, not counted")
        else:
            notes[n].append("No usable survey reply - placed by department fit")
        got = 0
        for s in D.picks.get(n, []):
            if s in A[n]:
                got += 1
            else:
                why, grp = miss_reason(D, best, n, s)
                notes[n].append(f"Missed pick {s}: {why}")
                miss_groups[grp].append(f"{n} ({s})")
        honored[n] = got
    X = sum(honored.values())

    # ---- notes tab text ----
    D.interp = {
        1: f"Every ordered split of the {len(D.sids)} sessions into {len(D.slots)} slots of {len(D.rooms)} is tried "
           f"({len(orders)} slot orders). Inside each order the solver also picks which session gets which room.",
        2: "Each person is in at most one session per slot; otherwise on the floor.",
        3: f"Roster column '{out_col}' non-empty = Out in every slot, no survey used.",
        4: f"Each working person attends at least {R['min_sessions']} sessions (teaching counts).",
        5: f"Size >= {R['min_size']} and <= min(room seats, session cap), trainers included. The cap follows the room the solver picks.",
        6: "Each listed trainer is fixed into the session(s) they teach.",
        7: "Floor count = working people in the department not in a session that slot. Departments not in the file have no minimum.",
        R["fork_rule"]: f"Forklift card date strictly before {R['fork_cut']:%m/%d/%Y} -> must attend {R['fork_sess']}. Blank date = no card, not required.",
        R["loto_rule"]: f"Refresher date on or before {R['loto_cut']:%m/%d/%Y} -> must attend {R['loto_sess']}. Blank date = not required.",
    }
    for s, slot, rule in R["sess_not_slot"]:
        D.interp[rule] = f"Slot orders that put {s} in slot {slot} are rejected."
    for name, slot, rule in R["person_not_slot"]:
        D.interp[rule] = f"{name} is on the floor in slot {slot}."
    D.wish_interp = [
        f"Maximize picks honored ({R['points'][0]} pts each). Solved first and fixed at its proven best.",
        f"Then maximize department-fit attendances ({R['points'][1]} pts each), keeping wish 1 at its best. Trainers count too.",
        f"Then minimize sum over slots of the size gap between the two sessions ({R['points'][2]} pt per person), keeping wishes 1 and 2 at their best.",
    ]
    choices = [
        "Scoring is strictly lexicographic (solved in three stages per slot order) so a lower wish can never cost a higher one.",
        f"Survey: {len(used)} usable replies after name-map rules; {total_picks} countable picks from people working that day.",
    ]
    for rid, sn, why in sorted(skipped):
        choices.append(f"Survey reply #{rid} '{sn}' not used: {why}.")
    choices += [
        "Picks are matched to sessions by exact session title; anything else is a write-in and is dropped.",
        "A pick for a session a person teaches counts as honored (teaching counts as attending).",
        f"Slot orders tried: {len(orders)}; feasible: {len(results)}; tie on picks: {tie_picks}; tie on all three wishes: {tie_all}. "
        f"All optima proven: {'yes' if all_proven else 'NO'}.",
        f"Chosen plan: picks {best['picks']} x {R['points'][0]}, fit {best['fit']} x {R['points'][1]}, size gap {best['imb']} "
        f"(score {best['picks']*R['points'][0] + best['fit']*R['points'][1] - best['imb']*R['points'][2]}). "
        "Among tied plans the first one found is kept; a rerun may move people between equal spots.",
    ]
    infeas = Counter(tuple(v) for v in blocked.values())
    for rules, n in infeas.most_common():
        choices.append(f"{n} slot orders impossible, blocked by " + " + ".join(f"hard rule {r}" for r in rules) + ".")

    write_plan(D, best)
    write_schedule(D, best, notes, honored, choices)

    # ---- summary ----
    print(f"Slot orders: {len(orders)} tried, {len(results)} feasible, all proven optimal: {all_proven}")
    print("Best order: " + " | ".join(f"slot {t+1}: " + " + ".join(f"{s} ({best['rooms'][s]})" for s in g)
                                     for t, g in enumerate(best["order"])))
    print(f"Picks honored: {X} of {total_picks}")
    print(f"Department fit: {best['fit']}   size gap: {best['imb']}")
    print(f"Orders tied on picks honored: {tie_picks}; tied on all three wishes: {tie_all}")
    print("Missed picks by reason:")
    for g, lst in sorted(miss_groups.items(), key=lambda kv: -len(kv[1])):
        print(f"  {g}: {len(lst)} - " + ", ".join(lst))
    print("Infeasible orders by blocking rule(s): " +
          "; ".join(f"{' + '.join('R' + str(r) for r in k)}: {n}" for k, n in infeas.most_common()))
    print(f"Wrote {OUT_PLAN.name} and {OUT_SCHED.name} in {time.time() - t0:.1f}s")


if __name__ == "__main__":
    main()
