"""Check a training-day plan against the hard rules. One PASS or FAIL line per rule.

SAMPLE DATA. FICTIONAL COMPANY. NOT REAL. Mesquite Ridge Metal Works.

This checker does not use the solver's code. It reads the four input files, the
confirmed name map, and your plan, and counts everything again on its own.

Run (in the folder that holds the four input files):
  uv run --with openpyxl check_plan.py plan.xlsx
  uv run --with openpyxl check_plan.py plan.xlsx --change      (after Ray's change: Dale on the floor in slot 1)
Options:
  --data FOLDER      where the four input files are (default: this script's folder, then the current folder)
  --name-map FILE    the confirmed name map (default: answer-key/name-map.csv next to the inputs)

Plan format (plan.xlsx):
  Sheet "Assignments": columns Name, Slot 1, Slot 2, Slot 3. Each slot cell is a session ID (S1 to S6)
                       or "Floor". People out on 12/11 can be "Out" or left off.
  Sheet "Sessions":    columns Session ID, Slot (1, 2 or 3), Room (Training room or Break room).
"""
import argparse
import csv
import datetime as dt
import os
import re
import sys

from openpyxl import load_workbook

BEST = {"before": 64, "after": 63}  # from answer-key/answer-key.md (proven optimal with OR-Tools CP-SAT)
CUTOFF = dt.date(2026, 12, 31)
ROOM_SEATS = {"Training room": 24, "Break room": 40}
FILES = ["mrmw-training-sessions.xlsx", "mrmw-plant1-roster.xlsx", "mrmw-training-survey.xlsx", "mrmw-floor-coverage.xlsx"]
SHOW = 8  # rows to show under a FAIL


def table(path, sheet=None, key="name"):
    wb = load_workbook(path, data_only=True)
    ws = wb[sheet] if sheet else wb.worksheets[0]
    vals = list(ws.iter_rows(values_only=True))
    for i, r in enumerate(vals[:6]):
        if r and str(r[0] or "").strip().lower().startswith(key):
            head = [str(h).strip() if h is not None else "" for h in r]
            return [dict(zip(head, row)) for row in vals[i + 1:] if row and any(v not in (None, "") for v in row)]
    raise SystemExit(f"Could not find a header row starting with '{key}' in {os.path.basename(path)} {sheet or ''}")


def as_date(v):
    if v in (None, ""):
        return None
    if isinstance(v, dt.datetime):
        return v.date()
    if isinstance(v, dt.date):
        return v
    return dt.datetime.strptime(str(v).strip(), "%m/%d/%Y").date()


def find_data(arg):
    for d in ([arg] if arg else []) + [os.path.dirname(os.path.abspath(__file__)), os.getcwd()]:
        if all(os.path.exists(os.path.join(d, f)) for f in FILES):
            return d
    raise SystemExit("Could not find the four input files. Use --data FOLDER.")


def load_inputs(data, name_map_path):
    sessions = {}
    for s in table(os.path.join(data, FILES[0]), "Sessions", "session id"):
        sessions[str(s["Session ID"]).strip()] = {
            "title": str(s["Title"]).strip(),
            "trainers": [t.strip() for t in str(s["Trainer(s)"]).split(";") if t.strip()],
            "cap": int(s["Session cap"]) if s.get("Session cap") not in (None, "") else None,
        }
    roster = {}
    for r in table(os.path.join(data, FILES[1])):
        roster[str(r["Name"]).strip()] = {
            "dept": str(r["Department"]).strip(),
            "fork": as_date(r["Forklift card expires"]),
            "loto": as_date(r["Lockout/tagout refresher due"]),
            "out": bool(r["Out on 12/11"]),
        }
    survey = {int(r["ID"]): r for r in table(os.path.join(data, FILES[2]), key="id")}
    floor = {str(r["Department"]).strip(): int(r["Minimum on the floor every slot"]) for r in table(os.path.join(data, FILES[3]), key="department")}
    with open(name_map_path, newline="") as f:
        nmap = {int(r["Response ID"]): (r["Roster name"] or "").strip() for r in csv.DictReader(f)}
    # picks: later reply wins, people out are not counted, unmatched rows are set aside, write-ins ignored
    title_to_id = {v["title"]: k for k, v in sessions.items()}
    latest = {}
    for rid, row in survey.items():
        name = nmap.get(rid, "")
        if not name or name not in roster or roster[name]["out"]:
            continue
        when = row["Completion time"]
        if name not in latest or when > latest[name][0]:
            chosen = [title_to_id[p.strip()] for p in str(row["Which sessions do you want? Pick 2 or 3."] or "").split(";") if p.strip() in title_to_id]
            latest[name] = (when, chosen)
    picks = {n: v[1] for n, v in latest.items()}
    return sessions, roster, floor, picks


def read_plan(path, sessions):
    wb = load_workbook(path, data_only=True)
    names = {n.lower(): n for n in wb.sheetnames}
    problems = []
    if "assignments" not in names or "sessions" not in names:
        raise SystemExit(f"plan needs sheets 'Assignments' and 'Sessions'. Found: {wb.sheetnames}")
    assign = {}
    for r in table(path, names["assignments"], "name"):
        name = str(r.get("Name") or "").strip()
        if not name:
            continue
        cells = []
        for k in ("Slot 1", "Slot 2", "Slot 3"):
            v = str(r.get(k) or "").strip()
            m = re.match(r"^(S\d)\b", v.upper())
            if m and m.group(1) in sessions:
                cells.append(m.group(1))
            elif v.lower() in ("floor", "out", ""):
                cells.append(None)
            else:
                cells.append(None)
                problems.append(f"{name} {k}: '{v}' is not a session ID or Floor")
        if name in assign:
            problems.append(f"{name} is listed twice")
        assign[name] = cells
    layout = {}
    for r in table(path, names["sessions"], "session id"):
        col = {k.lower().split("(")[0].strip(): v for k, v in r.items() if k}  # "Slot (1, 2, or 3)" reads as "slot"
        sid = str(col.get("session id") or "").strip().upper()
        slot_m = re.search(r"[123]", str(col.get("slot") or ""))
        room = str(col.get("room") or "").strip()
        room = "Training room" if "training" in room.lower() else "Break room" if "break" in room.lower() else room
        layout[sid] = (int(slot_m.group(0)) if slot_m else None, room)
    return assign, layout, problems


def report(label, bad):
    print(f"{'PASS' if not bad else 'FAIL'}  {label}")
    for b in bad[:SHOW]:
        print(f"        {b}")
    if len(bad) > SHOW:
        print(f"        ... and {len(bad) - SHOW} more")
    return not bad


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("plan")
    ap.add_argument("--data")
    ap.add_argument("--name-map")
    ap.add_argument("--change", action="store_true", help="add Ray's change: Dale Pruitt stays on the floor in slot 1")
    a = ap.parse_args()
    data = find_data(a.data)
    nm = a.name_map or os.path.join(data, "answer-key", "name-map.csv")
    if not os.path.exists(nm):
        raise SystemExit(f"Could not find the confirmed name map at {nm}. Use --name-map FILE.")
    sessions, roster, floor, picks = load_inputs(data, nm)
    assign, layout, problems = read_plan(a.plan, sessions)
    working = [n for n, r in roster.items() if not r["out"]]
    print(f"Checking {os.path.basename(a.plan)}  ({'after the change' if a.change else 'rules as given'})")
    print(f"Inputs: {len(roster)} on roster, {len(working)} working 12/11, {len(picks)} survey replies used, {sum(len(v) for v in picks.values())} picks")
    print()
    ok = []

    unknown = [f"{n} is not on the roster" for n in assign if n not in roster]
    missing = [f"{n} is missing from the plan" for n in working if n not in assign]
    ok.append(report("Plan lists every working person once, and only roster names", problems + unknown + missing))

    bad = []
    for s in sessions:
        if s not in layout:
            bad.append(f"{s} has no slot and room")
            continue
        slot, room = layout[s]
        if slot not in (1, 2, 3):
            bad.append(f"{s} slot '{slot}' is not 1, 2 or 3")
        if room not in ROOM_SEATS:
            bad.append(f"{s} room '{room}' is not Training room or Break room")
    seen = {}
    for s, (slot, room) in layout.items():
        if s in sessions and (slot, room) in seen:
            bad.append(f"{s} and {seen[(slot, room)]} are both in the {room} in slot {slot}")
        seen[(slot, room)] = s
    ok.append(report("Each session runs once, in its own room and slot", bad))
    slot_of = {s: layout.get(s, (None, None))[0] for s in sessions}

    bad = [f"{n} slot {i + 1}: {c} runs in slot {slot_of[c]}, not slot {i + 1}"
           for n, cells in assign.items() for i, c in enumerate(cells) if c and slot_of.get(c) != i + 1]
    ok.append(report("Nobody is in two places at once (each session is in the slot it runs)", bad))

    bad = [f"{n} is out on 12/11 but has {c}" for n, cells in assign.items() if n in roster and roster[n]["out"] for c in cells if c]
    ok.append(report("People out on 12/11 are not scheduled", bad))

    bad = [f"{n} has {sum(1 for c in assign[n] if c)} session(s)" for n in working if n in assign and sum(1 for c in assign[n] if c) < 2]
    ok.append(report("Every working person attends at least 2 sessions", bad))

    size = {s: sum(1 for n, cells in assign.items() if s in cells and n in roster and not roster[n]["out"]) for s in sessions}
    bad = []
    for s in sessions:
        room = layout.get(s, (None, None))[1]
        cap = min(x for x in (ROOM_SEATS.get(room, 999), sessions[s]["cap"] or 999))
        if size[s] < 5:
            bad.append(f"{s} has {size[s]} people (minimum 5)")
        if size[s] > cap:
            bad.append(f"{s} has {size[s]} people, cap is {cap} ({room}{', session cap' if sessions[s]['cap'] else ''})")
    ok.append(report("Each session has 5 to its cap (room seats or session cap, trainers count)", bad))

    bad = [f"{t} is not in {s}" for s, v in sessions.items() for t in v["trainers"] if s not in assign.get(t, [])]
    ok.append(report("Trainers are in the sessions they teach", bad))

    bad = []
    for d, need in floor.items():
        members = [n for n in working if roster[n]["dept"] == d and n in assign]
        for i in range(3):
            on = sum(1 for n in members if not assign[n][i])
            if on < need:
                bad.append(f"slot {i + 1}: {d} has {on} on the floor, needs {need}")
    ok.append(report("Floor coverage minimum holds every slot", bad))

    bad = [f"{n} (card expires {roster[n]['fork']:%m/%d/%Y}) is not in S2" for n in working
           if roster[n]["fork"] and roster[n]["fork"] < CUTOFF and "S2" not in assign.get(n, [])]
    ok.append(report("Forklift card expiring before 12/31: in S2 Forklift recertification", bad))

    bad = [f"{n} (refresher due {roster[n]['loto']:%m/%d/%Y}) is not in S1" for n in working
           if roster[n]["loto"] and roster[n]["loto"] <= CUTOFF and "S1" not in assign.get(n, [])]
    ok.append(report("Lockout/tagout refresher due by 12/31: in S1 Lockout/tagout", bad))

    bad = [f"S2 is in slot 1"] if slot_of.get("S2") == 1 else []
    ok.append(report("Forklift recertification is not at 8:00 (dock busy)", bad))

    bad = [f"Hector Lee is in {assign['Hector Lee'][2]} in slot 3"] if assign.get("Hector Lee", [None] * 3)[2] else []
    ok.append(report("Hector Lee is free in slot 3 (10:00 schedule call)", bad))

    if a.change:
        bad = [f"Dale Pruitt is in {assign['Dale Pruitt'][0]} in slot 1"] if assign.get("Dale Pruitt", [None] * 3)[0] else []
        ok.append(report("Change: Dale Pruitt stays on the floor in slot 1", bad))

    honored = sum(1 for n, ps in picks.items() for s in ps
                  if s in assign.get(n, []) and slot_of.get(s) == assign[n].index(s) + 1)
    total = sum(len(v) for v in picks.values())
    best = BEST["after" if a.change else "before"]
    print()
    print(f"Picks honored: {honored} of {total}. Best possible under these rules: {best} of {total}.")
    fails = ok.count(False)
    if fails:
        print(f"{fails} hard rule(s) FAIL, so this plan cannot be used, whatever the score.")
    elif honored == best:
        print("Score matches the best in the answer key.")
    elif honored > best:
        print("Score is above the best possible. A hard rule must be broken, or the name map differs.")
    else:
        print(f"Score is {best - honored} below the best possible.")
    print(f"{len(ok) - fails} PASS, {fails} FAIL")
    return 1 if fails else 0


if __name__ == "__main__":
    sys.exit(main())
