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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
"""
Thread-safe in-memory fallback store when DATABASE_URL is not configured.
Ensures stateless local runs, previews, and tests never crash with
RuntimeError("DATABASE_URL is not configured.") across pairs, signals,
snapshots, trade journal, and Damian memory APIs.
"""

import copy
import threading
from datetime import datetime, timezone
from typing import Any


def _utc_now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


class InMemoryDatabaseStore:
    """Thread-safe bounded in-memory mirror of the PostgreSQL schema."""

    def __init__(self) -> None:
        self._lock = threading.RLock()
        self._pair_seq = 0
        self._signal_seq = 0
        self._snapshot_seq = 0
        self._journal_seq = 0
        self._memory_seq = 0
        self._prediction_seq = 0
        self._pairs: dict[str, dict[str, Any]] = {}
        self._signals: dict[str, list[dict[str, Any]]] = {}
        self._snapshots: dict[str, dict[str, dict[str, Any]]] = {}
        self._journal: dict[int, dict[str, Any]] = {}
        self._memories: list[dict[str, Any]] = []
        self._predictions: dict[int, dict[str, Any]] = {}
        self._hl_wallets: dict[str, dict[str, Any]] = {}
        self._microstructure_tape: list[dict[str, Any]] = []
        self._tape_seq = 0
        self._seed_defaults()

    def _seed_defaults(self) -> None:
        now = _utc_now_iso()
        for sym, disp in (("BTCUSDT", "BTC/USDT"), ("ETHUSDT", "ETH/USDT"), ("SOLUSDT", "SOL/USDT")):
            self._pair_seq += 1
            self._pairs[sym] = {
                "id": self._pair_seq,
                "symbol": sym,
                "display_name": disp,
                "on_binance": True,
                "on_bybit": True,
                "on_okx": True,
                "on_bitget": True,
                "on_hyperliquid": True,
                "streak_count": 0,
                "streak_direction": "NEUTRAL",
                "last_conviction": 0,
                "is_active": True,
                "created_at": now,
            }

    def reset(self) -> None:
        with self._lock:
            self._pair_seq = 0
            self._signal_seq = 0
            self._snapshot_seq = 0
            self._journal_seq = 0
            self._memory_seq = 0
            self._prediction_seq = 0
            self._pairs.clear()
            self._signals.clear()
            self._snapshots.clear()
            self._journal.clear()
            self._memories.clear()
            self._predictions.clear()
            self._hl_wallets.clear()
            self._microstructure_tape.clear()
            self._tape_seq = 0
            self._seed_defaults()

    # ── Pairs ────────────────────────────────────────────────────────────────
    def get_all_pairs(self) -> list[dict[str, Any]]:
        with self._lock:
            rows = list(self._pairs.values())
            rows.sort(key=lambda p: (p.get("created_at") or "", int(p.get("id") or 0)), reverse=True)
            return [copy.deepcopy(r) for r in rows]

    def get_pair(self, symbol: str) -> dict[str, Any] | None:
        with self._lock:
            row = self._pairs.get(symbol.upper())
            return copy.deepcopy(row) if row else None

    def insert_pair(
        self,
        symbol: str,
        display_name: str,
        on_binance: bool = False,
        on_bybit: bool = False,
        on_okx: bool = False,
        on_bitget: bool = False,
        on_hyperliquid: bool = False,
    ) -> dict[str, Any]:
        sym = symbol.upper()
        with self._lock:
            existing = self._pairs.get(sym)
            if existing:
                existing.update({
                    "display_name": display_name,
                    "on_binance": bool(on_binance),
                    "on_bybit": bool(on_bybit),
                    "on_okx": bool(on_okx),
                    "on_bitget": bool(on_bitget),
                    "on_hyperliquid": bool(on_hyperliquid),
                    "is_active": True,
                })
                return copy.deepcopy(existing)
            self._pair_seq += 1
            row = {
                "id": self._pair_seq,
                "symbol": sym,
                "display_name": display_name,
                "on_binance": bool(on_binance),
                "on_bybit": bool(on_bybit),
                "on_okx": bool(on_okx),
                "on_bitget": bool(on_bitget),
                "on_hyperliquid": bool(on_hyperliquid),
                "streak_count": 0,
                "streak_direction": "NEUTRAL",
                "last_conviction": 0,
                "is_active": True,
                "created_at": _utc_now_iso(),
            }
            self._pairs[sym] = row
            return copy.deepcopy(row)

    def update_pair_exchanges(
        self,
        symbol: str,
        on_binance: bool,
        on_bybit: bool,
        on_okx: bool = False,
        on_bitget: bool = False,
        on_hyperliquid: bool = False,
    ) -> dict[str, Any] | None:
        sym = symbol.upper()
        with self._lock:
            row = self._pairs.get(sym)
            if not row:
                return None
            row.update({
                "on_binance": bool(on_binance),
                "on_bybit": bool(on_bybit),
                "on_okx": bool(on_okx),
                "on_bitget": bool(on_bitget),
                "on_hyperliquid": bool(on_hyperliquid),
            })
            return copy.deepcopy(row)

    def update_pair_streak(
        self,
        symbol: str,
        streak_count: int,
        streak_direction: str,
        last_conviction: int,
    ) -> dict[str, Any] | None:
        sym = symbol.upper()
        with self._lock:
            row = self._pairs.get(sym)
            if not row:
                return None
            row.update({
                "streak_count": int(streak_count),
                "streak_direction": str(streak_direction),
                "last_conviction": int(last_conviction),
            })
            return copy.deepcopy(row)

    def delete_pair(self, symbol: str) -> bool:
        sym = symbol.upper()
        with self._lock:
            return self._pairs.pop(sym, None) is not None

    def delete_pair_by_identifier(self, identifier: str) -> bool:
        with self._lock:
            if identifier.isdigit():
                target_id = int(identifier)
                for sym, row in list(self._pairs.items()):
                    if row.get("id") == target_id:
                        del self._pairs[sym]
                        return True
                return False
            return self._pairs.pop(identifier.upper(), None) is not None

    def toggle_pair(self, symbol: str) -> dict[str, Any] | None:
        sym = symbol.upper()
        with self._lock:
            row = self._pairs.get(sym)
            if not row:
                return None
            row["is_active"] = not bool(row.get("is_active", True))
            return copy.deepcopy(row)

    def toggle_pair_by_identifier(self, identifier: str) -> dict[str, Any] | None:
        with self._lock:
            if identifier.isdigit():
                target_id = int(identifier)
                for row in self._pairs.values():
                    if row.get("id") == target_id:
                        row["is_active"] = not bool(row.get("is_active", True))
                        return copy.deepcopy(row)
                return None
            return self.toggle_pair(identifier)

    def get_active_pairs(self) -> list[dict[str, Any]]:
        with self._lock:
            active = [copy.deepcopy(r) for r in self._pairs.values() if r.get("is_active")]
            active.sort(key=lambda r: r["symbol"])
            return active

    def get_stale_active_pairs(self, limit: int | None = None) -> list[dict[str, Any]]:
        with self._lock:
            active = [r for r in self._pairs.values() if r.get("is_active")]

            def _sort_key(pair: dict[str, Any]) -> tuple[str, str]:
                hist = self._signals.get(pair["symbol"], [])
                last_ts = hist[0].get("created_at", "") if hist else ""
                return (last_ts, pair["symbol"])

            active.sort(key=_sort_key)
            if limit is not None and limit > 0:
                active = active[:limit]
            return [copy.deepcopy(r) for r in active]

    # ── Signals & Snapshots ──────────────────────────────────────────────────
    def _enrich_signal_row(self, sig: dict[str, Any]) -> dict[str, Any]:
        out = copy.deepcopy(sig)
        pair = self._pairs.get(out["symbol"], {})
        streak = int(pair.get("streak_count") or 0)
        streak_dir = str(pair.get("streak_direction") or "NEUTRAL")
        last_conv = int(pair.get("last_conviction") or 0)
        out["streak_count"] = streak
        out["streak_direction"] = streak_dir
        out["last_conviction"] = last_conv
        if isinstance(out.get("signal_data"), dict):
            if "streak" not in out["signal_data"] or out["signal_data"].get("streak") is None:
                out["signal_data"]["streak"] = streak
            if "streak_direction" not in out["signal_data"] or not out["signal_data"].get("streak_direction"):
                out["signal_data"]["streak_direction"] = streak_dir
        return out

    def save_signal(
        self,
        symbol: str,
        timeframe: str,
        direction: str,
        conviction: int,
        signal_data: dict[str, Any],
    ) -> None:
        clean_signal_data = signal_data
        if isinstance(signal_data, dict) and "_shadow_trade_levels" in signal_data:
            clean_signal_data = dict(signal_data)
            clean_signal_data.pop("_shadow_trade_levels", None)
        sym = symbol.upper()
        with self._lock:
            self._signal_seq += 1
            entry = {
                "id": self._signal_seq,
                "symbol": sym,
                "timeframe": timeframe,
                "direction": direction,
                "conviction": int(conviction),
                "signal_data": copy.deepcopy(clean_signal_data),
                "created_at": _utc_now_iso(),
            }
            bucket = self._signals.setdefault(sym, [])
            bucket.insert(0, entry)
            if len(bucket) > 100:
                del bucket[100:]

    def get_latest_signals(self) -> list[dict[str, Any]]:
        with self._lock:
            latest = [
                self._enrich_signal_row(bucket[0])
                for sym, bucket in sorted(self._signals.items())
                if bucket
            ]
            return latest

    def get_signal_history(self, symbol: str, limit: int = 50) -> list[dict[str, Any]]:
        sym = symbol.upper()
        with self._lock:
            bucket = self._signals.get(sym, [])[:limit]
            return [self._enrich_signal_row(r) for r in bucket]

    def get_latest_signal(self, symbol: str) -> dict[str, Any] | None:
        sym = symbol.upper()
        with self._lock:
            bucket = self._signals.get(sym)
            if not bucket:
                return None
            return self._enrich_signal_row(bucket[0])

    def save_snapshot(
        self,
        symbol: str,
        exchange: str,
        funding_rate: float | None,
        open_interest: float | None,
        long_ratio: float | None,
        short_ratio: float | None,
        mark_price: float | None,
        index_price: float | None,
        basis_pct: float | None,
    ) -> None:
        sym = symbol.upper()
        ex = exchange.lower()
        with self._lock:
            self._snapshot_seq += 1
            self._snapshots.setdefault(sym, {})[ex] = {
                "id": self._snapshot_seq,
                "symbol": sym,
                "exchange": ex,
                "funding_rate": funding_rate,
                "open_interest": open_interest,
                "long_ratio": long_ratio,
                "short_ratio": short_ratio,
                "mark_price": mark_price,
                "index_price": index_price,
                "basis_pct": basis_pct,
                "snapshot_at": _utc_now_iso(),
            }

    def save_snapshots_batch(self, snapshots: list[tuple]) -> None:
        for snap in snapshots:
            self.save_snapshot(*snap)

    def get_latest_snapshot(self, symbol: str) -> list[dict[str, Any]]:
        sym = symbol.upper()
        with self._lock:
            ex_map = self._snapshots.get(sym, {})
            return [copy.deepcopy(ex_map[ex]) for ex in sorted(ex_map.keys())]

    # ── Trade Journal & Damian Memory ────────────────────────────────────────
    def create_journal_entry(self, data: dict[str, Any]) -> dict[str, Any]:
        with self._lock:
            self._journal_seq += 1
            entry = {
                "id": self._journal_seq,
                "symbol": str(data.get("symbol") or "").upper(),
                "bias": data.get("bias", ""),
                "entry_zone": data.get("entry_zone"),
                "stop_loss": data.get("stop_loss"),
                "take_profit": data.get("take_profit"),
                "risk_reward": data.get("risk_reward"),
                "leverage": data.get("leverage"),
                "invalidation": data.get("invalidation"),
                "summary_tldr": data.get("summary_tldr"),
                "full_analysis": data.get("full_analysis"),
                "model_used": data.get("model_used"),
                "status": str(data.get("status") or "PENDING").upper(),
                "outcome_note": data.get("outcome_note"),
                "outcome_at": None,
                "failure_tag": data.get("failure_tag"),
                "exit_price": data.get("exit_price"),
                "holding_duration_seconds": data.get("holding_duration_seconds"),
                "snapshot_data": copy.deepcopy(data.get("snapshot_data") or {}),
                "audited": False,
                "created_at": _utc_now_iso(),
            }
            self._journal[entry["id"]] = entry
            return copy.deepcopy(entry)

    def get_journal_entries(
        self, status: str | None = None, limit: int = 50, offset: int = 0
    ) -> list[dict[str, Any]]:
        with self._lock:
            rows = list(self._journal.values())
            if status and status.upper() != "ALL":
                target = status.upper()
                rows = [r for r in rows if r.get("status") == target]
            rows.sort(key=lambda r: (r.get("created_at") or "", r["id"]), reverse=True)
            sliced = rows[offset : offset + limit]
            return [copy.deepcopy(r) for r in sliced]

    def update_journal_status(
        self,
        journal_id: int,
        status: str,
        note: str | None = None,
        failure_tag: str | None = None,
        exit_price: float | None = None,
        holding_duration_seconds: int | None = None,
    ) -> dict[str, Any] | None:
        st = status.upper().strip()
        with self._lock:
            entry = self._journal.get(journal_id)
            if not entry:
                return None
            entry["status"] = st
            if st == "PENDING":
                entry["outcome_note"] = None
                entry["outcome_at"] = None
                entry["failure_tag"] = None
                entry["exit_price"] = None
                entry["holding_duration_seconds"] = None
                entry["audited"] = False
                return copy.deepcopy(entry)

            entry["outcome_note"] = note
            entry["outcome_at"] = _utc_now_iso()
            if st == "HIT_SL":
                if failure_tag is not None:
                    entry["failure_tag"] = failure_tag
            else:
                entry["failure_tag"] = None
                entry["audited"] = False
            if exit_price is not None:
                entry["exit_price"] = exit_price
            if holding_duration_seconds is not None:
                entry["holding_duration_seconds"] = holding_duration_seconds
            return copy.deepcopy(entry)

    def delete_journal_entry(self, journal_id: int) -> bool:
        with self._lock:
            return self._journal.pop(journal_id, None) is not None

    def get_journal_stats(self) -> dict[str, Any]:
        with self._lock:
            entries = list(self._journal.values())
            total = len(entries)
            hit_tp = sum(1 for e in entries if e.get("status") == "HIT_TP")
            hit_sl = sum(1 for e in entries if e.get("status") == "HIT_SL")
            pending = sum(1 for e in entries if e.get("status") == "PENDING")
            cancelled = sum(1 for e in entries if e.get("status") == "CANCELLED")
            unaudited_sl = sum(1 for e in entries if e.get("status") == "HIT_SL" and not e.get("audited"))
            completed = hit_tp + hit_sl
            win_rate = round((hit_tp / completed) * 100.0, 1) if completed > 0 else 0.0
            return {
                "total": total,
                "hit_tp": hit_tp,
                "hit_sl": hit_sl,
                "pending": pending,
                "cancelled": cancelled,
                "completed": completed,
                "win_rate_pct": win_rate,
                "unaudited_sl_count": unaudited_sl,
            }

    def get_unaudited_failed_trades(self, limit: int = 10) -> list[dict[str, Any]]:
        with self._lock:
            failed = [
                r for r in self._journal.values()
                if r.get("status") == "HIT_SL" and not r.get("audited")
            ]
            failed.sort(key=lambda r: (r.get("created_at") or "", r["id"]))
            return [copy.deepcopy(r) for r in failed[:limit]]

    def mark_trades_as_audited(self, trade_ids: list[int]) -> None:
        if not trade_ids:
            return
        with self._lock:
            for tid in trade_ids:
                if tid in self._journal:
                    self._journal[tid]["audited"] = True

    def save_damian_memory(self, audit_summary: str, model_used: str, failed_count: int = 10) -> dict[str, Any]:
        with self._lock:
            self._memory_seq += 1
            next_batch = max((int(m.get("batch_index") or 0) for m in self._memories), default=0) + 1
            mem = {
                "id": self._memory_seq,
                "batch_index": next_batch,
                "failed_count": int(failed_count),
                "model_used": model_used,
                "audit_summary": audit_summary,
                "is_active": True,
                "created_at": _utc_now_iso(),
            }
            self._memories.insert(0, mem)
            return copy.deepcopy(mem)

    def get_active_damian_memory(self, limit: int = 3) -> list[dict[str, Any]]:
        with self._lock:
            active = [m for m in self._memories if m.get("is_active", True)]
            return [copy.deepcopy(m) for m in active[:limit]]

    @staticmethod
    def _parse_utc_dt(val: Any) -> datetime | None:
        if val is None:
            return None
        if isinstance(val, datetime):
            return val.replace(tzinfo=timezone.utc) if val.tzinfo is None else val.astimezone(timezone.utc)
        if isinstance(val, str):
            raw = val.strip()
            if not raw:
                return None
            try:
                dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
                return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt.astimezone(timezone.utc)
            except ValueError:
                return None
        return None

    @classmethod
    def _to_iso(cls, val: Any, fallback: str) -> str:
        dt = cls._parse_utc_dt(val)
        if dt is not None:
            return dt.isoformat()
        if isinstance(val, str) and val.strip():
            return val.strip()
        return fallback

    # ── Signal Predictions (Forward Accuracy Tracker) ────────────────────────
    def insert_signal_prediction(self, data: dict[str, Any]) -> dict[str, Any]:
        with self._lock:
            self._prediction_seq += 1
            now_iso = _utc_now_iso()
            row = {
                "id": self._prediction_seq,
                "symbol": str(data.get("symbol", "")).upper().strip(),
                "horizon": str(data.get("horizon", "intraday")),
                "direction": str(data.get("direction", "NEUTRAL")),
                "conviction": int(data.get("conviction", 0)),
                "regime": str(data.get("regime", "ranging")),
                "sniper_grade": str(data.get("sniper_grade", "WAIT")),
                "entry_price": float(data.get("entry_price", 0.0)),
                "stop_loss": float(data.get("stop_loss", 0.0)),
                "tp1": float(data.get("tp1", 0.0)),
                "tp2": float(data.get("tp2", 0.0)),
                "factor_scores": copy.deepcopy(data.get("factor_scores") or {}),
                "outcome": str(data.get("outcome") or "PENDING"),
                "outcome_price": data.get("outcome_price"),
                "r_multiple": data.get("r_multiple"),
                "created_at": self._to_iso(data.get("created_at"), now_iso),
                "expires_at": self._to_iso(data.get("expires_at"), now_iso),
                "evaluated_at": self._to_iso(data.get("evaluated_at"), "") if data.get("evaluated_at") else None,
                "is_shadow": bool(data.get("is_shadow", False)),
                "veto_reason": data.get("veto_reason"),
            }
            self._predictions[row["id"]] = row
            return copy.deepcopy(row)

    def get_pending_predictions(self, limit: int = 200) -> list[dict[str, Any]]:
        epoch_min = datetime.min.replace(tzinfo=timezone.utc)
        with self._lock:
            pending = [r for r in self._predictions.values() if r.get("outcome") == "PENDING"]
            pending.sort(key=lambda r: (self._parse_utc_dt(r.get("expires_at")) or epoch_min, r["id"]))
            return [copy.deepcopy(r) for r in pending[:limit]]

    def update_signal_prediction_outcome(
        self,
        pred_id: int,
        outcome: str,
        outcome_price: float,
        r_multiple: float,
    ) -> dict[str, Any] | None:
        with self._lock:
            row = self._predictions.get(int(pred_id))
            if not row:
                return None
            row["outcome"] = outcome
            row["outcome_price"] = float(outcome_price)
            row["r_multiple"] = float(r_multiple)
            row["evaluated_at"] = _utc_now_iso()
            return copy.deepcopy(row)

    def get_recent_prediction(
        self,
        symbol: str,
        horizon: str,
        direction: str,
        cooldown_hours: int,
        is_shadow: bool = False,
        veto_reason: str | None = None,
    ) -> dict[str, Any] | None:
        sym = symbol.upper().strip()
        now_dt = datetime.now(timezone.utc)
        with self._lock:
            candidates = [
                r for r in self._predictions.values()
                if r.get("symbol") == sym and r.get("horizon") == horizon
            ]
            if not is_shadow:
                candidates = [r for r in candidates if not r.get("is_shadow")]
            else:
                candidates = [
                    r for r in candidates
                    if r.get("is_shadow") and r.get("veto_reason") == veto_reason
                ]
            candidates.sort(key=lambda r: r["id"], reverse=True)
            for r in candidates:
                if r.get("outcome") == "PENDING":
                    return copy.deepcopy(r)
                if r.get("direction") == direction:
                    c_dt = self._parse_utc_dt(r.get("created_at"))
                    if c_dt is not None and (now_dt - c_dt).total_seconds() < cooldown_hours * 3600:
                        return copy.deepcopy(r)
            return None

    def get_accuracy_summary(self, days: int = 30, symbol: str | None = None) -> dict[str, Any]:
        sym_filter = symbol.upper().strip() if symbol else None
        now_dt = datetime.now(timezone.utc)
        cutoff_sec = max(1, int(days)) * 86400
        with self._lock:
            rows = []
            for r in self._predictions.values():
                if sym_filter and r.get("symbol") != sym_filter:
                    continue
                c_dt = self._parse_utc_dt(r.get("created_at"))
                if c_dt is None or (now_dt - c_dt).total_seconds() > cutoff_sec:
                    continue
                rows.append(copy.deepcopy(r))
        return compute_accuracy_summary_from_rows(rows, days=days)

    # ── Hyperliquid Whale Wallets ─────────────────────────────────────────────
    def upsert_hl_wallet(self, wallet: dict[str, Any]) -> dict[str, Any]:
        with self._lock:
            addr = str(wallet.get("address", "")).lower()
            if not addr:
                return {}
            existing = self._hl_wallets.get(addr, {})
            merged = {
                "address": addr,
                "label": wallet.get("label") or existing.get("label"),
                "account_value_usd": float(wallet.get("account_value_usd", existing.get("account_value_usd", 0.0)) or 0.0),
                "total_notional_usd": float(wallet.get("total_notional_usd", existing.get("total_notional_usd", 0.0)) or 0.0),
                "cumulative_pnl_usd": float(wallet.get("cumulative_pnl_usd", existing.get("cumulative_pnl_usd", 0.0)) or 0.0),
                "win_count": int(wallet.get("win_count", existing.get("win_count", 0)) or 0),
                "loss_count": int(wallet.get("loss_count", existing.get("loss_count", 0)) or 0),
                "reliability_score": float(wallet.get("reliability_score", existing.get("reliability_score", 1.0)) or 1.0),
                "tier": wallet.get("tier", existing.get("tier", "UNPROVEN")),
                "positions_json": copy.deepcopy(wallet.get("positions_json", existing.get("positions_json", {}))),
                "recent_events_json": copy.deepcopy(wallet.get("recent_events_json", existing.get("recent_events_json", []))),
                "updated_at": _utc_now_iso(),
            }
            self._hl_wallets[addr] = merged
            return copy.deepcopy(merged)

    def get_hl_wallets(self, limit: int = 100) -> list[dict[str, Any]]:
        with self._lock:
            rows = list(self._hl_wallets.values())
            rows.sort(key=lambda w: (float(w.get("reliability_score", 1.0) or 1.0), float(w.get("account_value_usd", 0.0) or 0.0)), reverse=True)
            return [copy.deepcopy(r) for r in rows[:limit]]

    def get_hl_wallet(self, address: str) -> dict[str, Any] | None:
        with self._lock:
            row = self._hl_wallets.get(str(address).lower())
            return copy.deepcopy(row) if row else None

    # ── Microstructure Tape ───────────────────────────────────────────────────
    def insert_microstructure_tape(self, tape_row: dict[str, Any]) -> dict[str, Any]:
        with self._lock:
            self._tape_seq += 1
            now = _utc_now_iso()
            row = {
                "id": self._tape_seq,
                "symbol": str(tape_row.get("symbol", "")).upper(),
                "recorded_at": tape_row.get("recorded_at") or now,
                "timestamp_ms": int(tape_row.get("timestamp_ms") or int(datetime.now(timezone.utc).timestamp() * 1000)),
                "mark_price": float(tape_row.get("mark_price", 0.0) or 0.0),
                "adv_24h_usd": float(tape_row.get("adv_24h_usd", 0.0) or 0.0),
                "horizon_scores": copy.deepcopy(tape_row.get("horizon_scores", {})),
                "factor_scores": copy.deepcopy(tape_row.get("factor_scores", {})),
                "whale_sub_metrics": copy.deepcopy(tape_row.get("whale_sub_metrics", {})),
                "raw_replay_slice": copy.deepcopy(tape_row.get("raw_replay_slice", {})),
                "ret_15m_pct": tape_row.get("ret_15m_pct"),
                "ret_1h_pct": tape_row.get("ret_1h_pct"),
                "ret_4h_pct": tape_row.get("ret_4h_pct"),
                "evaluated_at": tape_row.get("evaluated_at"),
            }
            self._microstructure_tape.append(row)
            return copy.deepcopy(row)

    def get_microstructure_tape(self, symbol: str | None = None, limit: int = 500, days: int = 14) -> list[dict[str, Any]]:
        now_dt = datetime.now(timezone.utc)
        cutoff_sec = max(1, int(days)) * 86400
        sym_filter = symbol.upper() if symbol else None
        with self._lock:
            matched = []
            for r in reversed(self._microstructure_tape):
                if sym_filter and r.get("symbol") != sym_filter:
                    continue
                c_dt = self._parse_utc_dt(r.get("recorded_at"))
                if c_dt is not None and (now_dt - c_dt).total_seconds() > cutoff_sec:
                    continue
                matched.append(copy.deepcopy(r))
                if len(matched) >= limit:
                    break
            return matched

    def get_unevaluated_microstructure_tape(self, limit: int = 200) -> list[dict[str, Any]]:
        with self._lock:
            res = [
                copy.deepcopy(r)
                for r in self._microstructure_tape
                if r.get("ret_4h_pct") is None or r.get("evaluated_at") is None
            ]
            return res[:limit]

    def update_microstructure_tape_returns(
        self,
        tape_id: int,
        ret_15m: float | None,
        ret_1h: float | None,
        ret_4h: float | None,
    ) -> bool:
        with self._lock:
            for r in self._microstructure_tape:
                if r.get("id") == tape_id:
                    if ret_15m is not None:
                        r["ret_15m_pct"] = ret_15m
                    if ret_1h is not None:
                        r["ret_1h_pct"] = ret_1h
                    if ret_4h is not None:
                        r["ret_4h_pct"] = ret_4h
                    r["evaluated_at"] = _utc_now_iso()
                    return True
            return False

    def prune_old_records(
        self,
        retention_hours_snapshots: int = 2,
        retention_days_signals: int = 2,
        retention_days_predictions: int = 30,
        retention_days_tape: int = 14,
    ) -> dict[str, int]:
        now_dt = datetime.now(timezone.utc)
        snap_sec = max(1, int(retention_hours_snapshots)) * 3600
        sig_sec = max(1, int(retention_days_signals)) * 86400
        pred_sec = max(1, int(retention_days_predictions)) * 86400
        tape_sec = max(1, int(retention_days_tape)) * 86400
        pruned = {"snapshots": 0, "signals": 0, "predictions": 0, "microstructure_tape": 0}
        with self._lock:
            for sym in list(self._snapshots.keys()):
                ex_map = self._snapshots[sym]
                for ex in list(ex_map.keys()):
                    dt = self._parse_utc_dt(ex_map[ex].get("snapshot_at"))
                    if dt is not None and (now_dt - dt).total_seconds() > snap_sec:
                        del ex_map[ex]
                        pruned["snapshots"] += 1
                if not ex_map:
                    del self._snapshots[sym]

            for sym in list(self._signals.keys()):
                orig = self._signals[sym]
                kept = []
                for s in orig:
                    dt = self._parse_utc_dt(s.get("created_at"))
                    if dt is not None and (now_dt - dt).total_seconds() > sig_sec:
                        pruned["signals"] += 1
                    else:
                        kept.append(s)
                self._signals[sym] = kept

            for pid in list(self._predictions.keys()):
                pred = self._predictions[pid]
                if pred.get("outcome") != "PENDING":
                    dt = self._parse_utc_dt(pred.get("created_at"))
                    if dt is not None and (now_dt - dt).total_seconds() > pred_sec:
                        del self._predictions[pid]
                        pruned["predictions"] += 1

            kept_tape = []
            for r in self._microstructure_tape:
                dt = self._parse_utc_dt(r.get("recorded_at"))
                if dt is not None and (now_dt - dt).total_seconds() > tape_sec:
                    pruned["microstructure_tape"] += 1
                else:
                    kept_tape.append(r)
            self._microstructure_tape = kept_tape

            pruned_wallets = 0
            for addr in list(self._hl_wallets.keys()):
                w = self._hl_wallets[addr]
                if w.get("tier") != "SMART_WHALE":
                    dt = self._parse_utc_dt(w.get("updated_at"))
                    if dt is not None and (now_dt - dt).total_seconds() > tape_sec:
                        del self._hl_wallets[addr]
                        pruned_wallets += 1
            if len(self._hl_wallets) > 250:
                ordered = sorted(
                    self._hl_wallets.values(),
                    key=lambda x: (
                        1 if x.get("tier") == "SMART_WHALE" else 0,
                        float(x.get("reliability_score", 0.0) or 0.0),
                        float(x.get("account_value_usd", 0.0) or 0.0),
                    ),
                    reverse=True,
                )
                keep_addrs = {str(x.get("address", "")).lower() for x in ordered[:250]}
                for addr in list(self._hl_wallets.keys()):
                    if addr not in keep_addrs:
                        del self._hl_wallets[addr]
                        pruned_wallets += 1
            pruned["hl_whale_wallets"] = pruned_wallets
        return pruned


def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 30) -> dict[str, Any]:
    """Compute unified accuracy summary from signal_predictions rows (shared by DB and memory_store)."""
    # Exclude all is_shadow=True rows from primary metrics
    live_rows = [r for r in rows if not r.get("is_shadow")]
    shadow_rows = [r for r in rows if bool(r.get("is_shadow"))]

    pending_count = sum(1 for r in live_rows if r.get("outcome") == "PENDING")
    eval_rows = [r for r in live_rows if r.get("outcome") and r.get("outcome") != "PENDING" and r.get("r_multiple") is not None]
    total_evaluated = len(eval_rows)
    expired_count = sum(1 for r in eval_rows if r.get("outcome") == "EXPIRED")

    def _stats(subset: list[dict[str, Any]]) -> dict[str, Any]:
        n = len(subset)
        if n == 0:
            return {"total": 0, "win_rate_pct": 0.0, "avg_r": 0.0}
        wins = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) > 0.0)
        avg_r = sum(float(r.get("r_multiple") or 0.0) for r in subset) / n
        return {
            "total": n,
            "win_rate_pct": round((wins / n) * 100.0, 1),
            "avg_r": round(avg_r, 3),
        }

    overall = _stats(eval_rows)
    non_expired = [r for r in eval_rows if r.get("outcome") != "EXPIRED"]
    tp_hits = sum(1 for r in non_expired if r.get("outcome") in ("TP1_OPEN", "TP1_BREAKEVEN", "TP2"))
    tp_hit_rate_pct = round((tp_hits / len(non_expired)) * 100.0, 1) if non_expired else 0.0

    intraday_rows = [r for r in eval_rows if r.get("horizon") == "intraday"]
    swing_rows = [r for r in eval_rows if r.get("horizon") == "swing"]
    sniper_rows = [r for r in eval_rows if r.get("sniper_grade") == "SNIPER_A_PLUS"]
    non_sniper_rows = [r for r in eval_rows if r.get("sniper_grade") != "SNIPER_A_PLUS"]

    factor_buckets: dict[str, dict[str, list[float]]] = {}
    for r in eval_rows:
        dir_sign = 1 if r.get("direction") == "LONG" else (-1 if r.get("direction") == "SHORT" else 0)
        if dir_sign == 0:
            continue
        r_mult = float(r.get("r_multiple") or 0.0)
        f_scores = r.get("factor_scores") or {}
        if isinstance(f_scores, str):
            import json
            try:
                f_scores = json.loads(f_scores)
            except Exception:
                f_scores = {}
        if not isinstance(f_scores, dict):
            continue
        for f_name, raw_val in f_scores.items():
            raw_score = raw_val.get("score", 0) if isinstance(raw_val, dict) else raw_val
            try:
                score = int(float(raw_score)) if raw_score is not None else 0
            except (TypeError, ValueError):
                score = 0
            if score == 0:
                continue
            b = factor_buckets.setdefault(f_name, {"aligned": [], "opposing": []})
            if score * dir_sign > 0:
                b["aligned"].append(r_mult)
            elif score * dir_sign < 0:
                b["opposing"].append(r_mult)

    by_factor: dict[str, dict[str, Any]] = {}
    for f_name, b in factor_buckets.items():
        al = b["aligned"]
        op = b["opposing"]
        al_n = len(al)
        op_n = len(op)
        al_wr = round((sum(1 for x in al if x > 0.0) / al_n) * 100.0, 1) if al_n > 0 else 0.0
        al_avg = round(sum(al) / al_n, 3) if al_n > 0 else 0.0
        op_wr = round((sum(1 for x in op if x > 0.0) / op_n) * 100.0, 1) if op_n > 0 else 0.0
        op_avg = round(sum(op) / op_n, 3) if op_n > 0 else 0.0
        by_factor[f_name] = {
            "aligned_trades": al_n,
            "aligned_win_rate_pct": al_wr,
            "aligned_avg_r": al_avg,
            "opposing_trades": op_n,
            "opposing_win_rate_pct": op_wr,
            "opposing_avg_r": op_avg,
        }

    # Isolated veto_effectiveness grouped by veto_reason
    shadow_eval_rows = [
        r for r in shadow_rows
        if r.get("outcome") and r.get("outcome") != "PENDING" and r.get("r_multiple") is not None
    ]
    veto_groups: dict[str, list[dict[str, Any]]] = {}
    for r in shadow_eval_rows:
        vr = str(r.get("veto_reason") or "UNKNOWN")
        veto_groups.setdefault(vr, []).append(r)

    veto_effectiveness: dict[str, dict[str, Any]] = {}
    for vr, subset in sorted(veto_groups.items()):
        n = len(subset)
        wins = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) > 0.0)
        losses = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) < 0.0)
        avg_r = sum(float(r.get("r_multiple") or 0.0) for r in subset) / n if n > 0 else 0.0
        veto_effectiveness[vr] = {
            "total": n,
            "would_have_won_pct": round((wins / n) * 100.0, 1) if n > 0 else 0.0,
            "avg_shadow_r": round(avg_r, 3),
            "saved_loss_rate_pct": round((losses / n) * 100.0, 1) if n > 0 else 0.0,
        }

    return {
        "window_days": int(days),
        "total_evaluated": total_evaluated,
        "pending_count": pending_count,
        "expired_count": expired_count,
        "win_rate_pct": overall["win_rate_pct"],
        "tp_hit_rate_pct": tp_hit_rate_pct,
        "avg_r_multiple": overall["avg_r"],
        "by_horizon": {
            "intraday": _stats(intraday_rows),
            "swing": _stats(swing_rows),
        },
        "sniper_a_plus": _stats(sniper_rows),
        "non_sniper": _stats(non_sniper_rows),
        "by_factor": by_factor,
        "veto_effectiveness": veto_effectiveness,
    }


memory_store = InMemoryDatabaseStore()