File size: 10,423 Bytes
35fbb15
 
 
 
 
 
 
98cf243
35fbb15
c6aa66a
35fbb15
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
35fbb15
 
c6aa66a
 
 
 
 
35fbb15
 
c6aa66a
35fbb15
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cf243
 
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
35fbb15
 
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cf243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
3e085e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
3e085e1
 
 
 
c6aa66a
 
3e085e1
 
c6aa66a
3e085e1
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
3e085e1
c6aa66a
 
 
 
 
 
 
 
 
 
 
98cf243
c6aa66a
 
 
 
 
98cf243
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e085e1
c6aa66a
 
 
 
 
 
 
 
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
"""
Supabase integration: token verification + chat-history persistence.

All database access here uses the *service-role* key, which bypasses Row Level
Security. Because of that, every query is explicitly scoped to the
authenticated user's id β€” never trust a client-supplied user id.
"""
import json
import os
import time
from pathlib import Path
from datetime import datetime, timezone

from dotenv import load_dotenv
from supabase import create_client, Client

load_dotenv(Path(__file__).parent.parent / ".env")

SUPABASE_URL      = os.environ.get("SUPABASE_URL", "").rstrip("/")
SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
SERVICE_ROLE_KEY  = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")

# Comma-separated list of emails allowed to upload/manage documents.
ADMIN_EMAILS = {
    e.strip().lower()
    for e in os.environ.get("ADMIN_EMAILS", "").split(",")
    if e.strip()
}

_admin: Client | None = None


def is_configured() -> bool:
    return bool(SUPABASE_URL and SERVICE_ROLE_KEY and SUPABASE_ANON_KEY)


def admin() -> Client:
    """Lazily create and reuse a single service-role client."""
    global _admin
    if _admin is None:
        if not is_configured():
            raise RuntimeError(
                "Supabase is not configured. Set SUPABASE_URL, SUPABASE_ANON_KEY "
                "and SUPABASE_SERVICE_ROLE_KEY in your .env file."
            )
        _admin = create_client(SUPABASE_URL, SERVICE_ROLE_KEY)
    return _admin


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


# ── Auth ────────────────────────────────────────────────────────────────────

# Verifying a token is a network round-trip to Supabase; caching it briefly
# shaves that latency off every request. Trade-off: a revoked token stays
# usable for up to TOKEN_CACHE_TTL seconds.
TOKEN_CACHE_TTL = 300
_token_cache: dict[str, tuple[float, object]] = {}


def verify_token(token: str):
    """Validate a Supabase access token and return the user, or None."""
    now = time.monotonic()
    hit = _token_cache.get(token)
    if hit and hit[0] > now:
        return hit[1]

    try:
        res = admin().auth.get_user(token)
        user = res.user if res else None
    except Exception:
        return None

    if user is not None:
        if len(_token_cache) > 500:
            for k in [k for k, v in _token_cache.items() if v[0] <= now]:
                del _token_cache[k]
        _token_cache[token] = (now + TOKEN_CACHE_TTL, user)
    return user


def is_admin(user) -> bool:
    """A user is an admin if their email is listed in ADMIN_EMAILS (.env)."""
    email = (getattr(user, "email", "") or "").lower()
    return bool(email) and email in ADMIN_EMAILS


# ── Sessions ──────────────────────────────────────────────────────────────────

def create_session(user_id: str, title: str) -> dict:
    res = (
        admin()
        .table("chat_sessions")
        .insert({"user_id": user_id, "title": title[:80] or "New chat"})
        .execute()
    )
    return res.data[0]


def list_sessions(user_id: str) -> list[dict]:
    res = (
        admin()
        .table("chat_sessions")
        .select("id, title, created_at, updated_at")
        .eq("user_id", user_id)
        .order("updated_at", desc=True)
        .execute()
    )
    return res.data or []


def get_session(session_id: str, user_id: str) -> dict | None:
    res = (
        admin()
        .table("chat_sessions")
        .select("*")
        .eq("id", session_id)
        .eq("user_id", user_id)
        .limit(1)
        .execute()
    )
    return res.data[0] if res.data else None


def touch_session(session_id: str) -> None:
    admin().table("chat_sessions").update({"updated_at": _now()}).eq("id", session_id).execute()


def rename_session(session_id: str, user_id: str, title: str) -> None:
    admin().table("chat_sessions").update({"title": title[:80]}).eq("id", session_id).eq("user_id", user_id).execute()


def delete_session(session_id: str, user_id: str) -> None:
    # messages cascade-delete via the foreign key
    admin().table("chat_sessions").delete().eq("id", session_id).eq("user_id", user_id).execute()


def delete_all_sessions(user_id: str) -> None:
    admin().table("chat_sessions").delete().eq("user_id", user_id).execute()


# ── Messages ──────────────────────────────────────────────────────────────────

def add_message(session_id: str, role: str, content: str, sources: list | None = None) -> dict:
    res = (
        admin()
        .table("messages")
        .insert({
            "session_id": session_id,
            "role": role,
            "content": content,
            "sources": sources or [],
        })
        .execute()
    )
    return res.data[0]


def list_messages(session_id: str) -> list[dict]:
    res = (
        admin()
        .table("messages")
        .select("id, role, content, sources, feedback, created_at")
        .eq("session_id", session_id)
        .order("created_at")
        .execute()
    )
    return res.data or []


def set_feedback(message_id: str, user_id: str, value: str | None) -> bool:
    """Record πŸ‘/πŸ‘Ž on a message. Verifies the message belongs to the user."""
    res = (
        admin()
        .table("messages")
        .select("session_id")
        .eq("id", message_id)
        .limit(1)
        .execute()
    )
    if not res.data:
        return False
    if get_session(res.data[0]["session_id"], user_id) is None:
        return False
    admin().table("messages").update({"feedback": value}).eq("id", message_id).execute()
    return True


# ── Analytics (admin) ─────────────────────────────────────────────────────────

NO_ANSWER_PREFIX = "I don't have information"

# "Clear unanswered" stores a cutoff timestamp on disk (no schema change needed):
# refusals older than the cutoff stay in chat history but leave the dashboard.
_STATE_PATH = Path(__file__).parent.parent / "data" / "analytics_state.json"


def _unanswered_cleared_at() -> str:
    try:
        return json.loads(_STATE_PATH.read_text(encoding="utf-8")).get("unanswered_cleared_at", "")
    except Exception:
        return ""


def clear_unanswered() -> None:
    _STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
    _STATE_PATH.write_text(
        json.dumps({"unanswered_cleared_at": _now()}), encoding="utf-8"
    )


def _admin_user_ids() -> set[str]:
    """Auth user ids of the accounts listed in ADMIN_EMAILS."""
    ids: set[str] = set()
    if not ADMIN_EMAILS:
        return ids
    try:
        page = 1
        while True:
            res = admin().auth.admin.list_users(page=page, per_page=200)
            users = res if isinstance(res, list) else getattr(res, "users", None) or []
            if not users:
                break
            for u in users:
                if (getattr(u, "email", "") or "").lower() in ADMIN_EMAILS:
                    ids.add(str(u.id))
            if len(users) < 200:
                break
            page += 1
    except Exception:
        pass  # if the lookup fails, stats simply include everyone
    return ids


def analytics() -> dict:
    """Aggregate usage statistics for regular users (admin activity excluded)."""
    admin_ids = _admin_user_ids()

    sess_rows = (
        admin()
        .table("chat_sessions")
        .select("id, user_id")
        .limit(10000)
        .execute()
    ).data or []
    user_session_ids = {
        s["id"] for s in sess_rows if str(s.get("user_id")) not in admin_ids
    }

    msgs = (
        admin()
        .table("messages")
        .select("role, content, sources, feedback, session_id, created_at")
        .order("created_at")
        .limit(5000)
        .execute()
    ).data or []
    msgs = [m for m in msgs if m.get("session_id") in user_session_ids]

    total_questions = sum(1 for m in msgs if m.get("role") == "user")
    answers = [m for m in msgs if m.get("role") == "assistant"]
    fb_up = sum(1 for m in answers if m.get("feedback") == "up")
    fb_down = sum(1 for m in answers if m.get("feedback") == "down")

    # Which documents get cited, and which questions the bot could not answer
    cited: dict[str, int] = {}
    last_user_question: dict[str, str] = {}
    unanswered: list[str] = []

    cleared_at = _unanswered_cleared_at()
    for m in msgs:
        if m.get("role") == "user":
            last_user_question[m.get("session_id")] = m.get("content", "")
            continue
        if (m.get("content") or "").startswith(NO_ANSWER_PREFIX):
            if cleared_at and (m.get("created_at") or "") <= cleared_at:
                continue  # dismissed by the admin
            q = last_user_question.get(m.get("session_id"))
            if q:
                unanswered.append(q)
        for s in (m.get("sources") or []):
            f = s.get("file")
            if f:
                cited[f] = cited.get(f, 0) + 1

    top_documents = sorted(cited.items(), key=lambda x: -x[1])[:10]

    # Questions per day for the last 14 days (UTC)
    from datetime import timedelta, date
    per_day: dict[str, int] = {}
    for m in msgs:
        if m.get("role") == "user":
            day = (m.get("created_at") or "")[:10]
            if day:
                per_day[day] = per_day.get(day, 0) + 1
    today = datetime.now(timezone.utc).date()
    daily = [
        {"date": (today - timedelta(days=i)).isoformat(),
         "count": per_day.get((today - timedelta(days=i)).isoformat(), 0)}
        for i in range(13, -1, -1)
    ]

    return {
        "total_conversations": len(user_session_ids),
        "total_questions": total_questions,
        "total_answers": len(answers),
        "feedback": {"up": fb_up, "down": fb_down},
        "unanswered_count": len(unanswered),
        "recent_unanswered": unanswered[-10:][::-1],
        "top_documents": [{"file": f, "citations": c} for f, c in top_documents],
        "daily_questions": daily,
    }