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
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
"""
ai-service/tests/test_cheat_controller.py
──────────────────────────────────────────
Unit tests cho ExamCheatController – logic xΓ‘c nhαΊ­n chΓ©o multimodal.

Tests cover:
  1. calculate_mar – Inner Lips indices (96-103)
  2. evaluate_mouth_movement – Variance-based detection
  3. process_payload – Cross-check decision matrix
  4. Session isolation – Multi-user state management
  5. Debounce – 1.5s threshold for Level 2 warnings
"""

from __future__ import annotations

import time
from collections import deque
from unittest.mock import MagicMock, patch

import numpy as np
import pytest

from modules.face.exam_face_detector import (
    ExamFaceDetector,
    MultimodalResult,
)
from modules.face.exam_cheat_controller import (
    ExamCheatController,
    SessionState,
    CheatingVerdict,
    LEVEL_NORMAL,
    LEVEL_MILD_WARNING,
    LEVEL_WARNING_L1,
    LEVEL_WARNING_L2,
)


# ──────────────────────────────────────────────────────────────────────────────
# Helpers
# ──────────────────────────────────────────────────────────────────────────────
def _make_landmarks_106(
    inner_lip_gap: float = 0.0,
    horizontal_width: float = 60.0,
) -> np.ndarray:
    """
    TαΊ‘o mαΊ£ng 106 landmarks giαΊ£ vα»›i khe miệng trong (inner lip gap) tΓΉy chỉnh.

    inner_lip_gap: KhoαΊ£ng cΓ‘ch dọc giα»―a mΓ΄i trΓͺn vΓ  mΓ΄i dΖ°α»›i (inner lips).
        0 = miệng khΓ©p, >0 = miệng mở.
    horizontal_width: KhoαΊ£ng cΓ‘ch ngang giα»―a 2 khΓ³e miệng trong.
    """
    lmk = np.zeros((106, 2), dtype=np.float32)

    # Inner lip corners (horizontal base)
    cx, cy = 320.0, 240.0
    half_w = horizontal_width / 2.0

    lmk[96] = [cx - half_w, cy]      # KhΓ³e miệng trong trΓ‘i
    lmk[100] = [cx + half_w, cy]     # KhΓ³e miệng trong phαΊ£i

    # Inner lip vertical pairs – symmetric gap
    half_gap = inner_lip_gap / 2.0
    # Pair (97, 103) – trΓ‘i
    lmk[97] = [cx - half_w * 0.6, cy - half_gap]
    lmk[103] = [cx - half_w * 0.6, cy + half_gap]
    # Pair (98, 102) – giα»―a
    lmk[98] = [cx, cy - half_gap]
    lmk[102] = [cx, cy + half_gap]
    # Pair (99, 101) – phαΊ£i
    lmk[99] = [cx + half_w * 0.6, cy - half_gap]
    lmk[101] = [cx + half_w * 0.6, cy + half_gap]

    return lmk


# ──────────────────────────────────────────────────────────────────────────────
# Test: calculate_mar (Inner Lips)
# ──────────────────────────────────────────────────────────────────────────────
class TestCalculateMAR:
    """Test MAR calculation using Inner Lips indices."""

    def test_closed_mouth_returns_near_zero(self):
        """Miệng khΓ©p hoΓ n toΓ n β†’ MAR β‰ˆ 0."""
        lmk = _make_landmarks_106(inner_lip_gap=0.0)
        mar = ExamFaceDetector.calculate_mar(lmk)
        assert mar == pytest.approx(0.0, abs=1e-6)

    def test_open_mouth_returns_positive_mar(self):
        """Miệng mở β†’ MAR > 0."""
        lmk = _make_landmarks_106(inner_lip_gap=20.0, horizontal_width=60.0)
        mar = ExamFaceDetector.calculate_mar(lmk)
        # Expected: vertical_avg/horizontal = 20/60 β‰ˆ 0.333
        assert mar > 0.3
        assert mar < 0.4

    def test_wide_open_mouth_higher_mar(self):
        """Miệng mở rα»™ng β†’ MAR lα»›n hΖ‘n miệng hΓ©."""
        lmk_slight = _make_landmarks_106(inner_lip_gap=5.0)
        lmk_wide = _make_landmarks_106(inner_lip_gap=30.0)
        mar_slight = ExamFaceDetector.calculate_mar(lmk_slight)
        mar_wide = ExamFaceDetector.calculate_mar(lmk_wide)
        assert mar_wide > mar_slight

    def test_none_landmarks_returns_zero(self):
        """Landmarks None β†’ MAR = 0."""
        assert ExamFaceDetector.calculate_mar(None) == 0.0

    def test_insufficient_landmarks_returns_zero(self):
        """Landmarks < 106 Δ‘iểm β†’ MAR = 0."""
        lmk = np.zeros((50, 2), dtype=np.float32)
        assert ExamFaceDetector.calculate_mar(lmk) == 0.0

    def test_zero_horizontal_returns_zero(self):
        """Horizontal distance β‰ˆ 0 β†’ trΓ‘nh chia cho 0."""
        lmk = np.zeros((106, 2), dtype=np.float32)
        # TαΊ₯t cαΊ£ Δ‘iểm trΓΉng nhau β†’ horizontal = 0
        assert ExamFaceDetector.calculate_mar(lmk) == 0.0


# ──────────────────────────────────────────────────────────────────────────────
# Test: evaluate_mouth_movement (Variance-based)
# ──────────────────────────────────────────────────────────────────────────────
class TestEvaluateMouthMovement:
    """Test variance-based mouth movement detection."""

    def setup_method(self):
        """Khởi tαΊ‘o controller vα»›i threshold nhỏ để test dα»… hΖ‘n."""
        self.controller = ExamCheatController(
            mar_variance_threshold=0.001,
        )

    def test_static_mouth_not_moving(self):
        """
        Miệng tΔ©nh (MAR khΓ΄ng Δ‘α»•i) β†’ variance β‰ˆ 0 β†’ is_moving = False.
        VΓ­ dα»₯: ThΓ­ sinh ngαΊ­m miệng im lαΊ·ng.
        """
        sid = "test-static"
        state = self.controller._get_or_create_session(sid)
        # Đẩy 5 giΓ‘ trα»‹ MAR giα»‘ng nhau vΓ o buffer
        for _ in range(5):
            state.mar_history.append(0.05)

        is_moving, variance = self.controller.evaluate_mouth_movement(sid)
        assert is_moving is False
        assert variance < 0.001

    def test_moving_mouth_detected(self):
        """
        Miệng cα»­ Δ‘α»™ng (MAR thay Δ‘α»•i liΓͺn tα»₯c) β†’ variance lα»›n β†’ is_moving = True.
        VΓ­ dα»₯: ThΓ­ sinh Δ‘ang nΓ³i chuyện.
        """
        sid = "test-moving"
        state = self.controller._get_or_create_session(sid)
        # MΓ΄ phỏng MAR dao Δ‘α»™ng khi nΓ³i: mở β†’ Δ‘Γ³ng β†’ mở β†’ Δ‘Γ³ng β†’ mở
        for mar in [0.05, 0.25, 0.08, 0.30, 0.06]:
            state.mar_history.append(mar)

        is_moving, variance = self.controller.evaluate_mouth_movement(sid)
        assert is_moving is True
        assert variance > 0.001

    def test_insufficient_samples_returns_not_moving(self):
        """
        Ít hΖ‘n 3 mαΊ«u β†’ khΓ΄ng Δ‘α»§ dα»― liệu β†’ mαΊ·c Δ‘α»‹nh is_moving = False.
        TrΓ‘nh false positive khi thΓ­ sinh vα»«a kαΊΏt nα»‘i.
        """
        sid = "test-few"
        state = self.controller._get_or_create_session(sid)
        state.mar_history.append(0.1)
        state.mar_history.append(0.3)

        is_moving, variance = self.controller.evaluate_mouth_movement(sid)
        assert is_moving is False
        assert variance == 0.0

    def test_thick_lips_static_not_false_positive(self):
        """
        Người cΓ³ mΓ΄i dΓ y β†’ MAR baseline cao hΖ‘n (vΓ­ dα»₯ 0.15 thay vΓ¬ 0.05)
        nhΖ°ng NαΊΎU miệng tΔ©nh β†’ variance vαΊ«n β‰ˆ 0 β†’ KHΓ”NG false positive.

        ĐÒy lΓ  lΓ½ do cα»‘t lΓ΅i dΓΉng variance thay vΓ¬ threshold tΔ©nh.
        """
        sid = "test-thick-lips"
        state = self.controller._get_or_create_session(sid)
        # MAR baseline cao nhΖ°ng α»•n Δ‘α»‹nh β†’ tΔ©nh
        for _ in range(5):
            state.mar_history.append(0.15)

        is_moving, variance = self.controller.evaluate_mouth_movement(sid)
        assert is_moving is False


# ──────────────────────────────────────────────────────────────────────────────
# Test: Session isolation (Multi-user)
# ──────────────────────────────────────────────────────────────────────────────
class TestSessionIsolation:
    """Test that different sessions don't leak state."""

    def setup_method(self):
        self.controller = ExamCheatController()

    def test_different_sessions_have_separate_buffers(self):
        """2 thΓ­ sinh khΓ‘c nhau phαΊ£i cΓ³ MAR buffer riΓͺng."""
        s1 = self.controller._get_or_create_session("student-A")
        s2 = self.controller._get_or_create_session("student-B")

        s1.mar_history.append(0.1)
        s1.mar_history.append(0.2)

        # Student B's buffer phαΊ£i rα»—ng
        assert len(s2.mar_history) == 0
        assert len(s1.mar_history) == 2

    def test_clear_session_removes_state(self):
        """clear_session phαΊ£i xΓ³a state hoΓ n toΓ n."""
        self.controller._get_or_create_session("temp")
        assert self.controller.active_session_count == 1

        self.controller.clear_session("temp")
        assert self.controller.active_session_count == 0

    def test_clear_nonexistent_session_no_error(self):
        """XΓ³a session khΓ΄ng tα»“n tαΊ‘i β†’ khΓ΄ng lα»—i."""
        self.controller.clear_session("nonexistent")  # Should not raise


# ──────────────────────────────────────────────────────────────────────────────
# Test: Cross-check decision matrix (process_payload)
# ──────────────────────────────────────────────────────────────────────────────
class TestCrossCheckMatrix:
    """Test the cross-check decision logic in process_payload."""

    def setup_method(self):
        self.controller = ExamCheatController(
            mar_variance_threshold=0.001,
            speech_debounce_seconds=1.5,
        )

    def _mock_multimodal(
        self,
        face_count: int = 1,
        mar_value: float = 0.0,
        is_looking_away: bool = False,
        has_landmarks: bool = True,
    ) -> MultimodalResult:
        """Helper to create a MultimodalResult."""
        return MultimodalResult(
            face_count=face_count,
            bboxes=[[0, 0, 100, 100]] * face_count,
            mar_value=mar_value,
            is_looking_away=is_looking_away,
            has_landmarks=has_landmarks,
        )

    @patch.object(ExamFaceDetector, "process_frame_multimodal")
    @patch.object(ExamFaceDetector, "decode_base64_image")
    def test_no_speech_returns_normal(self, mock_decode, mock_process):
        """speech_detected=False β†’ Level 0 (bΓ¬nh thường), bỏ qua decode."""
        result = self.controller.process_payload("s1", {
            "speech_detected": False,
            "image": "fake",
        })
        assert result["level"] == LEVEL_NORMAL
        # KhΓ΄ng cαΊ§n decode αΊ£nh khi khΓ΄ng cΓ³ tiαΊΏng nΓ³i
        mock_decode.assert_not_called()

    @patch.object(ExamFaceDetector, "process_frame_multimodal")
    @patch.object(ExamFaceDetector, "decode_base64_image")
    def test_speech_with_moving_mouth_returns_mild(self, mock_decode, mock_process):
        """
        speech=True + miệng cα»­ Δ‘α»™ng + nhΓ¬n thαΊ³ng β†’ Level 1 (đọc nhαΊ©m).
        """
        mock_decode.return_value = np.zeros((480, 640, 3), dtype=np.uint8)
        mock_process.return_value = self._mock_multimodal(
            mar_value=0.2, is_looking_away=False,
        )

        sid = "s-mild"
        state = self.controller._get_or_create_session(sid)
        # Đẩy MAR dao Δ‘α»™ng vΓ o buffer để is_mouth_moving = True
        for mar in [0.05, 0.25, 0.08, 0.30, 0.06]:
            state.mar_history.append(mar)

        result = self.controller.process_payload(sid, {
            "speech_detected": True,
            "image": "data:image/jpeg;base64,/9j/fake",
        })
        assert result["level"] == LEVEL_MILD_WARNING

    @patch.object(ExamFaceDetector, "process_frame_multimodal")
    @patch.object(ExamFaceDetector, "decode_base64_image")
    def test_speech_with_moving_mouth_looking_away_returns_l1(
        self, mock_decode, mock_process
    ):
        """
        speech=True + miệng cα»­ Δ‘α»™ng + nhΓ¬n Δ‘i β†’ Level 2 (quay sang nΓ³i).
        """
        mock_decode.return_value = np.zeros((480, 640, 3), dtype=np.uint8)
        mock_process.return_value = self._mock_multimodal(
            mar_value=0.2, is_looking_away=True,
        )

        sid = "s-l1"
        state = self.controller._get_or_create_session(sid)
        for mar in [0.05, 0.25, 0.08, 0.30, 0.06]:
            state.mar_history.append(mar)

        result = self.controller.process_payload(sid, {
            "speech_detected": True,
            "image": "data:image/jpeg;base64,/9j/fake",
        })
        assert result["level"] == LEVEL_WARNING_L1

    @patch.object(ExamFaceDetector, "process_frame_multimodal")
    @patch.object(ExamFaceDetector, "decode_base64_image")
    def test_speech_no_movement_under_debounce_waits(
        self, mock_decode, mock_process
    ):
        """
        speech=True + miệng tΔ©nh + thời gian < 1.5s β†’ Level 0 (chờ debounce).
        Kα»‹ch bαΊ£n: tiαΊΏng ho ngαΊ―n, chΖ°a Δ‘α»§ thời gian kαΊΏt luαΊ­n.
        """
        mock_decode.return_value = np.zeros((480, 640, 3), dtype=np.uint8)
        mock_process.return_value = self._mock_multimodal(
            mar_value=0.05, is_looking_away=False,
        )

        sid = "s-debounce"
        state = self.controller._get_or_create_session(sid)
        # Buffer tΔ©nh (variance β‰ˆ 0)
        for _ in range(5):
            state.mar_history.append(0.05)

        result = self.controller.process_payload(sid, {
            "speech_detected": True,
            "image": "data:image/jpeg;base64,/9j/fake",
        })
        # LαΊ§n Δ‘αΊ§u speech_detected β†’ bαΊ―t Δ‘αΊ§u Δ‘αΊΏm β†’ chΖ°a Δ‘α»§ 1.5s
        assert result["level"] == LEVEL_NORMAL

    @patch.object(ExamFaceDetector, "process_frame_multimodal")
    @patch.object(ExamFaceDetector, "decode_base64_image")
    def test_speech_no_movement_over_debounce_returns_l2(
        self, mock_decode, mock_process
    ):
        """
        speech=True + miệng tΔ©nh + thời gian > 1.5s β†’ Level 3 (người khΓ‘c nhαΊ―c bΓ i).
        """
        mock_decode.return_value = np.zeros((480, 640, 3), dtype=np.uint8)
        mock_process.return_value = self._mock_multimodal(
            mar_value=0.05, is_looking_away=False,
        )

        sid = "s-l2"
        state = self.controller._get_or_create_session(sid)
        # Buffer tΔ©nh
        for _ in range(5):
            state.mar_history.append(0.05)
        # GiαΊ£ lαΊ­p speech Δ‘Γ£ kΓ©o dΓ i > 1.5s
        state.speech_start_time = time.monotonic() - 2.0

        result = self.controller.process_payload(sid, {
            "speech_detected": True,
            "image": "data:image/jpeg;base64,/9j/fake",
        })
        assert result["level"] == LEVEL_WARNING_L2

    @patch.object(ExamFaceDetector, "process_frame_multimodal")
    @patch.object(ExamFaceDetector, "decode_base64_image")
    def test_no_face_with_speech_returns_l2(self, mock_decode, mock_process):
        """
        speech=True + khΓ΄ng thαΊ₯y mαΊ·t β†’ Level 3 (người khΓ‘c nhαΊ―c bΓ i).
        """
        mock_decode.return_value = np.zeros((480, 640, 3), dtype=np.uint8)
        mock_process.return_value = self._mock_multimodal(face_count=0)

        result = self.controller.process_payload("s-noface", {
            "speech_detected": True,
            "image": "data:image/jpeg;base64,/9j/fake",
        })
        assert result["level"] == LEVEL_WARNING_L2

    def test_missing_image_returns_error(self):
        """Payload thiαΊΏu image β†’ error."""
        result = self.controller.process_payload("s-err", {
            "speech_detected": True,
        })
        assert result["level"] == -1
        assert "ThiαΊΏu" in result["message"]

    @patch.object(ExamFaceDetector, "process_frame_multimodal")
    @patch.object(ExamFaceDetector, "decode_base64_image")
    def test_speech_end_resets_timer(self, mock_decode, mock_process):
        """
        speech_detected chuyển tα»« True β†’ False phαΊ£i reset speech_start_time.
        """
        sid = "s-reset"
        state = self.controller._get_or_create_session(sid)
        state.speech_start_time = time.monotonic() - 5.0  # Đang Δ‘αΊΏm

        result = self.controller.process_payload(sid, {
            "speech_detected": False,
        })
        assert result["level"] == LEVEL_NORMAL
        assert state.speech_start_time == 0.0