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
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""Dashboard stats service with in-memory read cache and async Supabase writes.

Architecture:
    - log_lookup() appends to memory instantly + fires a background Supabase INSERT
    - Dashboard reads (get_stats, get_trend, etc.) serve from in-memory cache (~0ms)
    - On startup, hydrates last 30 days from Supabase into memory
    - Failed Supabase writes are retried with exponential backoff
    - Zero data loss on container restart (every record hits Supabase immediately)
"""

import logging
import threading
import time
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone

from src.config.supabase import get_supabase_client

logger = logging.getLogger(__name__)


class StatsService:
    """Service for dashboard statistics with in-memory cache and async persistence."""

    TABLE_NAME = "ioc_stats"
    MAX_RECORDS = 10_000       # In-memory cap (~5MB)
    HYDRATION_DAYS = 30        # Days to load from Supabase on startup
    RETRY_INTERVAL = 5         # Base retry interval (seconds)
    MAX_BACKOFF = 300           # Max retry interval (5 minutes)

    HYDRATION_RETRIES = 5          # Max hydration retry attempts
    HYDRATION_RETRY_BASE = 2       # Base delay for hydration retry (seconds)
    HYDRATION_BG_INTERVAL = 30     # Background hydration retry interval (seconds)

    def __init__(self):
        self._lock = threading.Lock()
        self._records: list[dict] = []       # All in-memory records (for reads)
        self._failed_queue: list[dict] = []  # Records that failed Supabase write
        self._supabase = get_supabase_client()
        self._current_backoff = self.RETRY_INTERVAL
        self._hydrated = False               # Track if hydration succeeded

        # Thread pool for fire-and-forget Supabase writes
        self._write_pool = ThreadPoolExecutor(
            max_workers=2,
            thread_name_prefix="supabase-write",
        )

        # Hydrate from Supabase on startup (with retries)
        self._hydrate_with_retry()

        # Start retry thread for failed writes
        self._retry_thread = threading.Thread(
            target=self._retry_loop,
            daemon=True,
            name="supabase-retry",
        )
        self._retry_thread.start()

        # If hydration failed, start background thread to keep trying
        if not self._hydrated:
            self._hydration_thread = threading.Thread(
                target=self._background_hydration_loop,
                daemon=True,
                name="supabase-hydration",
            )
            self._hydration_thread.start()

        logger.info(
            f"StatsService initialized: {len(self._records)} records hydrated, "
            f"supabase={'connected' if self._supabase else 'unavailable'}"
        )

    @property
    def enabled(self) -> bool:
        """Always enabled β€” in-memory is the primary store."""
        return True

    # ─── Write Path ────────────────────────────────────────────────

    def log_lookup(
        self,
        ioc_value: str,
        ioc_type: str,
        verdict: str | None = None,
        country_code: str | None = None,
    ) -> bool:
        """
        Log an IOC lookup.

        1. SYNC: Append to in-memory list (instant, for dashboard reads)
        2. ASYNC: Fire-and-forget INSERT to Supabase (non-blocking)

        Returns:
            True (always succeeds β€” memory write can't fail)
        """
        record = {
            "ioc_value": ioc_value[:255],
            "ioc_type": ioc_type.lower(),
            "verdict": (verdict or "unknown").lower(),
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
        if country_code:
            record["country_code"] = country_code.upper()[:2]

        # 1. SYNC: Store in memory (instant)
        with self._lock:
            self._records.append(record)
            if len(self._records) > self.MAX_RECORDS:
                self._records = self._records[-self.MAX_RECORDS:]

        # 2. ASYNC: Fire-and-forget write to Supabase
        self._write_pool.submit(self._write_to_supabase, record)

        logger.debug(f"Logged lookup: {ioc_type}/{verdict}")
        return True

    def _write_to_supabase(self, record: dict) -> None:
        """Background thread: write a single record to Supabase."""
        if not self._supabase:
            # Queue for retry when Supabase becomes available
            with self._lock:
                self._failed_queue.append(record)
            return

        try:
            # Build clean insert data (exclude None values)
            data = {k: v for k, v in record.items() if v is not None}
            self._supabase.table(self.TABLE_NAME).insert(data).execute()
        except Exception as e:
            logger.warning(f"Supabase write failed, queued for retry: {e}")
            with self._lock:
                self._failed_queue.append(record)

    # ─── Retry Loop ────────────────────────────────────────────────

    def _retry_loop(self) -> None:
        """Daemon thread: retries failed Supabase writes with exponential backoff."""
        while True:
            time.sleep(self._current_backoff)

            # Atomically grab the failed queue
            with self._lock:
                if not self._failed_queue:
                    # Nothing to retry β€” reset backoff
                    self._current_backoff = self.RETRY_INTERVAL
                    continue
                batch = self._failed_queue.copy()
                self._failed_queue.clear()

            if not self._supabase:
                # Supabase still not available β€” put records back
                with self._lock:
                    self._failed_queue.extend(batch)
                self._current_backoff = min(
                    self._current_backoff * 2, self.MAX_BACKOFF
                )
                logger.debug(
                    f"Supabase unavailable, {len(batch)} records pending, "
                    f"retry in {self._current_backoff}s"
                )
                continue

            # Try batch insert
            try:
                clean_batch = [
                    {k: v for k, v in r.items() if v is not None}
                    for r in batch
                ]
                self._supabase.table(self.TABLE_NAME).insert(clean_batch).execute()
                self._current_backoff = self.RETRY_INTERVAL
                logger.info(f"Retry flush: {len(batch)} records written to Supabase")
            except Exception as e:
                logger.warning(
                    f"Retry flush failed ({len(batch)} records), "
                    f"next retry in {self._current_backoff}s: {e}"
                )
                # Put records back for next attempt
                with self._lock:
                    self._failed_queue.extend(batch)
                self._current_backoff = min(
                    self._current_backoff * 2, self.MAX_BACKOFF
                )

    # ─── Read Path (all from memory) ──────────────────────────────

    def get_stats(self, days: int = 7) -> dict:
        """Get aggregated statistics from in-memory cache."""
        days = max(1, min(365, days))
        since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
        today_start = datetime.now(timezone.utc).replace(
            hour=0, minute=0, second=0, microsecond=0
        ).isoformat()

        with self._lock:
            filtered = [r for r in self._records if r["created_at"] >= since]

        total = len(filtered)
        by_type: dict[str, int] = {}
        by_verdict: dict[str, int] = {}
        threats = 0
        today_count = 0

        for r in filtered:
            ioc_type = r.get("ioc_type", "unknown")
            verdict = r.get("verdict", "unknown")

            by_type[ioc_type] = by_type.get(ioc_type, 0) + 1
            by_verdict[verdict] = by_verdict.get(verdict, 0) + 1

            if verdict in ("malicious", "suspicious"):
                threats += 1

            if r["created_at"] >= today_start:
                today_count += 1

        threat_rate = round((threats / total * 100), 1) if total > 0 else 0

        return {
            "total": total,
            "today": today_count,
            "threats": threats,
            "threat_rate": threat_rate,
            "by_type": by_type,
            "by_verdict": by_verdict,
        }

    def get_trend(self, days: int = 7) -> list[dict]:
        """Get daily trend data from in-memory cache."""
        days = max(1, min(365, days))
        since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()

        with self._lock:
            filtered = [r for r in self._records if r["created_at"] >= since]

        # Group by day
        daily: dict[str, dict] = {}
        for r in filtered:
            date_key = r["created_at"][:10]  # YYYY-MM-DD
            verdict = r.get("verdict", "unknown")

            if date_key not in daily:
                daily[date_key] = {"date": date_key, "total": 0, "threats": 0}

            daily[date_key]["total"] += 1
            if verdict in ("malicious", "suspicious"):
                daily[date_key]["threats"] += 1

        # Return sorted by date
        return sorted(daily.values(), key=lambda x: x["date"])

    def get_recent(self, limit: int = 20) -> list[dict]:
        """Get recent IOC lookups from in-memory cache."""
        limit = max(1, min(100, limit))

        with self._lock:
            # Return most recent N, newest first
            recent = self._records[-limit:]

        # Return in reverse chronological order
        return [
            {
                "ioc_value": r["ioc_value"],
                "ioc_type": r["ioc_type"],
                "verdict": r["verdict"],
                "created_at": r["created_at"],
            }
            for r in reversed(recent)
        ]

    def get_top_iocs(self, limit: int = 10, days: int = 30) -> list[dict]:
        """Get most frequently searched IOCs from in-memory cache."""
        limit = max(1, min(50, limit))
        since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()

        with self._lock:
            filtered = [r for r in self._records if r["created_at"] >= since]

        # Count occurrences
        counter: Counter[str] = Counter()
        type_map: dict[str, str] = {}

        for r in filtered:
            key = f"{r['ioc_type']}:{r['ioc_value']}"
            counter[key] += 1
            type_map[key] = r["ioc_type"]

        # Build sorted result
        result = []
        for key, count in counter.most_common(limit):
            ioc_type, ioc_value = key.split(":", 1)
            result.append({
                "ioc_value": ioc_value,
                "ioc_type": ioc_type,
                "count": count,
            })

        return result

    def get_geo_stats(self, days: int = 30) -> list[dict]:
        """Get geographic distribution from in-memory cache."""
        since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()

        with self._lock:
            filtered = [
                r for r in self._records
                if r["created_at"] >= since and r.get("country_code")
            ]

        counter: Counter[str] = Counter()
        for r in filtered:
            counter[r["country_code"]] += 1

        return [
            {"country": cc, "count": count}
            for cc, count in counter.most_common()
        ]

    # ─── Startup Hydration ─────────────────────────────────────────

    def _hydrate_with_retry(self) -> None:
        """Attempt hydration with retries using exponential backoff."""
        for attempt in range(1, self.HYDRATION_RETRIES + 1):
            if self._hydrate():
                return  # Success
            if attempt < self.HYDRATION_RETRIES:
                delay = self.HYDRATION_RETRY_BASE ** attempt
                logger.warning(
                    f"Hydration attempt {attempt}/{self.HYDRATION_RETRIES} failed, "
                    f"retrying in {delay}s..."
                )
                time.sleep(delay)

        logger.warning(
            f"All {self.HYDRATION_RETRIES} hydration attempts failed β€” "
            f"will keep retrying in background every {self.HYDRATION_BG_INTERVAL}s"
        )

    def _background_hydration_loop(self) -> None:
        """Daemon thread: keeps retrying hydration until it succeeds."""
        while not self._hydrated:
            time.sleep(self.HYDRATION_BG_INTERVAL)
            logger.info("Background hydration: retrying Supabase connection...")

            # Re-initialize the Supabase client in case the issue was transient
            get_supabase_client.cache_clear()
            self._supabase = get_supabase_client()

            if self._hydrate():
                logger.info(
                    f"Background hydration succeeded! "
                    f"{len(self._records)} records loaded."
                )
                return

    def _hydrate(self) -> bool:
        """Load historical data from Supabase into memory.

        Paginates in batches of 1,000 (Supabase PostgREST row limit)
        to ensure ALL records within the hydration window are loaded.

        Returns:
            True if hydration succeeded, False otherwise.
        """
        if not self._supabase:
            # Re-initialize in case env vars are now available
            get_supabase_client.cache_clear()
            self._supabase = get_supabase_client()

        if not self._supabase:
            logger.warning("Supabase unavailable β€” cannot hydrate")
            return False

        try:
            since = (
                datetime.now(timezone.utc) - timedelta(days=self.HYDRATION_DAYS)
            ).isoformat()

            all_records: list[dict] = []
            page_size = 1000  # Supabase PostgREST max per request
            offset = 0

            while len(all_records) < self.MAX_RECORDS:
                response = (
                    self._supabase.table(self.TABLE_NAME)
                    .select("ioc_value, ioc_type, verdict, country_code, created_at")
                    .gte("created_at", since)
                    .order("created_at")
                    .range(offset, offset + page_size - 1)
                    .execute()
                )

                batch = response.data or []
                if not batch:
                    break  # No more records

                all_records.extend(batch)
                offset += page_size

                if len(batch) < page_size:
                    break  # Last page

            # Trim to MAX_RECORDS if needed
            all_records = all_records[:self.MAX_RECORDS]

            with self._lock:
                self._records = [
                    {
                        "ioc_value": r.get("ioc_value", ""),
                        "ioc_type": r.get("ioc_type", "unknown"),
                        "verdict": r.get("verdict", "unknown"),
                        "country_code": r.get("country_code"),
                        "created_at": r.get("created_at", ""),
                    }
                    for r in all_records
                ]

            self._hydrated = True
            logger.info(f"Hydrated {len(all_records)} records from Supabase ({offset // page_size + (1 if offset % page_size else 0)} pages)")
            return True

        except Exception as e:
            logger.warning(f"Supabase hydration failed β€” starting empty: {e}")
            return False

    # ─── Status / Diagnostics ──────────────────────────────────────

    def get_status(self) -> dict:
        """Get service status for diagnostics."""
        with self._lock:
            return {
                "records_in_memory": len(self._records),
                "pending_retries": len(self._failed_queue),
                "supabase_connected": self._supabase is not None,
                "hydrated": self._hydrated,
                "retry_backoff_seconds": self._current_backoff,
            }


# Global service instance
stats_service = StatsService()