# RUN LOCATION: execute from the workspace root (the directory containing inputs/),
# e.g. `python output/check_schedule.py`. It reads inputs/ via relative paths.
"""Task 8 feasibility check. Std-lib only. All times in minutes from midnight Pacific.
Sources: inputs/availability.csv, inputs/rooms.csv, inputs/constraints.md, inputs/update.txt
"""
import csv, datetime

def m(s):
    h, mm = s.split(':'); return int(h)*60 + int(mm)

def hm(x):
    return f"{x//60:02d}:{x%60:02d}"

avail = {}
with open('inputs/availability.csv') as f:
    for r in csv.DictReader(f):
        avail.setdefault(r['person'], []).append((m(r['available_start']), m(r['available_end'])))

rooms = {}
with open('inputs/rooms.csv') as f:
    for r in csv.DictReader(f):
        rooms.setdefault(r['room'], []).append((m(r['available_start']), m(r['available_end'])))

def inside(person, a, b):
    """Return the single availability window fully containing [a,b], else None."""
    for w in avail.get(person, []):
        if w[0] <= a and b <= w[1]:
            return w
    return None

def room_free(room, a, b):
    return any(w[0] <= a and b <= w[1] for w in rooms.get(room, []))

LUNCH = (m('12:00'), m('13:00'))
DAY = (m('09:00'), m('17:00'))

print("Date weekday check:", datetime.date(2026, 10, 27).strftime('%A'))

feasible = []
rejects = {}
for start in range(DAY[0], DAY[1], 5):
    end = start + 45                 # main review 45 min
    prep = (start - 30, start)       # Theo prep immediately before
    setup = (start - 10, start)      # 10-min setup finishing at start
    fu = (end, end + 15)             # 15-min follow-up after review
    reasons = []
    # workday + lunch for every scheduled block
    for a, b in (prep, setup, (start, end), fu):
        if a < DAY[0] or b > DAY[1]:
            reasons.append('outside 09:00-17:00')
        if a < LUNCH[1] and b > LUNCH[0]:
            reasons.append('overlaps lunch')
    # required attendees for review, within one window each
    wM = inside('Maya', start, end)
    wT = inside('Theo', start, end)
    wJ = inside('Jules', start, end)
    if not wM: reasons.append('Maya not available for review')
    if not wT: reasons.append('Theo not available for review')
    if not wJ: reasons.append('Jules not available for review')
    # Theo prep within his availability (proxy for no meeting overlap)
    if not inside('Theo', *prep): reasons.append('Theo prep not in availability')
    # follow-up: Maya & Jules, same window that contained the review
    if not wM or not (wM[0] <= fu[0] and fu[1] <= wM[1]):
        reasons.append('follow-up outside Maya review window')
    if not wJ or not (wJ[0] <= fu[0] and fu[1] <= wJ[1]):
        reasons.append('follow-up outside Jules review window')
    room_ok = []
    for room in ('B', 'C'):
        if room_free(room, setup[0], end):  # room free through setup AND review
            room_ok.append(room)
    if not room_ok:
        reasons.append('no room free for setup+review (B/C)')
    if reasons:
        rejects[start] = sorted(set(reasons))
    else:
        nora = inside('Nora', start, end) is not None
        feasible.append((start, room_ok, nora))

print("\nFeasible starts (Pacific), rooms, Nora-can-attend:")
for s, r, n in feasible:
    print(f"  {hm(s)}-{hm(s+45)} rooms={r} nora={n}  UTC {hm(s+7*60)}-{hm(s+45+7*60)}")

print("\nRejection reasons for candidate starts near boundaries:")
for s in (m('09:30'), m('10:00'), m('10:05'), m('13:30'), m('14:00'), m('14:05'), m('14:10'), m('14:15'), m('14:30')):
    if s in rejects:
        print(f"  {hm(s)}: {'; '.join(rejects[s])}")
    else:
        print(f"  {hm(s)}: feasible")

if feasible:
    s, r, n = feasible[0]
    print(f"\nEARLIEST FEASIBLE: {hm(s)} Pacific, room(s) {r}")
    print(f"  Theo prep   {hm(s-30)}-{hm(s)} PT / {hm(s-30+420)}-{hm(s+420)} UTC")
    print(f"  Room setup  {hm(s-10)}-{hm(s)} PT / {hm(s-10+420)}-{hm(s+420)} UTC")
    print(f"  Main review {hm(s)}-{hm(s+45)} PT / {hm(s+420)}-{hm(s+45+420)} UTC")
    print(f"  Follow-up   {hm(s+45)}-{hm(s+60)} PT / {hm(s+45+420)}-{hm(s+60+420)} UTC (remote)")
