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
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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
"""
app.py β€” Single entry point for HuggingFace Spaces.

Run with:
  uv run python app.py          ← HuggingFace Spaces / production
  uv run uvicorn app:app --reload  ← local dev

Lifecycle on startup:
  1. Configures structured logging
  2. Waits for Redis / Qdrant / Memgraph to be healthy (skipped in DEMO_MODE)
  3. Initialises Qdrant collection + Memgraph schema
  4. Seeds demo evidence chunks into Qdrant
  5. Warms up BGE-M3 embedder in the background
  6. Serves FastAPI on port 7860 (HuggingFace default)

WebSocket message lifecycle (per text segment):
  1. Extension sends TextBatch  β†’  Redis cache check (xxhash key)
  2. Cache miss  β†’  Gatekeeper (Groq llama3-8b, <120 ms p95)
  3. Noise  β†’  dropped.  Fact  β†’  continue
  4. Concurrent: RAG pipeline (BGE-M3 + Qdrant + Memgraph) + Grok sensor
  5. Prefect flow: misinformation agent + hallucination agent (both Groq, free)
  6. AnalysisResult cached in Redis (TTL: 6 h green/red, 15 min yellow, no-cache purple)
  7. Result streamed back over WebSocket β†’ extension applies DOM highlight + hover card
"""

import asyncio
import os
import sys
import time
from contextlib import asynccontextmanager
from typing import Any

import orjson
import redis.asyncio as aioredis
import structlog
import xxhash
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from pydantic import ValidationError

# ---------------------------------------------------------------------------
# Bootstrap logging FIRST so every subsequent import logs correctly
# ---------------------------------------------------------------------------
from core.logging import configure_logging
from core.config import HighlightColor, Platform, get_settings

settings = get_settings()
configure_logging(
    log_level=settings.log_level,
    json_output=os.environ.get("JSON_LOGS", "false").lower() == "true",
)
log = structlog.get_logger("app")

# ---------------------------------------------------------------------------
# Remaining imports (after logging is configured)
# ---------------------------------------------------------------------------
from agents import evaluate_claim
from core.models import AnalysisResult, GatekeeperResult, TextBatch, WSInbound, WSOutbound
from gatekeeper import classify_claim
from grok_sensor import query_grok_sensor
from rag_pipeline import run_rag_pipeline

# ============================================================================
# SECTION 1 β€” Infrastructure health checks (used during startup)
# ============================================================================

async def _wait_for_redis(url: str, timeout: int = 30) -> bool:
    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            r = await aioredis.from_url(url, decode_responses=True)
            await r.ping()
            await r.aclose()
            return True
        except Exception:
            await asyncio.sleep(1)
    return False


async def _wait_for_qdrant(host: str, port: int, timeout: int = 30) -> bool:
    import httpx
    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            async with httpx.AsyncClient(timeout=2.0) as client:
                resp = await client.get(f"http://{host}:{port}/readyz")
                if resp.status_code == 200:
                    return True
        except Exception:
            await asyncio.sleep(1)
    return False


async def _wait_for_memgraph(host: str, port: int, timeout: int = 30) -> bool:
    from neo4j import AsyncGraphDatabase
    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            driver = AsyncGraphDatabase.driver(
                f"bolt://{host}:{port}",
                auth=("", settings.memgraph_password),
                encrypted=False,
            )
            async with driver.session() as session:
                await session.run("RETURN 1;")
            await driver.close()
            return True
        except Exception:
            await asyncio.sleep(2)
    return False


# ============================================================================
# SECTION 2 β€” Demo data seeding (populates Qdrant for the HF Spaces demo UI)
# ============================================================================

_DEMO_EVIDENCE = [
    {
        "text": "mRNA vaccines demonstrated sustained immune responses lasting 18-24 months across multiple peer-reviewed studies.",
        "url": "https://www.nejm.org/doi/10.1056/NEJMoa2034577",
        "domain": "nejm.org",
    },
    {
        "text": "The Federal Reserve raised interest rates by 75 basis points in June 2022, the largest single hike since 1994.",
        "url": "https://reuters.com/markets/us/fed-hikes-rates-2022-06-15",
        "domain": "reuters.com",
    },
    {
        "text": "Amazon deforestation data showed over 11,000 sq km lost in a single year at record levels.",
        "url": "https://apnews.com/article/amazon-deforestation-record",
        "domain": "apnews.com",
    },
    {
        "text": "The United Nations projects global population will peak around 10.4 billion in the 2080s based on current demographic trends.",
        "url": "https://www.un.org/development/desa/pd/",
        "domain": "un.org",
    },
    {
        "text": "Renewable energy accounted for 30% of global electricity generation in 2023 according to the International Energy Agency.",
        "url": "https://www.iea.org/reports/renewables-2023",
        "domain": "iea.org",
    },
    {
        "text": "Social media use exceeding 3 hours daily correlates with higher anxiety rates in adolescents per multiple longitudinal studies.",
        "url": "https://jamanetwork.com/journals/jamapediatrics/fullarticle/2767581",
        "domain": "jamanetwork.com",
    },
]


async def _seed_demo_data() -> None:
    """Upsert demo evidence chunks into Qdrant so the demo UI returns real RAG results."""
    import uuid
    from qdrant_client.models import PointStruct
    from rag_pipeline import embed_texts, get_qdrant

    log.info("demo.seed.start", count=len(_DEMO_EVIDENCE))
    client = await get_qdrant(settings)
    texts = [e["text"] for e in _DEMO_EVIDENCE]
    vectors = await embed_texts(texts)

    points = [
        PointStruct(
            id=str(uuid.uuid4()),
            vector=vec,
            payload={
                "text": ev["text"],
                "source_url": ev["url"],
                "domain": ev["domain"],
                "platform": "news",
                "content_hash": f"demo_{i:04d}",
                "ingested_at_ts": time.time(),
                "author_handle": "demo_seed",
                "bias_rating": "center",
            },
        )
        for i, (ev, vec) in enumerate(zip(_DEMO_EVIDENCE, vectors))
    ]
    await client.upsert(collection_name=settings.qdrant_collection, points=points)
    log.info("demo.seed.complete", count=len(points))


# ============================================================================
# SECTION 3 β€” Redis singleton
# ============================================================================

_redis: aioredis.Redis | None = None


async def get_redis() -> aioredis.Redis:
    global _redis
    if _redis is None:
        _redis = await aioredis.from_url(settings.redis_url, decode_responses=True)
    return _redis


# ============================================================================
# SECTION 4 β€” WebSocket connection manager
# ============================================================================

class ConnectionManager:
    def __init__(self) -> None:
        self.active: dict[str, WebSocket] = {}

    async def connect(self, session_id: str, ws: WebSocket) -> None:
        await ws.accept()
        self.active[session_id] = ws
        log.info("ws.connected", session_id=session_id, total=len(self.active))

    def disconnect(self, session_id: str) -> None:
        self.active.pop(session_id, None)
        log.info("ws.disconnected", session_id=session_id, total=len(self.active))

    async def send(self, session_id: str, payload: Any) -> None:
        ws = self.active.get(session_id)
        if ws:
            msg = WSOutbound(type="result", payload=payload)
            await ws.send_bytes(orjson.dumps(msg.model_dump(mode="json")))


manager = ConnectionManager()


# ============================================================================
# SECTION 5 β€” FastAPI lifespan (startup + shutdown)
# ============================================================================

@asynccontextmanager
async def lifespan(app: FastAPI):
    log.info("startup.begin", demo_mode=settings.demo_mode, port=settings.port)

    if not settings.demo_mode:
        # Wait for all infrastructure services
        log.info("startup.waiting_for_services")

        if not await _wait_for_redis(settings.redis_url):
            log.error("startup.redis.timeout"); sys.exit(1)
        log.info("startup.redis.ok")

        if not await _wait_for_qdrant(settings.qdrant_host, settings.qdrant_port):
            log.error("startup.qdrant.timeout"); sys.exit(1)
        log.info("startup.qdrant.ok")

        if not await _wait_for_memgraph(settings.memgraph_host, settings.memgraph_port):
            log.warning("startup.memgraph.timeout β€” trust scores will use neutral 0.5 fallback")
        else:
            log.info("startup.memgraph.ok")

        # Initialise DB schemas (idempotent)
        from core.db_init import init_all
        await init_all(settings)

        # Seed demo evidence into Qdrant
        try:
            await _seed_demo_data()
        except Exception as exc:
            log.warning("startup.seed.failed", error=str(exc))
    else:
        # Demo mode: just make sure Redis is reachable (may be local or absent)
        try:
            r = await get_redis()
            await r.ping()
            log.info("startup.redis.ok")
        except Exception:
            log.warning("startup.redis.unavailable β€” cache disabled in demo mode")

    # Pre-warm BGE-M3 embedder in the background (avoids cold-start spike on first request)
    async def _warm():
        try:
            from rag_pipeline import embed_texts
            await embed_texts(["warm up"])
            log.info("startup.embedder.warm")
        except Exception as exc:
            log.warning("startup.embedder.warn", error=str(exc))

    asyncio.create_task(_warm())
    log.info("startup.complete")

    yield  # ← app is live and serving

    # Graceful shutdown
    if _redis:
        await _redis.aclose()
    log.info("shutdown.complete")


# ============================================================================
# SECTION 6 β€” FastAPI application
# ============================================================================

app = FastAPI(
    title="Omnichannel Fact & Hallucination Intelligence API",
    version="1.0.0",
    description="Near-zero-latency fact-checking and hallucination detection via WebSocket",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


# ============================================================================
# SECTION 7 β€” Core analysis pipeline
# ============================================================================

async def process_segment(
    text: str,
    content_hash: str,
    element_id: str,
    platform: Platform,
) -> AnalysisResult | None:
    """
    Full pipeline for a single text segment. Returns None if noise.

    Cache key:  verdict:{content_hash}
    TTL:        6 h  β†’ green / red
                15 m β†’ yellow
                none β†’ purple (hallucination results are context-specific)
    """
    # 1 β€” Redis cache check (sub-millisecond)
    try:
        r = await get_redis()
        cached_json = await r.get(f"verdict:{content_hash}")
        if cached_json:
            result = AnalysisResult.model_validate_json(cached_json)
            result.cached = True
            result.element_id = element_id
            log.debug("cache.hit", hash=content_hash[:8])
            return result
    except Exception:
        pass  # Redis unavailable in demo mode β€” continue without cache

    # 2 β€” Gatekeeper: fact vs noise (<120 ms p95)
    try:
        gate: GatekeeperResult = await classify_claim(text, settings)
    except Exception as exc:
        log.error("gatekeeper.error", error=str(exc))
        return None

    if gate.label == "noise":
        log.debug("gatekeeper.noise_dropped", hash=content_hash[:8])
        return None

    # 3 β€” Concurrent: RAG pipeline + Grok sensor
    rag_result, grok_result = await asyncio.gather(
        run_rag_pipeline(text, content_hash, settings),
        query_grok_sensor(text, content_hash, settings),
    )

    # 4 β€” Multi-agent Prefect flow
    result: AnalysisResult = await evaluate_claim(
        claim=text,
        claim_hash=content_hash,
        element_id=element_id,
        platform=platform,
        rag_result=rag_result,
        grok_result=grok_result,
        settings=settings,
    )

    # 5 β€” Cache with color-appropriate TTL
    try:
        r = await get_redis()
        if result.color != HighlightColor.PURPLE:
            ttl = (
                settings.cache_ttl_green_red
                if result.color in (HighlightColor.GREEN, HighlightColor.RED)
                else settings.cache_ttl_yellow
            )
            await r.setex(f"verdict:{content_hash}", ttl, result.model_dump_json())
    except Exception:
        pass

    return result


# ============================================================================
# SECTION 8 β€” WebSocket endpoint
# ============================================================================

@app.websocket("/ws/{session_id}")
async def websocket_endpoint(ws: WebSocket, session_id: str):
    """
    Persistent WebSocket connection from the browser extension.

    Inbound:  { type: "batch", payload: TextBatch }
            | { type: "ping" }
    Outbound: { type: "result",  payload: AnalysisResult }
            | { type: "pong" }
            | { type: "error",  payload: { message: str } }
            | { type: "status", payload: { connected: bool, demo_mode: bool, … } }
    """
    await manager.connect(session_id, ws)

    # Initial handshake
    await ws.send_bytes(orjson.dumps(
        WSOutbound(type="status", payload={
            "connected": True,
            "demo_mode": settings.demo_mode,
            "has_groq": settings.has_groq,
            "has_x_api": settings.has_x_api,
        }).model_dump(mode="json")
    ))

    try:
        while True:
            raw = await ws.receive_bytes()
            envelope = WSInbound.model_validate_json(raw)

            if envelope.type == "ping":
                await ws.send_bytes(orjson.dumps(
                    WSOutbound(type="pong", payload=None).model_dump(mode="json")
                ))
                continue

            if envelope.type != "batch" or not envelope.payload:
                continue

            try:
                batch = TextBatch.model_validate(envelope.payload)
            except ValidationError as exc:
                await ws.send_bytes(orjson.dumps(
                    WSOutbound(type="error", payload={"message": str(exc)}).model_dump(mode="json")
                ))
                continue

            # Process all segments in the batch concurrently
            async def _process_and_send(segment):
                t0 = time.perf_counter()
                result = await process_segment(
                    text=segment.text,
                    content_hash=segment.content_hash,
                    element_id=segment.element_id,
                    platform=batch.platform,
                )
                if result:
                    result.latency_ms = round((time.perf_counter() - t0) * 1000, 2)
                    await manager.send(session_id, result.model_dump(mode="json"))

            await asyncio.gather(*[_process_and_send(seg) for seg in batch.segments])

    except WebSocketDisconnect:
        manager.disconnect(session_id)
    except Exception as exc:
        log.error("ws.unexpected_error", session_id=session_id, error=str(exc))
        manager.disconnect(session_id)


# ============================================================================
# SECTION 9 β€” REST endpoints
# ============================================================================

@app.get("/health")
async def health():
    try:
        r = await get_redis()
        redis_ok = await r.ping()
    except Exception:
        redis_ok = False
    return {
        "status": "ok",
        "redis": redis_ok,
        "demo_mode": settings.demo_mode,
        "version": "1.0.0",
    }


@app.get("/metrics")
async def metrics():
    try:
        r = await get_redis()
        cached_verdicts = await r.dbsize()
    except Exception:
        cached_verdicts = 0
    return {
        "active_connections": len(manager.active),
        "cached_verdicts": cached_verdicts,
    }


@app.get("/", response_class=HTMLResponse)
async def demo_ui():
    """Serves the interactive demo UI at the root path (HuggingFace Spaces landing page)."""
    ui_path = os.path.join(os.path.dirname(__file__), "static", "index.html")
    if os.path.exists(ui_path):
        with open(ui_path) as f:
            return HTMLResponse(f.read())
    return HTMLResponse(
        "<h1>Fact Intelligence API</h1>"
        "<p>Connect via WebSocket at <code>/ws/{session_id}</code></p>"
    )


# ============================================================================
# SECTION 10 β€” __main__ block (python app.py)
# ============================================================================

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=settings.port,
        log_level=settings.log_level.lower(),
        access_log=False,
        ws_ping_interval=20,
        ws_ping_timeout=60,
    )