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
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
"""Rule engine for scan-mode alerting.

Each scan session owns its own ``RuleEngine`` instance. On every
inference tick the session calls ``engine.tick(ts, vehicle, person)``
which returns a (possibly empty) list of fires.

Rule kinds shipped at v1:

- **sustained_count** — fires when the target count stays at or above
  ``threshold`` for ``sustained_seconds`` of contiguous ticks. Used by
  the "Kemacetan" (kendaraan) and "Keramaian" (orang) presets.

- **sudden_drop** — fires when the target count crashes by ``drop_pct``
  (default 50 %) from a recent baseline of at least ``threshold``. Used
  as a (very rough) accident proxy: cars stop and either pile up or
  bystanders block the lane → count of detected vehicles plummets while
  the previous tick was still busy. Real crash detection needs a
  dedicated model; this just surfaces "something dramatic just changed."

Time is wall-clock seconds (float) so the engine is independent of
inference cadence — a rule with ``sustained_seconds=60`` fires after
60 wall seconds whether the session ticks at 1 fps or 5 fps."""
from __future__ import annotations

import logging
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Optional

log = logging.getLogger(__name__)


RuleKind = str  # "sustained_count" | "sudden_drop"
RuleTarget = str  # "vehicle" | "person" | "any"


@dataclass(slots=True)
class Rule:
    name: str
    kind: RuleKind
    target: RuleTarget
    threshold: int
    cooldown_seconds: float = 60.0
    severity: str = "info"
    # sustained_count knobs
    sustained_seconds: float = 30.0
    # sudden_drop knobs
    window_seconds: float = 5.0
    baseline_seconds: float = 5.0
    drop_pct: float = 0.5

    def to_dict(self) -> dict[str, Any]:
        return {
            "name":              self.name,
            "kind":              self.kind,
            "target":            self.target,
            "threshold":         self.threshold,
            "cooldown_seconds":  self.cooldown_seconds,
            "severity":          self.severity,
            "sustained_seconds": self.sustained_seconds,
            "window_seconds":    self.window_seconds,
            "baseline_seconds":  self.baseline_seconds,
            "drop_pct":          self.drop_pct,
        }

    @classmethod
    def from_dict(cls, d: dict[str, Any]) -> "Rule":
        return cls(
            name=str(d["name"]),
            kind=str(d.get("kind", "sustained_count")),
            target=str(d.get("target", "vehicle")),
            threshold=int(d.get("threshold", 10)),
            cooldown_seconds=float(d.get("cooldown_seconds", 60.0)),
            severity=str(d.get("severity", "info")),
            sustained_seconds=float(d.get("sustained_seconds", 30.0)),
            window_seconds=float(d.get("window_seconds", 5.0)),
            baseline_seconds=float(d.get("baseline_seconds", 5.0)),
            drop_pct=float(d.get("drop_pct", 0.5)),
        )


@dataclass(slots=True)
class AlertFire:
    rule: Rule
    fired_at: float
    metrics: dict[str, Any]


# History entry — kept small; engine prunes by oldest ts past needed window.
@dataclass(slots=True)
class _Sample:
    ts: float
    vehicle: int
    person: int


def _count_for(sample: _Sample, target: RuleTarget) -> int:
    if target == "vehicle":
        return sample.vehicle
    if target == "person":
        return sample.person
    return sample.vehicle + sample.person


class RuleEngine:
    def __init__(self, rules: list[Rule], history_capacity: int = 1024):
        self.rules: list[Rule] = list(rules)
        # Per-rule last fired ts (monotonic-style float, same domain as
        # the caller's ``ts`` argument). Zero = never fired.
        self._last_fired: dict[str, float] = {r.name: 0.0 for r in self.rules}
        # Rolling sample history, oldest → newest. Cap at history_capacity
        # so a misconfigured rule with a 1-hour window doesn't blow memory.
        self._history: deque[_Sample] = deque(maxlen=history_capacity)

    # ---------- public ----------
    def update_rules(self, rules: list[Rule]) -> None:
        """Replace the active rule set. Cooldowns are preserved for
        rules whose name survives — by-name match, by design (analyst
        nudging a threshold shouldn't reset the cooldown)."""
        carry = {r.name: self._last_fired.get(r.name, 0.0) for r in rules}
        self.rules = list(rules)
        self._last_fired = carry

    def tick(self, ts: float, vehicle: int, person: int) -> list[AlertFire]:
        self._history.append(_Sample(ts=ts, vehicle=vehicle, person=person))
        self._prune(ts)

        fires: list[AlertFire] = []
        for rule in self.rules:
            # Cooldown gate. Each rule has its own clock.
            last = self._last_fired.get(rule.name, 0.0)
            if last > 0 and (ts - last) < rule.cooldown_seconds:
                continue
            fire = self._evaluate(rule, ts)
            if fire is not None:
                self._last_fired[rule.name] = ts
                fires.append(fire)
        return fires

    # ---------- progress (for FE probability bar) ----------
    def progress_snapshot(self, ts: float) -> list[dict[str, Any]]:
        """Per-rule "probability of firing" snapshot for the FE.

        Each entry is a small dict:
          - ``name`` / ``kind`` / ``target`` / ``severity``
          - ``progress``      — 0.0 → 1.0 (1.0 = fires now if cooldown clear)
          - ``current``       — current target count (latest sample)
          - ``threshold``     — copied from rule for FE display
          - ``cooldown_left`` — seconds remaining in cooldown (0 if ready)
          - kind-specific extras (sustained_progress, drop_ratio, …)

        The shape mirrors what an analyst wants to *eyeball*: how close
        the rule is to triggering right now.
        """
        if not self._history:
            return [self._idle_progress(rule) for rule in self.rules]
        latest = self._history[-1]
        snapshots: list[dict[str, Any]] = []
        for rule in self.rules:
            cooldown_left = self._cooldown_left(rule, ts)
            base = {
                "name":          rule.name,
                "kind":          rule.kind,
                "target":        rule.target,
                "severity":      rule.severity,
                "threshold":     rule.threshold,
                "current":       _count_for(latest, rule.target),
                "cooldown_left": round(cooldown_left, 1),
            }
            if rule.kind == "sustained_count":
                base.update(self._progress_sustained(rule, ts, latest))
            elif rule.kind == "sudden_drop":
                base.update(self._progress_drop(rule, ts, latest))
            else:
                base["progress"] = 0.0
            snapshots.append(base)
        return snapshots

    def _idle_progress(self, rule: Rule) -> dict[str, Any]:
        return {
            "name":          rule.name,
            "kind":          rule.kind,
            "target":        rule.target,
            "severity":      rule.severity,
            "threshold":     rule.threshold,
            "current":       0,
            "cooldown_left": 0.0,
            "progress":      0.0,
        }

    def _cooldown_left(self, rule: Rule, ts: float) -> float:
        last = self._last_fired.get(rule.name, 0.0)
        if last <= 0:
            return 0.0
        remaining = rule.cooldown_seconds - (ts - last)
        return max(0.0, remaining)

    def _progress_sustained(
        self, rule: Rule, ts: float, latest: _Sample,
    ) -> dict[str, Any]:
        # Two factors blended into a single 0-1 progress:
        #   - count_ratio: current / threshold (capped at 1)
        #   - sustained_ratio: how much of the window has held at/above threshold
        # Geometric mean rewards "both factors high"; a brief spike to 2×
        # threshold without sustain doesn't peg the meter on its own.
        count = _count_for(latest, rule.target)
        count_ratio = min(1.0, count / max(1, rule.threshold))
        lo = ts - rule.sustained_seconds
        window = [s for s in self._history if s.ts >= lo]
        if window:
            above = [s for s in window if _count_for(s, rule.target) >= rule.threshold]
            if above:
                span = above[-1].ts - above[0].ts
                sustained_ratio = min(1.0, span / max(0.1, rule.sustained_seconds))
            else:
                sustained_ratio = 0.0
        else:
            sustained_ratio = 0.0
        progress = round((count_ratio * sustained_ratio) ** 0.5, 3)
        return {
            "progress":          progress,
            "count_ratio":       round(count_ratio, 3),
            "sustained_ratio":   round(sustained_ratio, 3),
            "sustained_seconds": rule.sustained_seconds,
        }

    def _progress_drop(
        self, rule: Rule, ts: float, latest: _Sample,
    ) -> dict[str, Any]:
        baseline_lo = ts - rule.window_seconds - rule.baseline_seconds
        baseline_hi = ts - rule.window_seconds
        recent_lo = ts - rule.window_seconds
        baseline_window = [
            s for s in self._history if baseline_lo <= s.ts < baseline_hi
        ]
        recent_window = [s for s in self._history if s.ts >= recent_lo]
        if not baseline_window or not recent_window:
            return {
                "progress":      0.0,
                "drop_ratio":    0.0,
                "baseline":      0,
                "recent":        _count_for(latest, rule.target),
            }
        baseline = max(_count_for(s, rule.target) for s in baseline_window)
        recent_max = max(_count_for(s, rule.target) for s in recent_window)
        if baseline <= 0:
            drop_ratio = 0.0
        else:
            drop_ratio = max(0.0, min(1.0, 1.0 - recent_max / baseline))
        if baseline < rule.threshold:
            # Not enough activity in the baseline window for the rule
            # to be meaningful; floor progress to 0 so the meter isn't
            # alarming when nothing is happening.
            progress = 0.0
        else:
            # Need both: enough drop AND a meaningful baseline.
            ratio_progress = drop_ratio / max(0.01, rule.drop_pct)
            progress = min(1.0, ratio_progress)
        return {
            "progress":   round(progress, 3),
            "drop_ratio": round(drop_ratio, 3),
            "baseline":   int(baseline),
            "recent":     int(recent_max),
        }

    # ---------- internals ----------
    def _prune(self, ts: float) -> None:
        needed = 0.0
        for r in self.rules:
            if r.kind == "sustained_count":
                needed = max(needed, r.sustained_seconds)
            elif r.kind == "sudden_drop":
                needed = max(needed, r.window_seconds + r.baseline_seconds)
        # Add a small slop so the window evaluator has its lower bound.
        cutoff = ts - (needed + 5.0)
        while self._history and self._history[0].ts < cutoff:
            self._history.popleft()

    def _evaluate(self, rule: Rule, ts: float) -> Optional[AlertFire]:
        if rule.kind == "sustained_count":
            return self._eval_sustained(rule, ts)
        if rule.kind == "sudden_drop":
            return self._eval_drop(rule, ts)
        log.warning("unknown rule kind: %s (%s)", rule.kind, rule.name)
        return None

    def _eval_sustained(self, rule: Rule, ts: float) -> Optional[AlertFire]:
        lo = ts - rule.sustained_seconds
        window = [s for s in self._history if s.ts >= lo]
        if not window:
            return None
        # Require the window to actually span ``sustained_seconds`` so a
        # cold-start session doesn't fire on the first frame.
        if (window[-1].ts - window[0].ts) < rule.sustained_seconds * 0.9:
            return None
        counts = [_count_for(s, rule.target) for s in window]
        if min(counts) < rule.threshold:
            return None
        return AlertFire(
            rule=rule,
            fired_at=ts,
            metrics={
                "trigger":          "sustained_count",
                "target":           rule.target,
                "threshold":        rule.threshold,
                "sustained_seconds": rule.sustained_seconds,
                "min_in_window":    int(min(counts)),
                "max_in_window":    int(max(counts)),
                "avg_in_window":    round(sum(counts) / len(counts), 2),
                "samples":          len(counts),
                "last_vehicle":     window[-1].vehicle,
                "last_person":      window[-1].person,
            },
        )

    def _eval_drop(self, rule: Rule, ts: float) -> Optional[AlertFire]:
        baseline_lo = ts - rule.window_seconds - rule.baseline_seconds
        baseline_hi = ts - rule.window_seconds
        recent_lo = ts - rule.window_seconds
        baseline_window = [
            s for s in self._history if baseline_lo <= s.ts < baseline_hi
        ]
        recent_window = [s for s in self._history if s.ts >= recent_lo]
        if not baseline_window or not recent_window:
            return None
        baseline = max(_count_for(s, rule.target) for s in baseline_window)
        if baseline < rule.threshold:
            return None
        recent_max = max(_count_for(s, rule.target) for s in recent_window)
        if baseline <= 0:
            return None
        ratio = recent_max / baseline
        if ratio > (1.0 - rule.drop_pct):
            return None
        return AlertFire(
            rule=rule,
            fired_at=ts,
            metrics={
                "trigger":         "sudden_drop",
                "target":          rule.target,
                "threshold":       rule.threshold,
                "baseline_count":  int(baseline),
                "recent_count":    int(recent_max),
                "drop_pct":        round(1.0 - ratio, 3),
                "window_seconds":  rule.window_seconds,
                "baseline_seconds": rule.baseline_seconds,
                "last_vehicle":    recent_window[-1].vehicle,
                "last_person":     recent_window[-1].person,
            },
        )


# ---------- shipped presets ----------
# Threshold + window tuning sengaja di-baca dari env (lihat app/config.py)
# supaya operator bisa geser ambang per kota tanpa redeploy. Diakses via
# property ``PRESETS`` yang rebuild dari ``settings`` setiap call — biar
# perubahan env (mis. via container restart) langsung ke-pick-up tanpa
# perlu reload modul.

# `kecelakaan` (sudden_drop) dihapus — terlalu eksperimental untuk
# production: drop count vehicle bisa jadi karena banyak hal selain
# kecelakaan (frame loss, occlusion, kamera buram). Real crash detection
# butuh model dedicated. Bisa di-revisit nanti.


def _build_presets() -> dict[str, Rule]:
    # Import dalam fungsi untuk menghindari circular import; rule_engine
    # tidak butuh ``settings`` saat module load (Detector/etc bisa dipakai
    # standalone untuk smoke test).
    #
    # Preset keys ("kemacetan", "keramaian") sengaja Indonesian — itu
    # user-facing slug yang FE pakai; tuning knob-nya di settings pakai
    # English (scan_traffic_jam_*, scan_crowd_*).
    from app.config import settings
    return {
        "kemacetan": Rule(
            name="Kemacetan",
            kind="sustained_count",
            target="vehicle",
            threshold=settings.scan_traffic_jam_threshold,
            sustained_seconds=settings.scan_traffic_jam_sustained_seconds,
            cooldown_seconds=settings.scan_traffic_jam_cooldown_seconds,
            severity="warning",
        ),
        "keramaian": Rule(
            name="Keramaian",
            kind="sustained_count",
            target="person",
            threshold=settings.scan_crowd_threshold,
            sustained_seconds=settings.scan_crowd_sustained_seconds,
            cooldown_seconds=settings.scan_crowd_cooldown_seconds,
            severity="warning",
        ),
    }


class _PresetsProxy:
    """Dict-like view yang rebuild snapshot dari env setiap akses.

    Memungkinkan ``PRESETS["kemacetan"]`` dan ``PRESETS.values()`` tetap
    bekerja seperti dict biasa (route ``/scan/presets`` + ``routes_scan
    .start_scan`` fallback) tanpa perlu refactor caller-nya."""

    def _snap(self) -> dict[str, Rule]:
        return _build_presets()

    def __getitem__(self, key: str) -> Rule:
        return self._snap()[key]

    def __contains__(self, key: object) -> bool:
        return key in self._snap()

    def __iter__(self):
        return iter(self._snap())

    def __len__(self) -> int:
        return len(self._snap())

    def keys(self):
        return self._snap().keys()

    def values(self):
        return self._snap().values()

    def items(self):
        return self._snap().items()

    def get(self, key: str, default: Optional[Rule] = None) -> Optional[Rule]:
        return self._snap().get(key, default)


PRESETS = _PresetsProxy()


def preset(name: str) -> Optional[Rule]:
    p = PRESETS.get(name.lower().strip())
    if p is None:
        return None
    # Return a copy so the global preset isn't mutated by per-CCTV edits.
    return Rule(**{k: getattr(p, k) for k in p.__slots__})