File size: 10,318 Bytes
8ba58ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
"""
agent.py β€” Simulated AI Rostering Agent

Implements the 5-step agent flow:
  1. Analyze   β†’ identify unfilled shifts
  2. Filter    β†’ find eligible nurses with capacity
  3. Outreach  β†’ simulate SMS/WhatsApp messages (mock Twilio)
  4. Resolve   β†’ simulate nurse responses
  5. Update    β†’ fill the roster and report back

In production, replace the clearly-marked simulation blocks with:
  β€’ LLM API calls (OpenAI / Anthropic / Gemini) for natural-language reasoning
  β€’ Twilio / WhatsApp Business API for real outreach
  β€’ Database writes for persistence
"""

from __future__ import annotations

import random
import time
from dataclasses import dataclass
from datetime import date
from typing import Generator

from mock_data import (
    Nurse,
    ShiftSlot,
    eligible_nurses_for_slot,
    get_unfilled_slots,
    week_number,
)


# ── Agent response streaming ─────────────────────────────────────────────────

@dataclass
class AgentStep:
    """One chunk of the agent's thought process, streamed to the UI."""
    phase: str        # e.g. "πŸ” Analyze", "πŸ“² Outreach"
    message: str      # markdown-formatted content


def run_agent(
    roster: list[ShiftSlot],
    nurses: list[Nurse],
    user_prompt: str,
) -> Generator[AgentStep, None, list[ShiftSlot]]:
    """Generator that yields AgentSteps and mutates the roster in-place.

    The caller iterates over yielded steps to build the chat log,
    then collects the final roster state.
    """

    # ──────────────────────────────────────────────────────────────────────
    # STEP 1 β€” ANALYZE
    # In production: send the roster + prompt to an LLM to identify intent
    # and extract which gaps to fill.
    # ──────────────────────────────────────────────────────────────────────
    unfilled = get_unfilled_slots(roster)

    if not unfilled:
        yield AgentStep(
            phase="βœ… Complete",
            message="All shifts are fully staffed β€” no action needed.",
        )
        return roster

    yield AgentStep(
        phase="πŸ” Step 1 β€” Analyze",
        message=_format_gap_analysis(unfilled, roster),
    )

    # ──────────────────────────────────────────────────────────────────────
    # STEP 2 β€” FILTER ELIGIBLE NURSES
    # In production: query the HR database / BQ for nurse availability,
    # leave balance, skills match, etc.
    # ──────────────────────────────────────────────────────────────────────
    fill_plan: list[tuple[ShiftSlot, list[Nurse]]] = []
    for slot in unfilled:
        eligible = eligible_nurses_for_slot(slot, nurses, roster)
        fill_plan.append((slot, eligible))

    yield AgentStep(
        phase="🎯 Step 2 β€” Filter Eligible Nurses",
        message=_format_eligibility(fill_plan, roster),
    )

    # ──────────────────────────────────────────────────────────────────────
    # STEP 3 β€” OUTREACH (MOCKED)
    # In production: call Twilio REST API or WhatsApp Business API here.
    # Example:
    #   from twilio.rest import Client
    #   client = Client(ACCOUNT_SID, AUTH_TOKEN)
    #   client.messages.create(body=msg, from_=TWILIO_NUM, to=nurse.phone)
    # ──────────────────────────────────────────────────────────────────────
    outreach_log = _simulate_outreach(fill_plan)

    yield AgentStep(
        phase="πŸ“² Step 3 β€” Outreach (Simulated SMS/WhatsApp)",
        message=outreach_log,
    )

    # ──────────────────────────────────────────────────────────────────────
    # STEP 4 β€” RESOLVE RESPONSES
    # In production: poll for incoming webhook responses from Twilio,
    # or use an async callback handler.
    # ──────────────────────────────────────────────────────────────────────
    assignments, resolution_log = _simulate_responses(fill_plan)

    yield AgentStep(
        phase="πŸ“© Step 4 β€” Nurse Responses",
        message=resolution_log,
    )

    # ──────────────────────────────────────────────────────────────────────
    # STEP 5 β€” UPDATE ROSTER
    # In production: write to BigQuery / Postgres, notify the manager,
    # update the calendar system.
    # ──────────────────────────────────────────────────────────────────────
    for slot, nurse in assignments:
        if nurse not in slot.assigned:
            slot.assigned.append(nurse)

    remaining = get_unfilled_slots(roster)

    yield AgentStep(
        phase="βœ… Step 5 β€” Roster Updated",
        message=_format_completion(assignments, remaining),
    )

    return roster


# ── Formatting helpers ────────────────────────────────────────────────────────

def _format_gap_analysis(unfilled: list[ShiftSlot], roster: list[ShiftSlot]) -> str:
    lines = [f"Found **{len(unfilled)} unfilled shift(s)** across the 2-week roster:\n"]
    lines.append("| # | Date | Day | Shift | Hours | Vacancies |")
    lines.append("|---|------|-----|-------|-------|-----------|")
    for i, s in enumerate(unfilled, 1):
        day_name = s.day.strftime("%A")
        lines.append(
            f"| {i} | {s.day.strftime('%d %b')} | {day_name} "
            f"| {s.shift_name} | {s.shift_hours} | {s.vacancies} |"
        )
    return "\n".join(lines)


def _format_eligibility(
    fill_plan: list[tuple[ShiftSlot, list[Nurse]]],
    roster: list[ShiftSlot],
) -> str:
    lines = ["Searching the 20-nurse pool for availability…\n"]
    for slot, eligible in fill_plan:
        day_name = slot.day.strftime("%A")
        lines.append(
            f"**{slot.day.strftime('%d %b')} ({day_name}) β€” {slot.shift_name}** "
            f"β†’ {len(eligible)} eligible nurses"
        )
        top3 = eligible[:3]
        for n in top3:
            week = week_number(slot, roster)
            from mock_data import nurse_shifts_in_week
            current = nurse_shifts_in_week(n, roster, week)
            lines.append(f"  - {n.name} β€” {current}/5 shifts this week")
        if len(eligible) > 3:
            lines.append(f"  - … and {len(eligible) - 3} more\n")
        else:
            lines.append("")
    return "\n".join(lines)


def _simulate_outreach(fill_plan: list[tuple[ShiftSlot, list[Nurse]]]) -> str:
    """Mock SMS/WhatsApp outreach to top-3 eligible nurses per gap."""
    lines = ["Sending shift-cover requests…\n"]
    lines.append("```")
    for slot, eligible in fill_plan:
        top3 = eligible[:3]
        day_str = slot.day.strftime("%d %b (%A)")
        for n in top3:
            lines.append(
                f"πŸ“± β†’ {n.name} ({n.phone})\n"
                f'   "Hi {n.name.replace("Nurse ", "")}, '
                f"can you cover {slot.shift_name} shift on {day_str} "
                f'({slot.shift_hours})? Reply YES to confirm."'
            )
        lines.append("")
    lines.append("```")
    lines.append(f"\nβœ… **{sum(min(3, len(e)) for _, e in fill_plan)} messages sent** β€” awaiting responses…")
    return "\n".join(lines)


def _simulate_responses(
    fill_plan: list[tuple[ShiftSlot, list[Nurse]]],
) -> tuple[list[tuple[ShiftSlot, Nurse]], str]:
    """Simulate nurse replies β€” first eligible nurse always says YES."""
    rng = random.Random(99)
    assignments: list[tuple[ShiftSlot, Nurse]] = []
    lines = ["Responses received:\n"]
    lines.append("```")

    for slot, eligible in fill_plan:
        filled = False
        top3 = eligible[:3]
        for i, n in enumerate(top3):
            # Simulate: first nurse accepts, others may decline
            if not filled and (i == 0 or rng.random() > 0.5):
                lines.append(f"βœ… {n.name}: \"YES β€” I'll take it!\"")
                assignments.append((slot, n))
                filled = True
            else:
                lines.append(f"❌ {n.name}: \"Sorry, can't make it.\"")

        if not filled:
            lines.append(f"⚠️  No confirmation yet for {slot.day.strftime('%d %b')} {slot.shift_name}")
        lines.append("")

    lines.append("```")
    return assignments, "\n".join(lines)


def _format_completion(
    assignments: list[tuple[ShiftSlot, Nurse]],
    remaining: list[ShiftSlot],
) -> str:
    lines = [f"**{len(assignments)} shift(s) filled successfully!**\n"]
    lines.append("| Date | Shift | Assigned To |")
    lines.append("|------|-------|-------------|")
    for slot, nurse in assignments:
        lines.append(
            f"| {slot.day.strftime('%d %b (%a)')} | {slot.shift_name} | {nurse.name} |"
        )
    lines.append("")
    if remaining:
        lines.append(
            f"⚠️ **{len(remaining)} shift(s) still unfilled** β€” "
            "consider extending outreach to part-time or agency staff."
        )
    else:
        lines.append("πŸŽ‰ **All shifts are now fully covered!** Roster is complete.")
    return "\n".join(lines)