Spaces:
Paused

File size: 19,718 Bytes
8eb630b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
 
8eb630b
 
0743ddc
 
8eb630b
 
 
 
0743ddc
 
 
 
 
 
8eb630b
 
579285c
8eb630b
 
 
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
 
8eb630b
 
0743ddc
 
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
579285c
 
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
0743ddc
 
8eb630b
 
 
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
0743ddc
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
 
 
 
 
 
 
 
 
 
 
 
 
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
 
8eb630b
 
579285c
 
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
 
8eb630b
579285c
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
 
8eb630b
0743ddc
 
 
 
 
 
 
 
 
 
 
 
 
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
 
8eb630b
 
579285c
 
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
0743ddc
8eb630b
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
 
0743ddc
8eb630b
 
579285c
 
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
579285c
 
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
579285c
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
579285c
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
579285c
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
 
8eb630b
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
 
 
579285c
0743ddc
8eb630b
0743ddc
8eb630b
579285c
 
8eb630b
 
579285c
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
579285c
8eb630b
 
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
 
 
 
 
 
 
 
 
 
 
8eb630b
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
 
 
579285c
0743ddc
8eb630b
 
579285c
 
8eb630b
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
 
 
 
 
 
 
 
 
 
8eb630b
0743ddc
 
 
 
 
 
 
 
 
 
8eb630b
 
0743ddc
 
 
 
 
 
 
 
 
 
8eb630b
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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
"""
YAZ Care Platform - Cell Controller
Automatic cell management and split/merge proposals

Architecture:
- Monitors cell metrics continuously
- Proposes split when SLA slips persistently
- Proposes merge when cells are underutilized
- Human-approved actions (no auto-execute for safety)

Clinical Context: Dynamic resource allocation
Standards: Lean Six Sigma, Theory of Constraints
"""

import json
from datetime import UTC, datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from uuid import UUID, uuid4

import structlog
from sqlalchemy import and_, func, select
from sqlalchemy.ext.asyncio import AsyncSession

from .models import (
    AlertSeverity,
    Cell,
    CellLoad,
    CellSplitProposal,
    CellStatus,
    CellType,
    SLAMetric,
)

logger = structlog.get_logger(__name__)


class CellController:
    """
    Automatic cell management controller

    Monitors metrics and proposes:
    - Cell splits when overloaded
    - Cell merges when underutilized
    - Staff/resource rebalancing
    """

    # Thresholds for actions
    SPLIT_UTILIZATION_THRESHOLD = 95  # % utilization to consider split
    SPLIT_BREACH_THRESHOLD = 3  # Number of breaches to trigger
    MERGE_UTILIZATION_THRESHOLD = 30  # % below which to consider merge
    MERGE_DURATION_HOURS = 24  # Hours of low util before proposing merge

    def __init__(self, session: AsyncSession):
        self.session = session

    async def analyze_all_cells(self, tenant_id: UUID) -> list[CellSplitProposal]:
        """
        Analyze all cells and generate proposals

        Returns list of new proposals generated
        """
        proposals = []

        # Get all active cells
        query = select(Cell).where(
            Cell.tenant_id == tenant_id,  # type: ignore[arg-type]
            Cell.is_active == True,  # type: ignore[arg-type]
        )
        result = await self.session.execute(query)
        cells = result.scalars().all()

        for cell in cells:
            # Check for split
            split_proposal = await self._check_split_needed(cell)
            if split_proposal:
                proposals.append(split_proposal)

            # Check for merge
            merge_proposal = await self._check_merge_needed(cell)
            if merge_proposal:
                proposals.append(merge_proposal)

        return proposals

    async def _check_split_needed(self, cell: Cell) -> CellSplitProposal | None:
        """Check if cell should be split"""
        if not cell.should_split():
            return None

        # Check if we already have a pending proposal
        existing = await self._get_pending_proposal(cell.id, "split")
        if existing:
            return None

        # Create proposal
        proposal = CellSplitProposal(
            tenant_id=cell.tenant_id,
            source_cell_id=cell.id,
            action="split",
            reason=self._generate_split_reason(cell),
            metrics_snapshot=json.dumps(
                {
                    "utilization": cell.utilization_percent,
                    "breach_count": cell.current_breach_count,
                    "load": cell.current_load,
                    "capacity": cell.capacity,
                    "latency_p95": cell.current_latency_p95,
                }
            ),
            proposed_changes=json.dumps(
                {
                    "action": "split",
                    "new_cells": [
                        {
                            "name": f"{cell.name} - A",
                            "code": f"{cell.code}_A",
                            "capacity": cell.capacity // 2,
                        },
                        {
                            "name": f"{cell.name} - B",
                            "code": f"{cell.code}_B",
                            "capacity": cell.capacity - (cell.capacity // 2),
                        },
                    ],
                    "staffing_recommendation": "Split team coverage between new cells",
                }
            ),
            expected_sla_improvement=20.0,  # Estimated 20% improvement
            expected_capacity_change=0,  # Same total capacity, split
        )

        self.session.add(proposal)
        await self.session.flush()

        logger.info(
            f"cell_split_proposed: cell_id={cell.id}, proposal_id={proposal.id}, reason={proposal.reason}"
        )

        return proposal

    async def _check_merge_needed(self, cell: Cell) -> CellSplitProposal | None:
        """Check if cell should be merged with sibling"""
        if cell.utilization_percent > self.MERGE_UTILIZATION_THRESHOLD:
            return None

        if not cell.parent_cell_id:
            return None  # Can't merge top-level cells

        # Check if underutilized for sustained period
        sustained = await self._check_sustained_low_utilization(cell)
        if not sustained:
            return None

        # Find sibling cell to merge with
        sibling = await self._find_merge_candidate(cell)
        if not sibling:
            return None

        # Check existing proposal
        existing = await self._get_pending_proposal(cell.id, "merge")
        if existing:
            return None

        # Create proposal
        proposal = CellSplitProposal(
            tenant_id=cell.tenant_id,
            source_cell_id=cell.id,
            action="merge",
            reason=f"Cell '{cell.name}' has been underutilized ({cell.utilization_percent:.1f}%) for 24+ hours",
            metrics_snapshot=json.dumps(
                {
                    "utilization": cell.utilization_percent,
                    "sibling_utilization": sibling.utilization_percent,
                }
            ),
            proposed_changes=json.dumps(
                {
                    "action": "merge",
                    "source_cell": str(cell.id),
                    "target_cell": str(sibling.id),
                    "merged_capacity": cell.capacity + sibling.capacity,
                }
            ),
            expected_sla_improvement=0.0,
            expected_capacity_change=-(cell.capacity),  # Reduce by merged cell capacity
        )

        self.session.add(proposal)
        await self.session.flush()

        return proposal

    async def _get_pending_proposal(self, cell_id: UUID, action: str) -> CellSplitProposal | None:
        """Check for existing pending proposal"""
        query = select(CellSplitProposal).where(
            CellSplitProposal.source_cell_id == cell_id,  # type: ignore[arg-type]
            CellSplitProposal.action == action,  # type: ignore[arg-type]
            CellSplitProposal.status == "pending",  # type: ignore[arg-type]
        )
        result = await self.session.execute(query)
        return result.scalar_one_or_none()

    async def _check_sustained_low_utilization(self, cell: Cell) -> bool:
        """Check if cell has been low utilization for sustained period"""
        cutoff = datetime.now(UTC) - timedelta(hours=self.MERGE_DURATION_HOURS)

        query = select(func.avg(CellLoad.active_cases)).where(
            CellLoad.cell_id == cell.id,  # type: ignore[arg-type]
            CellLoad.recorded_at >= cutoff,  # type: ignore[arg-type]
        )
        result = await self.session.execute(query)
        avg_load = result.scalar()

        if avg_load is None:
            return False

        avg_utilization = (avg_load / cell.capacity) * 100 if cell.capacity > 0 else 100
        return avg_utilization < self.MERGE_UTILIZATION_THRESHOLD

    async def _find_merge_candidate(self, cell: Cell) -> Cell | None:
        """Find sibling cell that could be merged"""
        query = (
            select(Cell)
            .where(
                Cell.tenant_id == cell.tenant_id,  # type: ignore[arg-type]
                Cell.parent_cell_id == cell.parent_cell_id,  # type: ignore[arg-type]
                Cell.id != cell.id,  # type: ignore[arg-type]
                Cell.is_active == True,  # type: ignore[arg-type]
                Cell.cell_type == cell.cell_type,  # type: ignore[arg-type]
            )
            .order_by(Cell.current_load)
            .limit(1)
        )  # type: ignore[arg-type]

        result = await self.session.execute(query)
        return result.scalar_one_or_none()

    def _generate_split_reason(self, cell: Cell) -> str:
        """Generate human-readable split reason"""
        reasons = []

        if cell.utilization_percent >= 95:
            reasons.append(f"utilization at {cell.utilization_percent:.1f}%")
        if cell.current_breach_count >= 3:
            reasons.append(f"{cell.current_breach_count} active SLA breaches")
        if cell.current_latency_p95 > 0:
            reasons.append(f"P95 latency {cell.current_latency_p95:.1f}s")

        return f"Cell '{cell.name}' is overloaded: " + ", ".join(reasons)

    # ========================================================================
    # PROPOSAL ACTIONS
    # ========================================================================

    async def approve_proposal(
        self,
        proposal_id: UUID,
        tenant_id: UUID,
        user_id: UUID,
        notes: str | None = None,
    ) -> CellSplitProposal | None:
        """Approve a proposal (human approval required)"""
        query = select(CellSplitProposal).where(
            CellSplitProposal.id == proposal_id,  # type: ignore[arg-type]
            CellSplitProposal.tenant_id == tenant_id,  # type: ignore[arg-type]
            CellSplitProposal.status == "pending",  # type: ignore[arg-type]
        )
        result = await self.session.execute(query)
        proposal = result.scalar_one_or_none()

        if not proposal:
            return None

        proposal.status = "approved"
        proposal.reviewed_by = user_id
        proposal.reviewed_at = datetime.now(UTC)
        proposal.review_notes = notes

        await self.session.flush()

        logger.info(
            f"proposal_approved: proposal_id={proposal_id}, action={proposal.action}, reviewed_by={user_id}"
        )

        return proposal

    async def reject_proposal(
        self,
        proposal_id: UUID,
        tenant_id: UUID,
        user_id: UUID,
        reason: str,
    ) -> CellSplitProposal | None:
        """Reject a proposal"""
        query = select(CellSplitProposal).where(
            CellSplitProposal.id == proposal_id,  # type: ignore[arg-type]
            CellSplitProposal.tenant_id == tenant_id,  # type: ignore[arg-type]
            CellSplitProposal.status == "pending",  # type: ignore[arg-type]
        )
        result = await self.session.execute(query)
        proposal = result.scalar_one_or_none()

        if not proposal:
            return None

        proposal.status = "rejected"
        proposal.reviewed_by = user_id
        proposal.reviewed_at = datetime.now(UTC)
        proposal.review_notes = reason

        await self.session.flush()

        return proposal

    async def implement_proposal(
        self,
        proposal_id: UUID,
        tenant_id: UUID,
        user_id: UUID,
    ) -> tuple[bool, str, list[Cell]]:
        """
        Implement an approved proposal

        Returns: (success, message, new_cells)
        """
        query = select(CellSplitProposal).where(
            CellSplitProposal.id == proposal_id,  # type: ignore[arg-type]
            CellSplitProposal.tenant_id == tenant_id,  # type: ignore[arg-type]
            CellSplitProposal.status == "approved",  # type: ignore[arg-type]
        )
        result = await self.session.execute(query)
        proposal = result.scalar_one_or_none()

        if not proposal:
            return False, "Proposal not found or not approved", []

        changes = json.loads(proposal.proposed_changes)  # type: ignore[arg-type, assignment]

        if proposal.action == "split":
            new_cells = await self._implement_split(proposal, changes, user_id)
            proposal.status = "implemented"
            proposal.implemented_at = datetime.now(UTC)
            await self.session.flush()
            return True, f"Cell split into {len(new_cells)} new cells", new_cells

        elif proposal.action == "merge":
            await self._implement_merge(proposal, changes, user_id)
            proposal.status = "implemented"
            proposal.implemented_at = datetime.now(UTC)
            await self.session.flush()
            return True, "Cells merged successfully", []

        return False, f"Unknown action: {proposal.action}", []

    async def _implement_split(
        self,
        proposal: CellSplitProposal,
        changes: dict,
        user_id: UUID,
    ) -> list[Cell]:
        """Implement a cell split"""
        # Get source cell
        query = select(Cell).where(Cell.id == proposal.source_cell_id)  # type: ignore[arg-type]
        result = await self.session.execute(query)
        source_cell = result.scalar_one()

        # Deactivate source
        source_cell.is_active = False
        source_cell.status = CellStatus.INACTIVE

        # Create new cells
        new_cells = []
        for new_cell_spec in changes.get("new_cells", []):
            new_cell = Cell(
                tenant_id=proposal.tenant_id,
                name=new_cell_spec["name"],
                code=new_cell_spec["code"],
                cell_type=source_cell.cell_type,
                parent_cell_id=source_cell.parent_cell_id,
                capacity=new_cell_spec["capacity"],
                default_sla_minutes=source_cell.default_sla_minutes,
                status=CellStatus.ACTIVE,
            )
            self.session.add(new_cell)
            new_cells.append(new_cell)

        await self.session.flush()

        logger.info(
            f"cell_split_implemented: source_cell_id={source_cell.id}, new_cell_count={len(new_cells)}"
        )

        return new_cells

    async def _implement_merge(
        self,
        proposal: CellSplitProposal,
        changes: dict,
        user_id: UUID,
    ) -> None:
        """Implement a cell merge"""
        source_id = UUID(changes["source_cell"])
        target_id = UUID(changes["target_cell"])

        # Get cells
        query = select(Cell).where(Cell.id.in_([source_id, target_id]))  # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
        result = await self.session.execute(query)
        cells = {c.id: c for c in result.scalars().all()}

        source = cells.get(source_id)
        target = cells.get(target_id)

        if not source or not target:
            return

        # Merge capacity into target
        target.capacity += source.capacity
        target.updated_at = datetime.now(UTC)

        # Deactivate source
        source.is_active = False
        source.status = CellStatus.INACTIVE

        await self.session.flush()

        logger.info(
            f"cell_merge_implemented: source_cell_id={source_id}, target_cell_id={target_id}"
        )

    # ========================================================================
    # INSIGHTS & PREDICTIONS
    # ========================================================================

    async def get_predictions(
        self,
        tenant_id: UUID,
        cell_id: UUID | None = None,
        hours_ahead: int = 24,
    ) -> list[dict[str, Any]]:
        """
        Generate predictions for cell load

        Simple rule-based predictions (can be upgraded to ML later):
        - Time-of-day patterns
        - Day-of-week patterns
        - Historical averages
        """
        predictions = []  # type: ignore[name-defined, index, return-value, var-annotated]

        # Get historical data
        cutoff = datetime.now(UTC) - timedelta(days=14)
        query = select(CellLoad).where(
            CellLoad.tenant_id == tenant_id,  # type: ignore[arg-type]
            CellLoad.recorded_at >= cutoff,  # type: ignore[arg-type]
        )
        if cell_id:
            query = query.where(CellLoad.cell_id == cell_id)  # type: ignore[arg-type]

        result = await self.session.execute(query)
        history = result.scalars().all()

        if not history:
            return predictions

        # Group by hour of day
        hourly_loads = {}  # type: ignore[name-defined, index, return-value, var-annotated]
        for load in history:
            hour = load.recorded_at.hour
            if hour not in hourly_loads:
                hourly_loads[hour] = []
            hourly_loads[hour].append(load.active_cases)

        # Generate predictions
        now = datetime.now(UTC)
        for h in range(hours_ahead):
            future_time = now + timedelta(hours=h)
            hour = future_time.hour

            if hour in hourly_loads:
                avg_load = sum(hourly_loads[hour]) / len(hourly_loads[hour])
                max_load = max(hourly_loads[hour])
            else:
                avg_load = 0
                max_load = 0

            predictions.append(
                {
                    "time": future_time.isoformat(),
                    "hour": hour,
                    "predicted_load": round(avg_load, 1),
                    "predicted_max": max_load,
                    "confidence": "medium" if len(hourly_loads.get(hour, [])) >= 7 else "low",
                }
            )

        return predictions

    async def get_recommendations(
        self,
        tenant_id: UUID,
        cell_id: UUID,
    ) -> list[dict[str, Any]]:
        """
        Generate actionable recommendations

        Rule-based recommendations:
        - Staff adjustments
        - Pre-positioning supplies
        - Proactive notifications
        """
        recommendations = []  # type: ignore[name-defined, index, return-value, var-annotated]

        # Get cell
        query = select(Cell).where(
            Cell.id == cell_id,  # type: ignore[arg-type]
            Cell.tenant_id == tenant_id,  # type: ignore[arg-type]
        )
        result = await self.session.execute(query)
        cell = result.scalar_one_or_none()

        if not cell:
            return recommendations

        # Get predictions
        predictions = await self.get_predictions(tenant_id, cell_id, 8)

        # Analyze and recommend
        for pred in predictions:
            if pred["predicted_load"] > cell.capacity * 0.9:
                recommendations.append(
                    {
                        "type": "staffing",
                        "time": pred["time"],
                        "severity": "high",
                        "message": f"Predicted high load at {pred['hour']}:00. Consider adding staff.",
                        "action": "notify_supervisor",
                    }
                )

            if pred["predicted_max"] > cell.capacity:
                recommendations.append(
                    {
                        "type": "capacity",
                        "time": pred["time"],
                        "severity": "critical",
                        "message": f"Predicted over-capacity at {pred['hour']}:00. Prepare overflow plan.",
                        "action": "activate_overflow",
                    }
                )

        # Current state recommendations
        if cell.current_breach_count > 0:
            recommendations.append(
                {
                    "type": "sla",
                    "time": datetime.now(UTC).isoformat(),
                    "severity": "high",
                    "message": f"{cell.current_breach_count} active SLA breaches. Escalate or add resources.",
                    "action": "escalate",
                }
            )

        return recommendations