File size: 13,629 Bytes
fcf8749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Unit tests for Explainability Agent v2 (Phase 4.3).
Tests classification logic and template generation.
"""

import pytest
from app.services.explainability import ExplainabilityAgent
from app.schemas.explainability import DriverExplanationInput, DriverExplanationOutput


class TestCategoryClassification:
    """Tests for _classify_category logic."""
    
    def setup_method(self):
        """Set up test fixtures."""
        self.agent = ExplainabilityAgent()
    
    def _base_input(self, **overrides) -> DriverExplanationInput:
        """Create base input with optional overrides."""
        defaults = {
            "driver_id": "driver-1",
            "driver_name": "Test Driver",
            "num_drivers": 5,
            "today_effort": 50.0,
            "today_rank": 3,
            "route_id": "route-1",
            "route_summary": {
                "num_packages": 20,
                "total_weight_kg": 50.0,
                "num_stops": 10,
                "difficulty_score": 2.5,
                "estimated_time_minutes": 180,
            },
            "effort_breakdown": {
                "physical_effort": 15.0,
                "route_complexity": 10.0,
                "time_pressure": 5.0,
            },
            "global_avg_effort": 50.0,
            "global_std_effort": 10.0,
            "global_gini_index": 0.15,
            "global_max_gap": 20.0,
            "history_efforts_last_7_days": [45.0, 50.0, 55.0],
            "history_hard_days_last_7": 1,
            "is_recovery_day": False,
            "had_manual_override": False,
            "liaison_decision": None,
            "swap_applied": False,
        }
        defaults.update(overrides)
        return DriverExplanationInput(**defaults)
    
    def test_near_avg_category(self):
        """Effort close to average should classify as NEAR_AVG."""
        data = self._base_input(today_effort=52.0, global_avg_effort=50.0)
        category = self.agent._classify_category(data)
        assert category == "NEAR_AVG"
    
    def test_heavy_category(self):
        """Above-average effort without negotiation should classify as HEAVY."""
        data = self._base_input(today_effort=70.0, global_avg_effort=50.0)
        category = self.agent._classify_category(data)
        assert category == "HEAVY"
    
    def test_heavy_with_swap_category(self):
        """Above-average with swap applied should classify as HEAVY_WITH_SWAP."""
        data = self._base_input(
            today_effort=70.0,
            global_avg_effort=50.0,
            swap_applied=True,
        )
        category = self.agent._classify_category(data)
        assert category == "HEAVY_WITH_SWAP"
    
    def test_heavy_no_swap_category(self):
        """Above-average with COUNTER but no swap should classify as HEAVY_NO_SWAP."""
        data = self._base_input(
            today_effort=70.0,
            global_avg_effort=50.0,
            liaison_decision="COUNTER",
            swap_applied=False,
        )
        category = self.agent._classify_category(data)
        assert category == "HEAVY_NO_SWAP"
    
    def test_recovery_category(self):
        """Explicit recovery day should classify as RECOVERY."""
        data = self._base_input(
            today_effort=35.0,
            global_avg_effort=50.0,
            is_recovery_day=True,
        )
        category = self.agent._classify_category(data)
        assert category == "RECOVERY"
    
    def test_light_recovery_category(self):
        """Below average with hard day streak should classify as LIGHT_RECOVERY."""
        data = self._base_input(
            today_effort=35.0,
            global_avg_effort=50.0,
            history_hard_days_last_7=3,
        )
        category = self.agent._classify_category(data)
        assert category == "LIGHT_RECOVERY"
    
    def test_light_category(self):
        """Below average without hard streak should classify as LIGHT."""
        data = self._base_input(
            today_effort=35.0,
            global_avg_effort=50.0,
            history_hard_days_last_7=0,
        )
        category = self.agent._classify_category(data)
        assert category == "LIGHT"


class TestDriverTextGeneration:
    """Tests for _build_driver_text templates."""
    
    def setup_method(self):
        """Set up test fixtures."""
        self.agent = ExplainabilityAgent()
    
    def _base_input(self, **overrides) -> DriverExplanationInput:
        """Create base input with optional overrides."""
        defaults = {
            "driver_id": "driver-1",
            "driver_name": "Test Driver",
            "num_drivers": 5,
            "today_effort": 50.0,
            "today_rank": 3,
            "route_id": "route-1",
            "route_summary": {
                "num_packages": 20,
                "total_weight_kg": 50.0,
                "num_stops": 10,
                "difficulty_score": 2.5,
                "estimated_time_minutes": 180,
            },
            "effort_breakdown": {},
            "global_avg_effort": 50.0,
            "global_std_effort": 10.0,
            "global_gini_index": 0.15,
            "global_max_gap": 20.0,
            "history_efforts_last_7_days": [],
            "history_hard_days_last_7": 0,
            "is_recovery_day": False,
            "had_manual_override": False,
            "liaison_decision": None,
            "swap_applied": False,
        }
        defaults.update(overrides)
        return DriverExplanationInput(**defaults)
    
    def test_near_avg_contains_expected_phrases(self):
        """NEAR_AVG text should mention 'moderate' and 'balanced'."""
        data = self._base_input()
        text = self.agent._build_driver_text(data, "NEAR_AVG")
        
        assert "moderate" in text.lower()
        assert "balanced" in text.lower()
        assert "20 packages" in text
        assert "10 stops" in text
    
    def test_heavy_mentions_heavier(self):
        """HEAVY category text should mention 'heavier'."""
        data = self._base_input(today_effort=70.0)
        text = self.agent._build_driver_text(data, "HEAVY")
        
        assert "heavier" in text.lower()
    
    def test_recovery_mentions_lighter(self):
        """RECOVERY text should mention 'intentionally lighter' and 'recover'."""
        data = self._base_input(is_recovery_day=True)
        text = self.agent._build_driver_text(data, "RECOVERY")
        
        assert "lighter" in text.lower()
        assert "recover" in text.lower()
    
    def test_includes_packages_and_stops(self):
        """All templates should include package and stop counts."""
        data = self._base_input()
        
        for category in ["NEAR_AVG", "HEAVY", "LIGHT", "RECOVERY"]:
            text = self.agent._build_driver_text(data, category)
            assert "20 packages" in text
            assert "10 stops" in text


class TestAdminTextGeneration:
    """Tests for _build_admin_text templates."""
    
    def setup_method(self):
        """Set up test fixtures."""
        self.agent = ExplainabilityAgent()
    
    def _base_input(self, **overrides) -> DriverExplanationInput:
        """Create base input with optional overrides."""
        defaults = {
            "driver_id": "driver-1",
            "driver_name": "John Doe",
            "num_drivers": 5,
            "today_effort": 65.0,
            "today_rank": 2,
            "route_id": "route-1",
            "route_summary": {
                "num_packages": 25,
                "total_weight_kg": 75.0,
                "num_stops": 12,
                "difficulty_score": 3.0,
                "estimated_time_minutes": 240,
            },
            "effort_breakdown": {
                "physical_effort": 25.0,
                "route_complexity": 20.0,
                "time_pressure": 10.0,
            },
            "global_avg_effort": 50.0,
            "global_std_effort": 12.0,
            "global_gini_index": 0.12,
            "global_max_gap": 25.0,
            "history_efforts_last_7_days": [55.0, 60.0],
            "history_hard_days_last_7": 2,
            "is_recovery_day": False,
            "had_manual_override": False,
            "liaison_decision": None,
            "swap_applied": False,
        }
        defaults.update(overrides)
        return DriverExplanationInput(**defaults)
    
    def test_admin_text_includes_driver_name(self):
        """Admin text should include driver name."""
        data = self._base_input()
        text = self.agent._build_admin_text(data, "NEAR_AVG")
        assert "John Doe" in text
    
    def test_admin_text_includes_effort_metrics(self):
        """Admin text should include effort score and comparison to average."""
        data = self._base_input()
        text = self.agent._build_admin_text(data, "NEAR_AVG")
        
        assert "65" in text  # effort score
        assert "50" in text  # average
    
    def test_admin_text_includes_gini(self):
        """Admin text should include Gini index."""
        data = self._base_input()
        text = self.agent._build_admin_text(data, "NEAR_AVG")
        
        assert "Gini" in text
        assert "0.12" in text
    
    def test_admin_text_includes_rank(self):
        """Admin text should include rank."""
        data = self._base_input()
        text = self.agent._build_admin_text(data, "NEAR_AVG")
        
        assert "2/5" in text  # rank/total
    
    def test_heavy_with_swap_mentions_swap(self):
        """HEAVY_WITH_SWAP should mention swap in admin text."""
        data = self._base_input(swap_applied=True)
        text = self.agent._build_admin_text(data, "HEAVY_WITH_SWAP")
        
        assert "swap" in text.lower()
    
    def test_recovery_mentions_hard_days(self):
        """RECOVERY text should mention hard days count."""
        data = self._base_input(is_recovery_day=True, history_hard_days_last_7=4)
        text = self.agent._build_admin_text(data, "RECOVERY")
        
        assert "4" in text
        assert "hard day" in text.lower() or "recovery" in text.lower()
    
    def test_manual_override_note_included(self):
        """Manual override should be noted in admin text."""
        data = self._base_input(had_manual_override=True)
        text = self.agent._build_admin_text(data, "NEAR_AVG")
        
        assert "override" in text.lower()


class TestBuildExplanationForDriver:
    """Tests for the main build_explanation_for_driver method."""
    
    def setup_method(self):
        """Set up test fixtures."""
        self.agent = ExplainabilityAgent()
    
    def test_returns_correct_output_type(self):
        """Should return DriverExplanationOutput."""
        data = DriverExplanationInput(
            driver_id="d1",
            driver_name="Driver One",
            num_drivers=3,
            today_effort=50.0,
            today_rank=2,
            route_id="r1",
            route_summary={"num_packages": 15, "total_weight_kg": 40.0, "num_stops": 8, "difficulty_score": 2.0, "estimated_time_minutes": 120},
            global_avg_effort=50.0,
            global_std_effort=10.0,
            global_gini_index=0.1,
            global_max_gap=15.0,
        )
        
        result = self.agent.build_explanation_for_driver(data)
        
        assert isinstance(result, DriverExplanationOutput)
        assert isinstance(result.driver_explanation, str)
        assert isinstance(result.admin_explanation, str)
        assert isinstance(result.category, str)
    
    def test_driver_and_admin_texts_are_different(self):
        """Driver and admin explanations should have different detail levels."""
        data = DriverExplanationInput(
            driver_id="d1",
            driver_name="Driver One",
            num_drivers=3,
            today_effort=50.0,
            today_rank=2,
            route_id="r1",
            route_summary={"num_packages": 15, "total_weight_kg": 40.0, "num_stops": 8, "difficulty_score": 2.0, "estimated_time_minutes": 120},
            global_avg_effort=50.0,
            global_std_effort=10.0,
            global_gini_index=0.1,
            global_max_gap=15.0,
        )
        
        result = self.agent.build_explanation_for_driver(data)
        
        # Admin text should be longer and contain more metrics
        assert len(result.admin_explanation) > len(result.driver_explanation)
        assert "Gini" in result.admin_explanation
        assert "Gini" not in result.driver_explanation


class TestSnapshotGeneration:
    """Tests for DecisionLog snapshot helpers."""
    
    def setup_method(self):
        """Set up test fixtures."""
        self.agent = ExplainabilityAgent()
    
    def test_input_snapshot(self):
        """Input snapshot should include key metrics."""
        snapshot = self.agent.get_input_snapshot(
            num_drivers=5,
            avg_effort=55.0,
            std_effort=12.0,
            gini_index=0.15,
            category_counts={"NEAR_AVG": 3, "HEAVY": 2},
        )
        
        assert snapshot["num_drivers"] == 5
        assert snapshot["avg_effort"] == 55.0
        assert snapshot["gini_index"] == 0.15
    
    def test_output_snapshot(self):
        """Output snapshot should include totals and category counts."""
        category_counts = {"NEAR_AVG": 3, "HEAVY": 2}
        snapshot = self.agent.get_output_snapshot(
            total_explanations=5,
            category_counts=category_counts,
        )
        
        assert snapshot["total_explanations"] == 5
        assert snapshot["category_counts"]["NEAR_AVG"] == 3
        assert snapshot["category_counts"]["HEAVY"] == 2