Spaces:
Running

File size: 47,314 Bytes
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fbc184
aaaab82
 
 
 
 
 
 
 
5011e96
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b3d8b5
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b3d8b5
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b3d8b5
aaaab82
5b3d8b5
aaaab82
 
 
 
 
 
 
 
 
5b3d8b5
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
ca20870
 
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa3252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
5b3d8b5
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b3d8b5
 
 
 
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b3d8b5
aaaab82
 
 
 
 
5b3d8b5
aaaab82
 
5b3d8b5
 
 
 
261e89b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fbc184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83d1307
8fbc184
83d1307
8fbc184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261e89b
 
 
 
 
 
 
c01a7d2
 
 
 
 
 
 
 
 
345f8c8
 
 
 
 
 
 
 
c01a7d2
345f8c8
c01a7d2
 
345f8c8
 
c01a7d2
 
 
 
 
345f8c8
 
c01a7d2
 
345f8c8
 
c01a7d2
 
 
 
 
 
 
345f8c8
c01a7d2
 
 
345f8c8
 
c01a7d2
 
 
 
 
 
 
 
b70bb95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5011e96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b3d8b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca20870
 
 
 
 
 
 
 
 
 
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434048a
 
 
 
 
 
 
23fcc82
 
 
aaaab82
 
23fcc82
aaaab82
 
 
 
 
5b3d8b5
aaaab82
 
 
23fcc82
 
 
aaaab82
 
 
23fcc82
 
 
aaaab82
 
5b3d8b5
 
aaaab82
 
 
 
 
5b3d8b5
aaaab82
 
 
 
5b3d8b5
 
 
 
aaaab82
 
 
 
 
8fa3252
23fcc82
9db3830
aaaab82
 
 
9db3830
 
 
d5ad085
9db3830
d5ad085
 
 
 
 
9db3830
 
d5ad085
 
 
 
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c12ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaaab82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fbc184
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
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
"""

Khazna AI Assistant β€” natural-language search over KU's Elsevier Pure repository.



Environment variables (set as HF Space *Secrets*, never in code):

  PURE_API_KEY        required  Pure API key (read-only)

  OPENAI_API_KEY      required  planner + answer model (gpt-4o-mini)

  ANTHROPIC_API_KEY   optional  enables model="claude" (Claude Haiku 4.5)

  ADMIN_PASSWORD      optional  protects /admin/* and /debug/*

Variables (non-secret, optional):

  PURE_BASE_URL       default https://khazna.ku.ac.ae/ws/api

  PURE_PORTAL_URL     default https://khazna.ku.ac.ae

  PURE_PUBLIC_ONLY    default true   (drop records whose visibility is not public)

  TOP_K               default 8      (records passed to the answer model)

  ALLOWED_ORIGINS     default *      comma-separated, e.g. https://ku-ae.libguides.com,https://library.ku.ac.ae

  RATE_LIMIT_PER_MIN  default 12     per client IP on /agent

  FRONTEND_URL        default https://library.ku.ac.ae/khaznabot (the official LibGuides page; "/" redirects there,

                      the Space's own test chat stays at /test). Set to "" to serve the test chat at "/".

  ANNOUNCEMENT        optional banner text shown by the LibGuides frontend (via /config)

  MAINTENANCE_MODE    "true" disables asking in the frontend; MAINTENANCE_MESSAGE sets the text

Vector index (publication search = Pure API + index, see khazna_index.py):

  KHAZNA_INDEX_REPO   private HF dataset holding the index, e.g. nikeshn/khazna-index

  HF_TOKEN            secret: read token for that dataset

  USE_VECTOR_INDEX    "false" = Pure-only search (default true)

  INDEX_TOP           default 15     index hits fetched from Pure per question

  INDEX_WEIGHT        default 1.5    weight of the index list in the rank fusion

"""

from __future__ import annotations

import hmac
import os
import re
import secrets
import sqlite3
import time
from collections import defaultdict, deque
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote_plus

from fastapi import FastAPI, Header, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from pydantic import BaseModel

import khazna_index
import pipeline
from pure_client import PureClient, PureError

PURE_BASE_URL = os.environ.get("PURE_BASE_URL", "https://khazna.ku.ac.ae/ws/api")
PURE_PORTAL_URL = os.environ.get("PURE_PORTAL_URL", "https://khazna.ku.ac.ae")
PUBLIC_ONLY = os.environ.get("PURE_PUBLIC_ONLY", "true").lower() != "false"
ACTIVE_PERSONS_ONLY = os.environ.get("PURE_ACTIVE_PERSONS_ONLY", "true").lower() != "false"
TOP_K = int(os.environ.get("TOP_K", "8"))
ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "")
ALLOWED_ORIGINS = [o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "*").split(",") if o.strip()]
FRONTEND_URL = os.environ.get("FRONTEND_URL", "https://library.ku.ac.ae/khaznabot").strip()
RATE_LIMIT = int(os.environ.get("RATE_LIMIT_PER_MIN", "12"))
DB_PATH = "/data/khazna_analytics.db" if os.path.isdir("/data") else "khazna_analytics.db"
HERE = os.path.dirname(os.path.abspath(__file__))
SCOPES = ("all", "publications", "theses", "persons", "organisations", "projects", "equipment", "collaborations", "datasets")
SCOPE_PORTAL_PATH = {"publications": "publications", "theses": "studentTheses", "persons": "persons",
                     "organisations": "organisations", "projects": "projects", "equipment": "equipments",
                     "collaborations": "publications", "datasets": "datasets"}
INTENT_SCOPE = {"thesis_search": "theses", "project_search": "projects", "equipment_search": "equipment",
                "collab_search": "collaborations", "topic_search": "publications", "author_search": "publications", "count": "publications",
                "expert_search": "persons", "org_search": "organisations", "dataset_search": "datasets",
                "unit_people": "organisations"}

pure: PureClient | None = None


# ───────────────────────────── analytics ────────────────────────────
def init_db():
    with sqlite3.connect(DB_PATH) as c:
        c.execute("""CREATE TABLE IF NOT EXISTS queries (

            id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT, question TEXT, intent TEXT,

            keywords TEXT, results INTEGER, model TEXT, seconds REAL, error TEXT)""")
        c.execute("""CREATE TABLE IF NOT EXISTS feedback (

            id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT, question TEXT, rating TEXT, comment TEXT)""")
        cols = {r[1] for r in c.execute("PRAGMA table_info(queries)")}
        if "scope" not in cols:  # migrate DBs created by the first version
            c.execute("ALTER TABLE queries ADD COLUMN scope TEXT")
        for col in ("origin", "request_id", "session_id"):
            if col not in cols:
                c.execute(f"ALTER TABLE queries ADD COLUMN {col} TEXT")
        fcols = {r[1] for r in c.execute("PRAGMA table_info(feedback)")}
        for col in ("request_id", "session_id"):
            if col not in fcols:
                c.execute(f"ALTER TABLE feedback ADD COLUMN {col} TEXT")


def log_query(question, intent, keywords, results, model, seconds, error=None, scope="all", origin="",

              request_id="", session_id=""):
    try:
        with sqlite3.connect(DB_PATH) as c:
            c.execute(
                "INSERT INTO queries (ts,question,intent,keywords,results,model,seconds,error,scope,origin,request_id,session_id) "
                "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
                (datetime.now(timezone.utc).isoformat(), question, intent, " | ".join(keywords or []), results, model,
                 round(seconds, 2), error, scope, origin, request_id, session_id),
            )
    except Exception as e:
        print(f"[log] {e}")


# ───────────────────────────── rate limit ───────────────────────────
_hits: dict[str, deque] = defaultdict(deque)


def _client_ip(request: Request) -> str:
    fwd = request.headers.get("x-forwarded-for", "")  # HF Spaces sit behind a proxy
    return fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "?")


def _rate_limited(ip: str) -> bool:
    now, q = time.time(), _hits[ip]
    while q and now - q[0] > 60:
        q.popleft()
    if len(q) >= RATE_LIMIT:
        return True
    q.append(now)
    if len(_hits) > 5000:
        _hits.clear()
    return False


# ───────────────────────────── app ──────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
    global pure
    init_db()
    key = os.environ.get("PURE_API_KEY", "")
    if not key:
        print("WARNING: PURE_API_KEY not set β€” searches will fail.")
    pure = PureClient(PURE_BASE_URL, key, PURE_PORTAL_URL, public_only=PUBLIC_ONLY, active_persons_only=ACTIVE_PERSONS_ONLY)
    khazna_index.CATALOG.start_background_load()   # downloads + loads in a thread; Pure-only until ready
    yield
    await pure.aclose()


app = FastAPI(title="Khazna AI Assistant", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=ALLOWED_ORIGINS, allow_methods=["GET", "POST"], allow_headers=["*"],
                   expose_headers=["X-Request-ID", "Retry-After"])


class ChatMessage(BaseModel):
    role: str
    content: str


class AgentRequest(BaseModel):
    question: str
    model: str = "gpt"            # "gpt" | "claude"  (same convention as LibBee)
    history: list[ChatMessage] = []
    top_k: int | None = None
    scope: str = "all"            # all | publications | theses | persons | organisations | projects | equipment | collaborations
    person_uuid: str | None = None  # set when the user picks one researcher from a disambiguation list
    person_name: str | None = None  # same, for a portal-listed researcher without an API uuid


class FeedbackRequest(BaseModel):
    # LibGuides frontend sends {request_id, feedback, session_id}; the Space widget sends {question, rating}.
    request_id: str = ""
    feedback: str = ""
    session_id: str = ""
    question: str = ""
    rating: str = ""
    comment: str = ""


def _require_admin(pw: str | None):
    if not ADMIN_PASSWORD or pw != ADMIN_PASSWORD:
        raise HTTPException(401, "Admin password required (X-Admin-Password header).")


def _public_result(o: dict, n: int) -> dict:
    kind = o.get("kind", "publication")
    if kind == "person":
        keep = ("kind", "uuid", "name", "job_titles", "organisations", "keywords", "orcid", "portal_url", "evidence", "matching_outputs",
                "supervised", "supervised_theses", "choose", "role", "college", "scholar_url")
    elif kind == "organisation":
        keep = ("kind", "uuid", "name", "type", "parents", "portal_url", "college", "people", "historic")
    elif kind == "collaborator":
        keep = ("kind", "uuid", "name", "type", "country", "joint_outputs", "examples", "portal_url")
    elif kind == "project":
        keep = ("kind", "uuid", "title", "subtitle", "type", "year", "period", "status", "venue", "funders", "keywords", "portal_url")
    elif kind == "equipment":
        keep = ("kind", "uuid", "title", "type", "category", "venue", "location", "keywords", "portal_url")
    else:
        keep = ("kind", "uuid", "title", "subtitle", "type", "year", "date", "authors", "ku_authors", "venue",
                "doi", "doi_url", "open_access", "file_available", "portal_url", "keywords",
                "department", "oa_url", "oa_label",   # these three come from the vector index (may be empty)
                "ku_affiliated", "in_khazna", "note", "level")  # Scopus/SciVal flags; thesis level
    out = {k: o.get(k) for k in keep}
    if kind == "thesis":
        out["supervisors"] = [{"name": x.get("name"), "uuid": x.get("uuid")} for x in (o.get("supervisors") or [])]
    if kind == "project":
        out["participants"] = [{"name": x.get("name"), "role": x.get("role")} for x in (o.get("participants") or [])]
    if kind == "equipment":
        out["contacts"] = [{"name": x.get("name")} for x in (o.get("contacts") or [])]  # names only
    out["n"] = n
    if kind in ("publication", "dataset", "thesis", "project", "equipment"):
        out["abstract"] = (o.get("abstract") or "")[:400]
    return out


CLARIFY_PREFIX = "Just to check:"


def _reply(t0: float, **kw) -> dict:
    kw.setdefault("search_results", [])
    kw["response_time"] = round(time.time() - t0, 2)
    return kw


_SESSION_RE = re.compile(r"^[A-Za-z0-9_-]{8,80}$")
FIRST_PAGE = 12  # people shown before "Show more"


from pure_client import PERSONS_PORTAL_PARAMS


def _portal_url(path: str, term: str, search_by: str | None = None) -> str:
    """Khazna portal search link. People searches use the portal's own parameters with

    community=false, so external 'Pure Community' profiles are not listed."""
    url = f"{PURE_PORTAL_URL}/en/{path}/?search={quote_plus(term)}"
    return url + PERSONS_PORTAL_PARAMS if path == "persons" else url


PORTAL_YEAR_MAX = 15   # a year range longer than this is not sent as year filters (the link would get unwieldy)


def _portal_link(plan, q: str) -> str:
    """'Open this search in Khazna' link built from the UNDERSTOOD question: the topic goes in the search box and

    years become the portal's own publicationYear filter (never the words of the question). Totals ('how many

    outputs in 2025') open the year-filtered list with an empty search box."""
    path = SCOPE_PORTAL_PATH.get(INTENT_SCOPE.get(plan.intent, "publications"), "publications")
    if plan.intent == "author_search" and plan.author_name:
        term = plan.author_name
    elif plan.intent == "count" and getattr(plan, "all_outputs", False):
        term = ""
    elif plan.intent in ("unit_people", "org_search") and getattr(plan, "unit_name", None):
        term = plan.unit_name
    elif plan.intent == "thesis_search" and not plan.keyword_queries:
        term = ""
    elif plan.keyword_queries:
        term = plan.keyword_queries[0]
    else:
        term = q
    url = f"{PURE_PORTAL_URL}/en/{path}/?search={quote_plus(term)}"
    if path == "publications" and (plan.year_from or plan.year_to):
        lo = plan.year_from or plan.year_to
        hi = plan.year_to or datetime.now().year
        if plan.year_from and lo <= hi and hi - lo < PORTAL_YEAR_MAX:
            url += "".join(f"&publicationYear={y}" for y in range(lo, hi + 1))
        elif not plan.year_from and plan.year_to:      # "before 2020": no start year, so no year filter
            pass
    if path == "persons":
        return url + PERSONS_PORTAL_PARAMS
    return url + "&nofollow=true"


def _followups(plan, retrieval: dict | None) -> list[dict]:
    """Next-step suggestions the frontend renders as chips: {label, question, scope}."""
    kw = (plan.keyword_queries[0] if plan.keyword_queries else "").strip()
    year = datetime.now().year
    out: list[dict] = []
    if plan.intent == "author_search" and retrieval and retrieval.get("person"):
        name = retrieval["person"]["name"]
        out.append({"label": f"Latest by {name}", "question": f"Latest publications by {name}", "scope": "publications"})
        top_kw = (retrieval["person"].get("keywords") or [kw])[0] if (retrieval["person"].get("keywords") or kw) else ""
        if top_kw:
            out.append({"label": f"Others working on {top_kw}", "question": f"Who else at KU works on {top_kw}?", "scope": "persons"})
        return out
    if not kw and plan.intent != "unit_people":
        return out
    if plan.intent in ("topic_search", "count"):
        out += [{"label": "Who at KU works on this?", "question": f"Who at KU works on {kw}?", "scope": "persons"},
                {"label": "KU theses on this", "question": f"KU theses on {kw}", "scope": "theses"},
                {"label": "Related projects", "question": f"KU research projects on {kw}", "scope": "projects"},
                {"label": "Who does KU collaborate with?", "question": f"Which organisations does KU collaborate with on {kw}?", "scope": "collaborations"}]
        if not plan.year_from:
            out.append({"label": f"Only since {year - 3}", "question": f"KU publications on {kw} since {year - 3}", "scope": "publications"})
    elif plan.intent == "project_search":
        out += [{"label": "Who works on this?", "question": f"Who at KU works on {kw}?", "scope": "persons"},
                {"label": "Publications from this area", "question": f"KU publications on {kw}", "scope": "publications"}]
    elif plan.intent == "equipment_search":
        out += [{"label": "Which departments use this?", "question": f"Which KU departments or centres work on {kw}?", "scope": "organisations"},
                {"label": "Experts in this area", "question": f"Who at KU works on {kw}?", "scope": "persons"}]
    elif plan.intent == "collab_search":
        out += [{"label": "The joint publications", "question": f"KU publications on {kw}", "scope": "publications"},
                {"label": "KU experts in this area", "question": f"Who at KU works on {kw}?", "scope": "persons"}]
    elif plan.intent == "thesis_search":
        out += [{"label": "Who supervises in this area?", "question": f"Who at KU supervises theses on {kw}?", "scope": "persons"},
                {"label": "Related publications", "question": f"KU publications on {kw}", "scope": "publications"}]
    elif plan.intent == "expert_search":
        out += [{"label": "Show the publications", "question": f"KU publications on {kw}", "scope": "publications"},
                {"label": "Which departments or centres?", "question": f"Which KU departments or centres work on {kw}?", "scope": "organisations"}]
    elif plan.intent == "unit_people":
        unit = plan.unit_name or kw
        if unit:
            out += [{"label": f"Publications from {unit}", "question": f"Recent KU publications from {unit}", "scope": "publications"},
                    {"label": f"Theses from {unit}", "question": f"Recent theses from {unit}", "scope": "theses"}]
    elif plan.intent == "org_search":
        out += [{"label": "Experts in this area", "question": f"Who at KU works on {kw}?", "scope": "persons"},
                {"label": "Publications on this", "question": f"KU publications on {kw}", "scope": "publications"}]
    elif plan.intent == "dataset_search":
        out += [{"label": "Publications on this", "question": f"KU publications on {kw}", "scope": "publications"},
                {"label": "Who works on this?", "question": f"Who at KU works on {kw}?", "scope": "persons"}]
    return out[:4]


# ───────────────────────────── routes ───────────────────────────────
@app.get("/")
def ui():
    # One public face: send visitors of the Space URL to the official LibGuides page.
    if FRONTEND_URL.startswith("https://"):
        return RedirectResponse(FRONTEND_URL, status_code=302)
    return FileResponse(os.path.join(HERE, "static", "index.html"))


@app.get("/test")
def test_ui():
    """The Space's own chat page (widget.js), for testing backend changes before they reach LibGuides."""
    return FileResponse(os.path.join(HERE, "static", "index.html"))


@app.get("/widget.js")
def widget_js():
    # Short cache so LibGuides pages pick up new versions within minutes of a push.
    return FileResponse(os.path.join(HERE, "static", "widget.js"), media_type="application/javascript",
                        headers={"Cache-Control": "public, max-age=300"})


@app.get("/config")
def public_config():
    return {
        "announcement": os.environ.get("ANNOUNCEMENT", ""),
        "maintenance_mode": os.environ.get("MAINTENANCE_MODE", "false").lower() == "true",
        "maintenance_message": os.environ.get("MAINTENANCE_MESSAGE", "The Khazna assistant is temporarily unavailable for maintenance."),
        "scopes": list(SCOPES),
    }


@app.get("/health")
def health():
    return {
        "status": "ok",
        "pure_base_url": PURE_BASE_URL,
        "pure_key_configured": bool(os.environ.get("PURE_API_KEY")),
        "frontend_url": FRONTEND_URL,
        "portal_people_status": getattr(pure, "portal_status", "not tried") if pure else "not started",
        "public_only": PUBLIC_ONLY,
        "scopes": SCOPES,
        "models": {"gpt": bool(os.environ.get("OPENAI_API_KEY")), "claude": bool(os.environ.get("ANTHROPIC_API_KEY"))},
        "vector_index": {"status": khazna_index.INDEX.status, "repo": khazna_index.INDEX.repo or None,
                         "built_at": khazna_index.INDEX.as_of or None,
                         "records": khazna_index.INDEX.info.get("records")},
        "indexes": khazna_index.CATALOG.health(),
    }


@app.post("/admin/reload-index")
async def reload_index(x_admin_password: str | None = Header(default=None)):
    """Download and load the newest indexes from KHAZNA_INDEX_REPO without restarting the Space."""
    _require_admin(x_admin_password)
    import asyncio
    status = await asyncio.to_thread(khazna_index.CATALOG.reload)
    return {"vector_index": khazna_index.INDEX.status, "indexes": status}


@app.get("/admin/build")
def build_page():
    """Upload page for building the offline data inside the Space (the API calls on it need the admin password)."""
    return FileResponse(os.path.join(HERE, "static", "build.html"), headers={"Cache-Control": "no-store"})


@app.post("/admin/build")
async def build_start(request: Request, x_admin_password: str | None = Header(default=None)):
    """multipart/form-data with any of: outputs, manifest, orgs, persons, theses, scival (.xlsx/.csv); upload=true|false."""
    _require_admin(x_admin_password)
    import builder
    if builder.running():
        raise HTTPException(409, "A build is already running.")
    form = await request.form()
    files = {}
    for field in builder.FILE_FIELDS:
        f = form.get(field)
        if f is not None and getattr(f, "filename", ""):
            files[field] = (f.filename, await f.read())
    if not files:
        raise HTTPException(422, "Attach at least one export file.")
    if "persons" in files and "orgs" not in files and not khazna_index.DIRECTORY.has_orgs:
        raise HTTPException(422, "The persons export needs the org-unit export (attach both the first time).")
    try:
        folder = builder.save_uploads(files)
    except ValueError as e:
        raise HTTPException(422, str(e))
    builder.start(folder, upload=str(form.get("upload", "true")).lower() != "false")
    return {"started": True, "files": sorted(files)}


@app.post("/admin/sync")
async def sync_start(request: Request, x_admin_password: str | None = Header(default=None),

                     x_sync_token: str | None = Header(default=None)):
    """Refresh from the Pure API, no files: JSON {"parts": ["orgs","persons","theses","outputs"], "upload": true}.

    Parts that fail, or return far fewer records than now, keep their current data. A weekly scheduler can call this

    with the X-Sync-Token header (secret SYNC_TOKEN), which allows ONLY this refresh, not the other admin pages."""
    token = os.environ.get("SYNC_TOKEN", "")
    if not (token and x_sync_token and hmac.compare_digest(token, x_sync_token)):
        _require_admin(x_admin_password)
    import builder
    import khazna_sync
    try:
        body = await request.json()
    except Exception:
        body = {}
    parts = [p for p in (body.get("parts") or khazna_sync.default_parts()) if p in khazna_sync.ALL_PARTS]
    if not parts:
        raise HTTPException(422, "parts must be any of: " + ", ".join(khazna_sync.ALL_PARTS))
    if not builder.start_sync(parts, upload=body.get("upload", True) is not False):
        raise HTTPException(409, "A build is already running.")
    return {"started": True, "parts": parts}


@app.get("/admin/sync/check")
async def sync_check(x_admin_password: str | None = Header(default=None)):
    """Which Pure list endpoints the key may read (one record each; field names only, no values)."""
    _require_admin(x_admin_password)
    import khazna_sync
    pure_ = khazna_sync.make_client()
    try:
        return await khazna_sync.check_access(pure_)
    finally:
        await pure_.aclose()


@app.get("/admin/build/status")
def build_status(x_admin_password: str | None = Header(default=None)):
    _require_admin(x_admin_password)
    import builder
    return builder.status()


# ── Khazna vs Scopus/SciVal coverage dashboard (open to anyone with the link: Nikesh, 30 Nov 2026) ──
def _coverage_year(year: str | None) -> int | None:
    if not year or year in ("all", "0"):
        return None
    if not year.isdigit() or not 1900 < int(year) < 2100:
        raise HTTPException(422, "year must be a 4-digit year or 'all'")
    return int(year)


def _cov_filter(v: str | None, allowed: tuple) -> str | None:
    if not v or v == "all":
        return None
    if v not in allowed:
        raise HTTPException(422, "filter must be one of: all, " + ", ".join(allowed))
    return v


@app.get("/coverage/summary")
def coverage_summary(year: str | None = None, portal: str | None = None, staff: str | None = None):
    import coverage
    try:
        return coverage.summary(_coverage_year(year), _cov_filter(portal, coverage.FILTERS["portal"]),
                                _cov_filter(staff, coverage.FILTERS["staff"]))
    except RuntimeError as e:
        raise HTTPException(503, str(e))


@app.get("/coverage/list")
def coverage_list(category: str, year: str | None = None, q: str = "", page: int = 1, size: int = 50,

                  portal: str | None = None, staff: str | None = None):
    import coverage
    try:
        return coverage.page(category, _coverage_year(year), q[:120], page, size,
                             _cov_filter(portal, coverage.FILTERS["portal"]), _cov_filter(staff, coverage.FILTERS["staff"]))
    except KeyError:
        raise HTTPException(422, "unknown category")
    except RuntimeError as e:
        raise HTTPException(503, str(e))


@app.get("/coverage/export")
def coverage_export(category: str = "all", year: str | None = None, portal: str | None = None, staff: str | None = None):
    import coverage
    from fastapi.responses import Response
    try:
        data, name = coverage.excel(category, _coverage_year(year), _cov_filter(portal, coverage.FILTERS["portal"]),
                                    _cov_filter(staff, coverage.FILTERS["staff"]))
    except KeyError:
        raise HTTPException(422, "unknown category")
    except RuntimeError as e:
        raise HTTPException(503, str(e))
    return Response(data, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    headers={"Content-Disposition": f'attachment; filename="{name}"'})


@app.post("/admin/repair-scival")
def repair_scival(x_admin_password: str | None = Header(default=None)):
    """One-off (30 Nov): restore SciVal's full author lists and years that a Scopus run had overwritten."""
    _require_admin(x_admin_password)
    import builder
    if not builder.start_repair():
        raise HTTPException(409, "A build is already running.")
    return {"started": True, "status": "/admin/build/status"}


@app.get("/admin/coverage/probe")
async def coverage_probe(n: int = 300, x_admin_password: str | None = Header(default=None)):
    """Opens a random sample of records on the Khazna portal (n, max 600) and reports which ones load, per feature.

    Admin only: it sends n x 2 requests to the portal. Takes about a minute for 300."""
    _require_admin(x_admin_password)
    import coverage
    try:
        return await coverage.probe(max(20, min(int(n), 600)))
    except RuntimeError as e:
        raise HTTPException(503, str(e))


# The LibGuides box holds only the block's HTML (LibGuides caps a box at ~65,000 characters); its styles and program
# are served from here. Only these two files; short cache so an upload shows within minutes.
_ASSETS = {"khazna-block.css": "text/css; charset=utf-8", "khazna-block.js": "application/javascript; charset=utf-8"}


@app.get("/assets/{name}")
def block_asset(name: str):
    if name not in _ASSETS:
        raise HTTPException(404, "not found")
    f = Path(__file__).resolve().parent / "static" / name
    if not f.exists():
        raise HTTPException(404, "not found")
    return Response(f.read_bytes(), media_type=_ASSETS[name],
                    headers={"Cache-Control": "public, max-age=300", "Access-Control-Allow-Origin": "*"})


@app.get("/stats/publications")
def publication_stats():
    """All KU publications by year for a dashboard: KU-affiliated records in Khazna (per Scopus/SciVal)

    plus KU papers that Scopus lists but Khazna does not have yet. Counts only, no records."""
    d, m = khazna_index.DIRECTORY, khazna_index.MISSING
    if not d.has_ku:
        raise HTTPException(503, "KU-affiliation data is not loaded yet.")
    k = d.ku_table
    by_year: dict[int, dict] = {}
    for (y, st), n in k.groupby(["year", "ku_status"]).size().items():
        by_year.setdefault(int(y), {"ku_in_khazna": 0, "not_ku_in_khazna": 0, "unverified": 0, "ku_not_in_khazna": 0})
        by_year[int(y)][{"ku": "ku_in_khazna", "not_ku": "not_ku_in_khazna"}.get(st, "unverified")] += int(n)
    if m.ready:
        for y, n in m._data[0]["year"].value_counts().items():
            by_year.setdefault(int(y), {"ku_in_khazna": 0, "not_ku_in_khazna": 0, "unverified": 0, "ku_not_in_khazna": 0})
            by_year[int(y)]["ku_not_in_khazna"] += int(n)
    rows = [{"year": y, **v, "all_ku": v["ku_in_khazna"] + v["ku_not_in_khazna"]} for y, v in sorted(by_year.items()) if y]
    tot = {c: sum(r[c] for r in rows) for c in ("ku_in_khazna", "ku_not_in_khazna", "all_ku", "not_ku_in_khazna", "unverified")}
    return {"as_of": d.info.get("ku_affiliation", {}).get("built_at", ""), "source": "Scopus/SciVal KU affiliation",
            "totals": tot, "by_year": rows}


@app.post("/agent")
async def agent(req: AgentRequest, request: Request, response: Response):
    t0 = time.time()
    request_id = secrets.token_hex(12)
    response.headers["X-Request-ID"] = request_id
    session_id = request.headers.get("x-khazna-session", "")
    session_id = session_id if _SESSION_RE.match(session_id) else ""
    if _rate_limited(_client_ip(request)):
        return JSONResponse(status_code=429, headers={"Retry-After": "60", "X-Request-ID": request_id},
                            content=_reply(t0, intent="rate_limited", request_id=request_id,
                                           answer="You're sending questions very quickly β€” please wait a minute and try again."))
    if os.environ.get("MAINTENANCE_MODE", "false").lower() == "true":
        return JSONResponse(status_code=503, headers={"X-Request-ID": request_id},
                            content=_reply(t0, intent="maintenance", request_id=request_id,
                                           answer=os.environ.get("MAINTENANCE_MESSAGE", "The Khazna assistant is temporarily unavailable.")))
    q = req.question.strip()[:1000]
    if not q:
        return _reply(t0, intent="empty", answer="Please type a question.")
    history = [m.model_dump() for m in req.history][-8:]
    model = req.model if req.model in ("gpt", "claude") else "gpt"
    scope = req.scope if req.scope in SCOPES else "all"
    top_k = max(1, min(req.top_k or TOP_K, 15))
    origin = request.headers.get("origin", "")

    plan = await pipeline.plan_query(q, history, model, datetime.now().year, scope)
    base = {"intent": plan.intent, "plan": plan.model_dump(), "model_used": model, "scope": scope, "request_id": request_id}
    logx = {"scope": scope, "origin": origin, "request_id": request_id, "session_id": session_id}

    # Clarify first when the planner sees genuinely different readings (Nikesh, 30 Nov 2026). Never twice in a row,
    # never when the user picked a search area on purpose; each option is a full question the block asks on click.
    opts = [o.strip() for o in (plan.clarify_question and plan.clarify_options or []) if o and o.strip()][:4]
    just_asked = bool(history) and history[-1].get("role") == "assistant" and \
        str(history[-1].get("content", "")).startswith(CLARIFY_PREFIX)
    if len(opts) >= 2 and scope == "all" and not just_asked:
        log_query(q, "clarify", opts, 0, model, time.time() - t0, **logx)
        return _reply(t0, **{**base, "intent": "clarify"}, answer=f"{CLARIFY_PREFIX} {plan.clarify_question.strip()}",
                      clarify=True, original_question=q,
                      follow_up_suggestions=[{"label": o, "question": o, "scope": "all"} for o in opts])

    if plan.intent == "social":
        return _reply(t0, **base, answer=pipeline.SOCIAL_ANSWER)
    if plan.intent == "out_of_scope":
        return _reply(t0, **base, answer=pipeline.OUT_OF_SCOPE_ANSWER)
    if plan.intent == "repository_help":
        ans = await pipeline.answer_repository_help(q, model)
        log_query(q, plan.intent, [], 0, model, time.time() - t0, **logx)
        return _reply(t0, **base, answer=ans)

    person_uuid = req.person_uuid if req.person_uuid and re.fullmatch(r"[A-Za-z0-9-]{1,64}", req.person_uuid) else None
    try:
        person_name = (req.person_name or "").strip()[:120] or None
        retrieval = await pipeline.retrieve(pure, plan, person_uuid=person_uuid, person_name=person_name)
    except PureError as e:
        log_query(q, plan.intent, plan.keyword_queries, 0, model, time.time() - t0, str(e), **logx)
        if e.status == 403 and plan.intent == "dataset_search":
            msg = ("Dataset search isn't switched on yet: the Khazna API key needs the /data-sets/* endpoint. "
                   "Meanwhile you can browse datasets at https://khazna.ku.ac.ae/en/datasets/.")
        else:
            msg = ("Sorry β€” I couldn't reach Khazna just now. Please try again in a moment, "
                   "or search directly at https://khazna.ku.ac.ae/.")
        return _reply(t0, **base, answer=msg, error=str(e))

    results = retrieval["results"]
    if retrieval.get("clarify"):
        c = retrieval["clarify"]
        more = (" Use **Show more** below the list to see everyone, or add a first name or department to narrow it down."
                if c["shown"] > FIRST_PAGE else "")
        if c["count"] > c["shown"]:
            more += f" (Showing the first {c['shown']} of {c['count']}.)"
        answer = (f"I found **{c['count']} KU researchers** whose name matches β€œ{c['name']}”. Which one do you mean?\n"
                  f"Choose **Explore this researcher** on the right person below, or add their full name or department to your question.{more}")
        log_query(q, "author_clarify", [c["name"]], len(results), model, time.time() - t0, **logx)
        return _reply(
            t0, **{**base, "intent": "author_clarify"},
            answer=answer, clarify=True, original_question=q,
            search_results=[_public_result(o, i) for i, o in enumerate(results[:FIRST_PAGE], 1)],
            more_results=[_public_result(o, i) for i, o in enumerate(results[FIRST_PAGE:], FIRST_PAGE + 1)],
            total_found=c["count"], after_filters=len(results),
            trace=[{k: v for k, v in t.items() if k != "error"} for t in retrieval["trace"]],
            portal_search_url=_portal_url("persons", c["name"], "PartOfNameOrTitle"),
            follow_up_suggestions=[],
        )
    if not results and retrieval.get("no_person"):
        name = retrieval["no_person"]
        if khazna_index.DIRECTORY.has_persons:   # former staff are recognised too (find_former)
            answer = (f"I couldn't find a KU researcher, current or former, named β€œ{name}” in Khazna. "
                      "Check the spelling or type their full name (names are matched on whole words). "
                      "External co-authors are not listed.")
        else:
            answer = (f"I couldn't find a current KU researcher named β€œ{name}” in Khazna. "
                      "Check the spelling or try their full name. Former staff and external co-authors are not listed.")
        sugs = retrieval.get("suggestions") or []
        if sugs:
            answer += " Did you mean one of these?"
        log_query(q, "author_not_found", [name], 0, model, time.time() - t0, **logx)
        return _reply(t0, **base, answer=answer, trace=[{k: v for k, v in t.items() if k != "error"} for t in retrieval["trace"]],
                      portal_search_url=_portal_url("persons", name), follow_up_suggestions=sugs[:4])
    if not results and retrieval.get("person"):
        pname = retrieval["person"].get("name", "this researcher")
        answer = (f"Here is **{pname}**'s Khazna profile. I couldn't find matching publications through search"
                  + (" for that topic or filter" if (plan.keyword_queries and plan.intent == "author_search") else "")
                  + "; open the profile for their full list of outputs.")
    elif not results and not retrieval.get("facts"):
        filt = bool(plan.year_from or plan.year_to or plan.output_types or plan.open_access_only)
        answer = ("I couldn't find Khazna records matching that" + (" with the filters you asked for" if filt else "")
                  + ". Try broader or different keywords" + (", or remove the year/type filter." if filt else "."))
        spell = next((s for s in retrieval.get("suggestions") or [] if s.get("kind") == "spelling"), None)
        if spell:
            answer += f" {spell['label']}"
    else:
        try:
            answer = await pipeline.synthesize(q, plan, retrieval, history, model, top_k)
            if retrieval.get("no_person_topic"):
                answer = (f"No KU researcher is named β€œ{retrieval['no_person_topic']}”, so here is KU research on it.\n\n"
                          + answer)
        except Exception as e:
            print(f"[synth] {e}")
            answer = (pipeline.facts_sentence(retrieval.get("facts"))
                      or f"I found {len(results)} matching Khazna records; here are the most relevant.")

    elapsed = time.time() - t0
    log_query(q, plan.intent, plan.keyword_queries, len(results), model, elapsed, **logx)
    person = retrieval.get("person")
    index_as_of = next((t.get("index_as_of", "") for t in retrieval["trace"] if t.get("source") == "index"), "")
    scopus_only = retrieval.get("scopus_only") or []
    return _reply(
        t0, **base,
        answer=answer,
        index_as_of=index_as_of[:10],
        search_results=[_public_result(o, i) for i, o in enumerate(results[:top_k], 1)]
                       + [_public_result(o, i) for i, o in enumerate(scopus_only, min(len(results), top_k) + 1)],
        more_results=[_public_result(o, i) for i, o in enumerate(results[top_k:top_k + 12], min(len(results), top_k) + len(scopus_only) + 1)],
        facts=retrieval.get("facts"),
        total_found=retrieval["total"],
        after_filters=len(results),
        person=_public_result(person, 0) if person else None,
        database_query=" | ".join(t.get("query", "") for t in retrieval["trace"] if t.get("query")),
        trace=[{k: v for k, v in t.items() if k != "error"} for t in retrieval["trace"]],
        portal_search_url=_portal_link(plan, q),
        follow_up_suggestions=((retrieval.get("suggestions") or []) + (_followups(plan, retrieval) if results else []))[:6],
        sections=_section_cards(retrieval, min(len(results), top_k) + len(scopus_only), plan),
    )


def _section_cards(retrieval: dict, start: int, plan=None) -> list[dict]:
    """Theses and experts of a combined question, numbered after the publications (as the answer cites them), each

    with its own Khazna portal search for the topic (theses list; people whose profiles match the topic)."""
    out, n = [], start
    topic = ((plan.keyword_queries or [plan.broad_query or ""])[0] if plan else "") or ""
    for k in ("theses", "experts"):
        v = (retrieval.get("sections") or {}).get(k)
        if not v or not v.get("results"):
            continue
        out.append({"kind": k, "label": {"theses": "Theses", "experts": "KU experts"}[k], "found": v["found"],
                    "topic": topic,
                    "portal_url": _portal_url("studentTheses" if k == "theses" else "persons", topic) if topic else "",
                    "results": [_public_result(o, i) for i, o in enumerate(v["results"], n + 1)]})
        n += len(v["results"])
    return out


@app.post("/feedback")
def feedback(req: FeedbackRequest):
    rating = (req.feedback or req.rating or "")[:10]
    if rating not in ("up", "down"):
        raise HTTPException(422, "feedback must be 'up' or 'down'")
    question = req.question
    with sqlite3.connect(DB_PATH) as c:
        if req.request_id and not question:  # recover the question from the query log
            row = c.execute("SELECT question FROM queries WHERE request_id=?", (req.request_id[:40],)).fetchone()
            question = row[0] if row else ""
        c.execute("INSERT INTO feedback (ts,question,rating,comment,request_id,session_id) VALUES (?,?,?,?,?,?)",
                  (datetime.now(timezone.utc).isoformat(), question[:1000], rating, req.comment[:1000],
                   req.request_id[:40], req.session_id[:80]))
    return {"status": "ok"}


@app.get("/admin/stats")
def admin_stats(x_admin_password: str | None = Header(default=None)):
    _require_admin(x_admin_password)
    with sqlite3.connect(DB_PATH) as c:
        c.row_factory = sqlite3.Row
        total = c.execute("SELECT COUNT(*) n, AVG(seconds) s FROM queries").fetchone()
        by_intent = c.execute("SELECT intent, COUNT(*) n FROM queries GROUP BY intent ORDER BY n DESC").fetchall()
        by_origin = c.execute("SELECT origin, COUNT(*) n FROM queries GROUP BY origin ORDER BY n DESC").fetchall()
        zero = c.execute("SELECT question, intent, keywords, ts FROM queries WHERE results=0 AND intent NOT IN "
                         "('social','repository_help','out_of_scope') ORDER BY id DESC LIMIT 30").fetchall()
        recent = c.execute("SELECT ts, question, intent, scope, keywords, results, seconds, error FROM queries ORDER BY id DESC LIMIT 50").fetchall()
        fb = c.execute("SELECT rating, COUNT(*) n FROM feedback GROUP BY rating").fetchall()
    return {"queries": total["n"], "avg_seconds": round(total["s"] or 0, 2),
            "by_intent": {r["intent"]: r["n"] for r in by_intent},
            "by_origin": {(r["origin"] or "direct"): r["n"] for r in by_origin},
            "zero_result_queries": [dict(r) for r in zero], "recent": [dict(r) for r in recent],
            "feedback": {r["rating"]: r["n"] for r in fb}}


DEBUG_ENDPOINTS = {"research-outputs": "normalize_research_output", "persons": "normalize_person",
                   "organizations": "normalize_organization", "data-sets": "normalize_dataset",
                   "student-theses": "normalize_student_thesis", "projects": "normalize_project",
                   "equipment": "normalize_equipment", "external-organizations": "normalize_external_organization"}


@app.get("/debug/directory")
def debug_directory(q: str = "", x_admin_password: str | None = Header(default=None)):
    """How a name is recorded in the bot's staff data: active flag, unit yes/no, appointment years. Admin only."""
    _require_admin(x_admin_password)
    d = khazna_index.DIRECTORY
    if d.persons is None:
        return {"loaded": False}
    hits = d.find_former(q, include_unlisted=True)
    rows = d.persons.set_index("uuid")
    out = []
    for h in hits[:20]:
        r = rows.loc[h["uuid"]]
        r = r.iloc[0] if hasattr(r, "iloc") and getattr(r, "ndim", 1) > 1 else r
        out.append({"name": h["name"], "status": h["status"], "active": None if r.get("active") is None else bool(r.get("active")),
                    "has_unit": bool(r.get("unit")), "start_year": str(r.get("start") or "")[:4],
                    "end_year": str(r.get("end") or "")[:4], "role": r.get("role", "")})
    return {"query": q, "matches": len(hits), "people": out}


@app.get("/debug/persons")
async def debug_persons(q: str = "Kumar", x_admin_password: str | None = Header(default=None)):
    """Why each person returned by Pure for a name is kept or dropped (visibility, staff appointments)."""
    _require_admin(x_admin_password)
    import pure_client
    from datetime import date as _date
    raw = await pure.request("POST", "/persons/search", json={"searchString": q, "size": 50, "offset": 0})
    items = raw.get("items") or []
    field_returned = any("staffOrganizationAssociations" in i for i in items)
    kept_uuids = {p["uuid"] for p in await pure.search_persons(q, size=50)}
    matched, _ = pipeline.match_people(q, [pure_client.normalize_person(i, PURE_PORTAL_URL) for i in items])
    matched_uuids = {p["uuid"] for p in matched}
    today = _date.today().isoformat()
    rows = []
    for i in items:
        vis = i.get("visibility")
        status = pure_client.staff_status(i)
        assocs = []
        for a in i.get("staffOrganizationAssociations") or []:
            per = a.get("period") or {}
            org = a.get("organization") or {}
            assocs.append({
                "organisation": pure_client._loc(org.get("name")) or await pure.organization_name(org.get("uuid", "")) if org.get("uuid") else "",
                "job_title": pure_client._loc(a.get("jobTitle")),
                "start": pure_client._date_parts(per.get("startDate"))[1], "end": pure_client._date_parts(per.get("endDate"))[1],
                "current": pure_client._association_active(a, today)})
        reason = ("not public" if not pure_client.is_public(i) else
                  "no current staff appointment" if status is False else
                  "name does not match" if i.get("uuid") not in matched_uuids else "kept")
        rows.append({"name": pure_client._person_name(i.get("name")), "uuid": i.get("uuid"),
                     "visibility": vis.get("key") if isinstance(vis, dict) else vis,
                     "staff_appointments": assocs,
                     "other_association_fields": [k for k in i if k.endswith("Associations") and k != "staffOrganizationAssociations" and i.get(k)],
                     "kept_by_filter": i.get("uuid") in kept_uuids, "result": reason})
    portal = await pure.portal_person_search(q)
    merged = pipeline.merge_portal_people(portal or [], await pure.search_persons(q, size=50)) if portal is not None else None
    shown_by_bot, _ = pipeline.match_people(q, merged if merged is not None else [])
    return {"query": q, "portal_reachable": portal is not None,
            "portal_people": [{"name": p["name"], "portal_url": p["portal_url"], "api_uuid": p.get("uuid") or None,
                               "shown_by_bot": p in shown_by_bot} for p in (merged or [])],
            "api_count": raw.get("count"), "api_returned": len(items), "staff_field_returned": field_returned,
            "api_people": rows}


@app.get("/debug/pure")
async def debug_pure(q: str = "machine learning", endpoint: str = "research-outputs",

                     x_admin_password: str | None = Header(default=None)):
    """Raw vs normalised first hit for any endpoint β€” verifies field mappings against your Pure version."""
    _require_admin(x_admin_password)
    if endpoint not in DEBUG_ENDPOINTS:
        raise HTTPException(400, f"endpoint must be one of {list(DEBUG_ENDPOINTS)}")
    import pure_client
    try:
        raw = await pure.request("POST", f"/{endpoint}/search", json={"searchString": q, "size": 1, "offset": 0})
    except PureError as e:
        return {"endpoint": endpoint, "error": str(e), "status": e.status}
    items = raw.get("items") or []
    norm = getattr(pure_client, DEBUG_ENDPOINTS[endpoint])
    return {
        "endpoint": endpoint,
        "count": raw.get("count"),
        "raw_first_item": items[0] if items else None,
        "is_public": pure_client.is_public(items[0]) if items else None,
        "normalized": norm(items[0], PURE_PORTAL_URL) if items else None,
    }