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23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
"""
app.py β€” Nurse Rostering AI Agent Demo (Gradio)

4-Tab Dashboard:
  Tab 1 β†’ AI Chat (agent fills gaps)
  Tab 2 β†’ Roster View (white background, readable)
  Tab 3 β†’ Insights (macro gap analysis)
  Tab 4 β†’ Nurse Availability (search & filter)

Deploy:  gradio deploy
Local:   python app.py
"""

from __future__ import annotations

import gradio as gr
import pandas as pd
from collections import defaultdict

from mock_data import (
    MAX_SHIFTS_PER_WEEK,
    NUM_NURSES,
    NURSES_PER_SHIFT,
    SHIFTS,
    generate_nurses,
    generate_roster,
    get_unfilled_slots,
    week_number,
    nurse_shifts_in_week,
    nurse_works_on_day,
    eligible_nurses_for_slot,
    ShiftSlot,
    Nurse,
)
from agent import run_agent

# ── Global state ──────────────────────────────────────────────────────────────
nurses: list[Nurse] = []
roster: list[ShiftSlot] = []


def init_state():
    global nurses, roster
    nurses = generate_nurses()
    roster = generate_roster(nurses)


init_state()


# ═══════════════════════════════════════════════════════════════════════════════
# TAB 2 β€” ROSTER VIEW  (white background, high contrast)
# ═══════════════════════════════════════════════════════════════════════════════

def roster_to_html(roster: list[ShiftSlot]) -> str:
    days: dict[str, list[ShiftSlot]] = {}
    for slot in roster:
        days.setdefault(slot.day.isoformat(), []).append(slot)
    all_days = sorted(days.keys())

    total_slots = len(roster)
    unfilled_count = len(get_unfilled_slots(roster))
    filled_count = total_slots - unfilled_count
    total_assignments = sum(len(s.assigned) for s in roster)

    html = """
    <style>
        .r-wrap { font-family: 'Inter', -apple-system, sans-serif; }
        .r-stats { display: flex; gap: 24px; padding: 14px 20px; background: #f0f4f8; border-radius: 10px; margin-bottom: 16px; font-size: 14px; color: #1a1a2e; flex-wrap: wrap; }
        .r-stat { display: flex; align-items: center; gap: 6px; }
        .r-dot { width: 10px; height: 10px; border-radius: 50%; }
        .r-dot-green { background: #16a34a; }
        .r-dot-red { background: #dc2626; }
        .r-table { border-collapse: collapse; width: 100%; font-size: 13px; }
        .r-table th { background: #1e293b; color: #fff; padding: 10px 8px; text-align: center; border: 1px solid #cbd5e1; }
        .r-table td { padding: 8px 10px; border: 1px solid #cbd5e1; vertical-align: top; min-width: 150px; line-height: 1.6; }
        .r-filled { background: #f0fdf4; color: #14532d; }
        .r-unfilled { background: #fef2f2; color: #7f1d1d; }
        .r-week { background: #e2e8f0 !important; color: #0f172a; font-size: 14px; font-weight: 700; text-align: left; padding: 8px 14px; }
        .r-day { font-weight: 600; background: #f8fafc; color: #1e293b; text-align: center; white-space: nowrap; }
        .r-name { display: block; padding: 1px 0; font-size: 12.5px; }
        .r-gap { display: inline-block; background: #dc2626; color: #fff; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; margin-top: 4px; }
    </style>
    <div class="r-wrap">
    """

    html += f"""
    <div class="r-stats">
        <div class="r-stat"><b>πŸ₯ ICU Roster</b> Β· 2-Week Schedule</div>
        <div class="r-stat"><span class="r-dot r-dot-green"></span> Filled: {filled_count}/{total_slots}</div>
        <div class="r-stat"><span class="r-dot r-dot-red"></span> Unfilled: {unfilled_count}</div>
        <div class="r-stat">πŸ‘©β€βš•οΈ {NUM_NURSES} nurses Β· {total_assignments} assignments</div>
    </div>
    """

    html += '<table class="r-table"><tr><th>Date</th>'
    for sn, sh in SHIFTS:
        html += f"<th>{sn}<br><small>{sh}</small></th>"
    html += "</tr>"

    for i, dk in enumerate(all_days):
        if i == 0:
            html += '<tr><td colspan="4" class="r-week">πŸ“… Week 1</td></tr>'
        elif i == 7:
            html += '<tr><td colspan="4" class="r-week">πŸ“… Week 2</td></tr>'

        slots = days[dk]
        label = slots[0].day.strftime("%a %d %b")
        html += f'<tr><td class="r-day">{label}</td>'

        for slot in slots:
            cls = "r-unfilled" if slot.vacancies > 0 else "r-filled"
            cell = ""
            for n in slot.assigned:
                cell += f'<span class="r-name">πŸ‘©β€βš•οΈ {n.name.replace("Nurse ", "")}</span>'
            if slot.vacancies > 0:
                cell += f'<span class="r-gap">⚠️ NEED {slot.vacancies}</span>'
            html += f'<td class="{cls}">{cell}</td>'
        html += "</tr>"

    html += "</table></div>"
    return html


# ═══════════════════════════════════════════════════════════════════════════════
# TAB 3 β€” INSIGHTS
# ═══════════════════════════════════════════════════════════════════════════════

def build_insights_html(roster: list[ShiftSlot]) -> str:
    unfilled = get_unfilled_slots(roster)
    total = len(roster)
    filled = total - len(unfilled)
    fill_pct = filled / total * 100 if total else 0

    # Gaps by shift type
    gap_by_shift: dict[str, int] = defaultdict(int)
    for s in unfilled:
        gap_by_shift[s.shift_name] += s.vacancies

    # Gaps by week
    gap_by_week: dict[int, int] = defaultdict(int)
    for s in unfilled:
        w = week_number(s, roster)
        gap_by_week[w] += s.vacancies

    # Nurse utilisation
    nurse_load: dict[int, dict[int, int]] = defaultdict(lambda: defaultdict(int))
    for s in roster:
        w = week_number(s, roster)
        for n in s.assigned:
            nurse_load[n.id][w] += 1

    at_max = sum(1 for nw in nurse_load.values() for c in nw.values() if c >= MAX_SHIFTS_PER_WEEK)

    bar_col = "#16a34a" if fill_pct >= 95 else "#f59e0b" if fill_pct >= 85 else "#dc2626"

    html = """
    <style>
        .ins { font-family: 'Inter', -apple-system, sans-serif; color: #1e293b; }
        .kpi-row { display: flex; gap: 16px; flex-wrap: wrap; margin-bottom: 24px; }
        .kpi { flex: 1; min-width: 160px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; text-align: center; }
        .kpi-val { font-size: 32px; font-weight: 800; margin-bottom: 4px; }
        .kpi-label { font-size: 13px; color: #64748b; }
        .bar-outer { width: 100%; height: 14px; background: #e2e8f0; border-radius: 7px; overflow: hidden; margin-top: 8px; }
        .bar-inner { height: 100%; border-radius: 7px; }
        .section { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 16px; }
        .section h3 { margin: 0 0 12px; font-size: 15px; color: #334155; }
        .gap-table { width: 100%; border-collapse: collapse; font-size: 13px; }
        .gap-table th { background: #f1f5f9; padding: 8px 12px; text-align: left; border-bottom: 2px solid #e2e8f0; color: #475569; }
        .gap-table td { padding: 8px 12px; border-bottom: 1px solid #f1f5f9; }
        .badge-red { background: #fee2e2; color: #991b1b; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
        .badge-green { background: #dcfce7; color: #166534; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
    </style>
    <div class="ins">
    """

    html += f"""
    <div class="kpi-row">
        <div class="kpi">
            <div class="kpi-val" style="color:{bar_col}">{fill_pct:.0f}%</div>
            <div class="kpi-label">Fill Rate</div>
            <div class="bar-outer"><div class="bar-inner" style="width:{fill_pct}%;background:{bar_col}"></div></div>
        </div>
        <div class="kpi">
            <div class="kpi-val" style="color:#dc2626">{len(unfilled)}</div>
            <div class="kpi-label">Unfilled Shifts</div>
        </div>
        <div class="kpi">
            <div class="kpi-val" style="color:#0ea5e9">{total}</div>
            <div class="kpi-label">Total Shifts (2 weeks)</div>
        </div>
        <div class="kpi">
            <div class="kpi-val" style="color:#8b5cf6">{at_max}</div>
            <div class="kpi-label">Nurse-Weeks at Max (5/5)</div>
        </div>
    </div>
    """

    # Gaps by shift type
    html += '<div class="section"><h3>πŸ“Š Gaps by Shift Type</h3><table class="gap-table"><tr><th>Shift</th><th>Unfilled Slots</th></tr>'
    for sn, _ in SHIFTS:
        cnt = gap_by_shift.get(sn, 0)
        badge = f'<span class="badge-red">{cnt}</span>' if cnt > 0 else '<span class="badge-green">0</span>'
        html += f"<tr><td>{sn}</td><td>{badge}</td></tr>"
    html += "</table></div>"

    # Gaps by week
    html += '<div class="section"><h3>πŸ“… Gaps by Week</h3><table class="gap-table"><tr><th>Week</th><th>Unfilled Slots</th></tr>'
    for w in sorted(gap_by_week.keys()):
        cnt = gap_by_week[w]
        badge = f'<span class="badge-red">{cnt}</span>' if cnt > 0 else '<span class="badge-green">0</span>'
        html += f"<tr><td>Week {w}</td><td>{badge}</td></tr>"
    if not gap_by_week:
        html += '<tr><td colspan="2">βœ… No gaps</td></tr>'
    html += "</table></div>"

    # Unfilled shift detail
    if unfilled:
        html += '<div class="section"><h3>πŸ”΄ Unfilled Shift Details</h3><table class="gap-table"><tr><th>#</th><th>Date</th><th>Day</th><th>Shift</th><th>Vacancies</th></tr>'
        for i, s in enumerate(unfilled, 1):
            html += f'<tr><td>{i}</td><td>{s.day.strftime("%d %b %Y")}</td><td>{s.day.strftime("%A")}</td><td>{s.shift_name} ({s.shift_hours})</td><td><span class="badge-red">{s.vacancies}</span></td></tr>'
        html += "</table></div>"
    else:
        html += '<div class="section"><h3>βœ… All shifts are fully covered!</h3></div>'

    html += "</div>"
    return html


# ═══════════════════════════════════════════════════════════════════════════════
# TAB 4 β€” NURSE AVAILABILITY (search / filter)
# ═══════════════════════════════════════════════════════════════════════════════

def build_nurse_table(name_filter: str, week_filter: str, availability_filter: str) -> str:
    """Build an HTML table of nurses with their weekly loads and availability."""

    week_num = None
    if week_filter and week_filter != "All":
        week_num = int(week_filter.replace("Week ", ""))

    only_available = availability_filter == "Has Capacity"

    rows = []
    for n in nurses:
        if name_filter and name_filter.lower() not in n.name.lower():
            continue

        w1 = nurse_shifts_in_week(n, roster, 1)
        w2 = nurse_shifts_in_week(n, roster, 2)
        cap1 = MAX_SHIFTS_PER_WEEK - w1
        cap2 = MAX_SHIFTS_PER_WEEK - w2

        days_w1 = sorted(set(
            s.day for s in roster
            if week_number(s, roster) == 1 and n in s.assigned
        ))
        days_w2 = sorted(set(
            s.day for s in roster
            if week_number(s, roster) == 2 and n in s.assigned
        ))

        if week_num == 1 and only_available and cap1 <= 0:
            continue
        if week_num == 2 and only_available and cap2 <= 0:
            continue
        if week_num is None and only_available and cap1 <= 0 and cap2 <= 0:
            continue

        rows.append({
            "nurse": n,
            "w1": w1, "w2": w2,
            "cap1": cap1, "cap2": cap2,
            "days_w1": days_w1, "days_w2": days_w2,
        })

    html = """
    <style>
        .na { font-family: 'Inter', -apple-system, sans-serif; color: #1e293b; }
        .na-count { font-size: 14px; color: #64748b; margin-bottom: 12px; }
        .na-table { width: 100%; border-collapse: collapse; font-size: 13px; }
        .na-table th { background: #f1f5f9; padding: 10px 12px; text-align: left; border-bottom: 2px solid #e2e8f0; color: #475569; font-weight: 600; }
        .na-table td { padding: 10px 12px; border-bottom: 1px solid #f1f5f9; vertical-align: top; }
        .na-table tr:hover { background: #f8fafc; }
        .cap-full { color: #dc2626; font-weight: 700; }
        .cap-has { color: #16a34a; font-weight: 700; }
        .day-chip { display: inline-block; background: #e0f2fe; color: #0c4a6e; padding: 1px 6px; border-radius: 4px; font-size: 11px; margin: 1px 2px; }
        .phone-txt { color: #64748b; font-size: 12px; }
    </style>
    <div class="na">
    """

    html += f'<div class="na-count">Showing {len(rows)} of {NUM_NURSES} nurses</div>'
    html += """
    <table class="na-table">
    <tr>
        <th>Nurse</th>
        <th>Phone</th>
        <th>Week 1 Shifts</th>
        <th>Week 1 Capacity</th>
        <th>Week 1 Days</th>
        <th>Week 2 Shifts</th>
        <th>Week 2 Capacity</th>
        <th>Week 2 Days</th>
    </tr>
    """

    for r in rows:
        n = r["nurse"]
        name_short = n.name.replace("Nurse ", "")

        cap1_cls = "cap-full" if r["cap1"] <= 0 else "cap-has"
        cap2_cls = "cap-full" if r["cap2"] <= 0 else "cap-has"

        days1_html = " ".join(f'<span class="day-chip">{d.strftime("%a %d")}</span>' for d in r["days_w1"]) or "β€”"
        days2_html = " ".join(f'<span class="day-chip">{d.strftime("%a %d")}</span>' for d in r["days_w2"]) or "β€”"

        html += f"""
        <tr>
            <td><b>πŸ‘©β€βš•οΈ {name_short}</b></td>
            <td><span class="phone-txt">{n.phone}</span></td>
            <td>{r['w1']}/5</td>
            <td class="{cap1_cls}">{r['cap1']} left</td>
            <td>{days1_html}</td>
            <td>{r['w2']}/5</td>
            <td class="{cap2_cls}">{r['cap2']} left</td>
            <td>{days2_html}</td>
        </tr>"""

    html += "</table></div>"
    return html


# ═══════════════════════════════════════════════════════════════════════════════
# TAB 1 β€” AI CHAT
# ═══════════════════════════════════════════════════════════════════════════════

def handle_chat(user_message: str, history: list[dict]) -> tuple:
    """Process user message β†’ agent steps β†’ update roster + all tabs."""
    global roster

    full_response = ""
    for step in run_agent(roster, nurses, user_message):
        full_response += f"### {step.phase}\n\n{step.message}\n\n---\n\n"

    history.append({"role": "user", "content": user_message})
    history.append({"role": "assistant", "content": full_response})

    return (
        history,
        "",                                    # clear textbox
        roster_to_html(roster),                # tab 2
        build_insights_html(roster),           # tab 3
        build_nurse_table("", "All", "All"),   # tab 4
    )


def reset_demo():
    global nurses, roster
    init_state()
    return (
        [],                                    # chat
        roster_to_html(roster),
        build_insights_html(roster),
        build_nurse_table("", "All", "All"),
    )


# ═══════════════════════════════════════════════════════════════════════════════
# GRADIO APP
# ═══════════════════════════════════════════════════════════════════════════════

def create_app() -> gr.Blocks:
    with gr.Blocks(title="πŸ₯ Nurse Rostering AI Agent") as app:

        gr.Markdown(
            """
            # πŸ₯ Nurse Rostering AI Agent β€” ICU Department
            **AI-Powered Workforce Scheduling Demo** Β· 20 Nurses Β· 3 Shifts / Day Β· 2-Week Roster
            """
        )

        with gr.Tabs():
            # ── Tab 1: AI Chat ────────────────────────────────────────────
            with gr.Tab("πŸ€– AI Manager"):
                gr.Markdown(
                    "> πŸ’‘ Type **\"Fill the unfilled shifts\"** to watch the AI agent "
                    "analyze gaps, find available nurses, send outreach, and update the roster."
                )
                chatbot = gr.Chatbot(
                    type="messages",
                    value=[{
                        "role": "assistant",
                        "content": (
                            "πŸ‘‹ Hi! I'm your AI Roster Manager for the **ICU department**.\n\n"
                            "I can see there are **unfilled shifts** in the 2-week roster. "
                            "How can I help?\n\n"
                            "**Try asking:**\n"
                            '- *"Fill the unfilled shifts"*\n'
                            '- *"Show me the gaps for this week"*\n'
                            '- *"Find nurses for the night shift"*'
                        ),
                    }],
                    height=520,
                )
                with gr.Row():
                    msg_input = gr.Textbox(
                        placeholder="e.g. Fill the unfilled shifts for this week…",
                        show_label=False,
                        scale=5,
                        container=False,
                    )
                    send_btn = gr.Button("Send", variant="primary", scale=1)
                reset_btn = gr.Button("πŸ”„ Reset Demo", variant="secondary", size="sm")

            # ── Tab 2: Roster View ────────────────────────────────────────
            with gr.Tab("πŸ“‹ Roster View"):
                roster_display = gr.HTML(value=roster_to_html(roster))

            # ── Tab 3: Insights ───────────────────────────────────────────
            with gr.Tab("πŸ“Š Insights"):
                insights_display = gr.HTML(value=build_insights_html(roster))

            # ── Tab 4: Nurse Availability ─────────────────────────────────
            with gr.Tab("πŸ‘©β€βš•οΈ Nurse Availability"):
                with gr.Row():
                    name_search = gr.Textbox(
                        label="πŸ” Search by name",
                        placeholder="e.g. Priya, Mei Ling…",
                        scale=3,
                    )
                    week_dd = gr.Dropdown(
                        label="Week",
                        choices=["All", "Week 1", "Week 2"],
                        value="All",
                        scale=1,
                    )
                    avail_dd = gr.Dropdown(
                        label="Availability",
                        choices=["All", "Has Capacity"],
                        value="All",
                        scale=1,
                    )
                    filter_btn = gr.Button("Apply Filter", variant="primary", scale=1)

                nurse_display = gr.HTML(value=build_nurse_table("", "All", "All"))

        # ── Event wiring ──────────────────────────────────────────────────
        chat_outputs = [chatbot, msg_input, roster_display, insights_display, nurse_display]

        send_btn.click(
            fn=handle_chat,
            inputs=[msg_input, chatbot],
            outputs=chat_outputs,
        )
        msg_input.submit(
            fn=handle_chat,
            inputs=[msg_input, chatbot],
            outputs=chat_outputs,
        )
        reset_btn.click(
            fn=reset_demo,
            outputs=[chatbot, roster_display, insights_display, nurse_display],
        )
        filter_btn.click(
            fn=build_nurse_table,
            inputs=[name_search, week_dd, avail_dd],
            outputs=nurse_display,
        )
        name_search.submit(
            fn=build_nurse_table,
            inputs=[name_search, week_dd, avail_dd],
            outputs=nurse_display,
        )

    return app


# ── Entry point ───────────────────────────────────────────────────────────────
if __name__ == "__main__":
    app = create_app()
    app.launch(show_error=True)