File size: 50,956 Bytes
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ac52f8
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ac52f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ec8fd6
1ac52f8
 
 
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ac52f8
 
 
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ac52f8
 
 
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ac52f8
 
 
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271c159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271c159
 
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c119294
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c119294
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c119294
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c119294
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c119294
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c119294
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
#!/usr/bin/env python3
"""
rag_server.py — `copernicus-rag` MCP server: RAG discovery + documentation layer
for Copernicus data, companion to the `copernicus` MCP server (which does the
actual subsetting/downloading).

Two-level flow:
  L0  search_datasets      — find datasets by meaning across ALL 4 stores
                             (CMEMS 1251 + CDS 136 + ADS 16 + EWDS 12 cards)
  L1  get_dataset_docs     — quality/EQC documentation (PUM/QUID/SQO) chunks
                             for a CMEMS product, semantically filtered
      search_docs          — same 29k doc chunks, searched globally
      list_dataset_documents / read_document — pull full doc markdown

Retrieval: Qdrant (embedded, out/qdrant_db) hybrid dense+BM25 with RRF fusion.
Dense query vector = gemini-embedding-2-preview (768-dim); if the embed call
fails (quota/net), we degrade to sparse-only BM25 and say so in the response.
Optional Google semantic-ranker rerank when GCP_PROJECT + ADC are set.

Invariants (mirrors copernicus-mcp): text/descriptors only — no raw scientific
bytes; logging to stderr only; tools never raise — they return {"ok": false}.
"""
from __future__ import annotations

import json
import logging
import os
import sys
import threading
from functools import lru_cache
from pathlib import Path

# stdio transport: stdout is the JSON-RPC channel — pin ALL logging to stderr
# before any library gets a chance to install a stdout handler.
logging.basicConfig(level=logging.WARNING, stream=sys.stderr, force=True)
for _name in ("httpx", "httpcore", "google", "google_genai", "fastembed", "qdrant_client"):
    logging.getLogger(_name).setLevel(logging.WARNING)

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))

import net_ipv4  # noqa: F401  — force IPv4 egress (VPN) before any genai call

from mcp.server.fastmcp import FastMCP
from qdrant_client import QdrantClient, models

import search as S  # embed_query, sparse_query, rerank_google, LOCAL_DB

OUT = ROOT / "out"
CARDS_COLLECTION = "copernicus_docs"   # 1 card per dataset, all 4 stores
DOCS_COLLECTION = "marine_docs"        # PUM/QUID/SQO chunks, CMEMS only
STORES = ("CMEMS", "CDS", "ADS", "EWDS")
DOC_TYPES = ("PUM", "QUID", "SQO", "CARD")
MAX_TEXT = 1600          # per-chunk text cap in tool output
READ_DEFAULT = 20_000    # default read_document window

PUBS_DB = ROOT.parent / "pubs_rag" / "qdrant_db"
PUBS_COLLECTION = "publications"
REGISTRY = ROOT.parent / "publications" / "registry" / "publications.jsonl"
PAPERS = ROOT.parent / "pubs_rag" / "out" / "papers.jsonl"
LINKS_SIDECAR = ROOT.parent / "pubs_rag" / "out" / "links_by_dataset.json"
PUB_DOMAINS = ("ocean/marine", "atmosphere", "cryosphere", "land",
               "climate-modeling", "climate-general", "emergency")

EQC_QA_DB = ROOT.parent / "eqc_qa" / "qdrant_db"
EQC_QA_COLLECTION = "eqc_qa"

# Deep documentation for the non-marine stores (CDS/ADS/EWDS): Confluence user
# guides / ATBDs / PDFs, chunked like marine_docs. Separate DB (own lock).
DEEP_DB = ROOT.parent / "deep_docs" / "qdrant_db"
DEEP_COLLECTION = "cds_docs"

# Notebook code layer: runnable example-notebook code ATTACHED to datasets
# (serve-time join by dataset id — NOT embedded/searched on its own).
NOTEBOOKS_SIDECAR = ROOT.parent / "eqc_qa" / "notebooks_by_dataset.json"

_lock = threading.Lock()
_client: QdrantClient | None = None
_pubs_client: QdrantClient | None = None
_eqc_client: QdrantClient | None = None
_deep_client: QdrantClient | None = None


def _log(msg: str) -> None:
    print(f"[copernicus-rag] {msg}", file=sys.stderr, flush=True)


# ── Qdrant SERVER fast path ─────────────────────────────────────────────────
# If a Qdrant server (server/docker-compose.yml) is reachable and carries the
# needed collection, use it instead of the embedded files: HNSW + payload
# indexes make publications queries ~30 ms vs minutes, and there is no
# single-process lock. Falls back to embedded silently when the server is
# down or lacks the collection. Disable with QDRANT_URL="".
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
_server_client: QdrantClient | None = None
_server_collections: frozenset | None = None


def _server() -> QdrantClient | None:
    global _server_client, _server_collections
    with _lock:
        if _server_collections is None:
            if not QDRANT_URL:
                _server_collections = frozenset()
                return None
            try:
                cl = QdrantClient(url=QDRANT_URL, timeout=30,
                                  check_compatibility=False)
                _server_collections = frozenset(
                    c.name for c in cl.get_collections().collections)
                _server_client = cl
                _log(f"qdrant SERVER at {QDRANT_URL}: "
                     f"{sorted(_server_collections)}")
            except Exception as e:
                _server_collections = frozenset()
                _log(f"qdrant server unreachable ({repr(e)[:60]}) — "
                     "using embedded indexes")
        return _server_client


def _via_server(collection: str) -> QdrantClient | None:
    cl = _server()
    if cl is not None and collection in (_server_collections or ()):
        return cl
    return None


def _qdrant() -> QdrantClient:
    srv = _via_server("marine_docs")
    if srv is not None and _via_server("copernicus_docs") is not None:
        return srv
    global _client
    with _lock:
        if _client is None:
            _log(f"opening embedded Qdrant at {S.LOCAL_DB}")
            try:
                _client = QdrantClient(path=str(S.LOCAL_DB))
            except Exception as e:
                raise RuntimeError(
                    "cannot open marine index (locked by a load script or another "
                    f"server instance? retry when it finishes): {repr(e)[:120]}") from e
        return _client


@lru_cache(maxsize=1)
def _catalog():
    """CMEMS product catalog: by product_id + dataset_id -> product_id map."""
    cat = json.loads((OUT / "catalog.json").read_text())
    by_pid = {c["product_id"]: c for c in cat}
    ds_to_pid = {}
    for c in cat:
        for ds in c.get("dataset_ids", []):
            ds_to_pid[ds.lower()] = c["product_id"]
    return by_pid, ds_to_pid


def resolve_product(any_id: str) -> str | None:
    """Exact product/dataset id, else UNIQUE prefix, else UNIQUE substring.

    Ambiguous fragments (e.g. "006" is contained in 13 product ids) return
    None instead of silently picking an arbitrary product.
    """
    by_pid, ds_to_pid = _catalog()
    if any_id in by_pid:
        return any_id
    low = any_id.lower()
    if not low:
        return None
    if low in ds_to_pid:
        return ds_to_pid[low]
    exact = [pid for pid in by_pid if pid.lower() == low]
    if exact:
        return exact[0]
    starts = [pid for pid in by_pid if pid.lower().startswith(low)]
    if len(starts) == 1:
        return starts[0]
    contains = starts or [pid for pid in by_pid if low in pid.lower()]
    return contains[0] if len(contains) == 1 else None


def _pubs_qdrant() -> QdrantClient | None:
    """Client for the separate publications DB; None until the index is built."""
    srv = _via_server(PUBS_COLLECTION)
    if srv is not None:
        return srv
    global _pubs_client
    with _lock:
        if _pubs_client is None:
            if not PUBS_DB.exists():
                return None
            _log(f"opening embedded Qdrant at {PUBS_DB}")
            try:
                _pubs_client = QdrantClient(path=str(PUBS_DB))
            except Exception as e:
                raise RuntimeError(
                    "cannot open publications index (locked by load_pubs_qdrant.py "
                    f"or another server instance? retry when it finishes): {repr(e)[:120]}") from e
        return _pubs_client


def _pubs_status() -> str:
    """Human-readable build status of the publications index."""
    return ("publications index not on disk yet — PDFs are being downloaded "
            "and VLM-parsed; the collection grows as parses land")


def _eqc_qdrant() -> QdrantClient | None:
    """Client for the CDS/C3S EQC quality-assessment DB; None until built."""
    srv = _via_server(EQC_QA_COLLECTION)
    if srv is not None:
        return srv
    global _eqc_client
    with _lock:
        if _eqc_client is None:
            if not EQC_QA_DB.exists():
                return None
            _log(f"opening embedded Qdrant at {EQC_QA_DB}")
            try:
                _eqc_client = QdrantClient(path=str(EQC_QA_DB))
            except Exception as e:
                raise RuntimeError(
                    "cannot open EQC-QA index (locked by load_eqc_qa.py or another "
                    f"server instance? retry when it finishes): {repr(e)[:120]}") from e
        return _eqc_client


def _deep_qdrant() -> QdrantClient | None:
    """Client for the CDS/ADS/EWDS deep-docs DB; None until built."""
    srv = _via_server(DEEP_COLLECTION)
    if srv is not None:
        return srv
    global _deep_client
    with _lock:
        if _deep_client is None:
            if not DEEP_DB.exists():
                return None
            _log(f"opening embedded Qdrant at {DEEP_DB}")
            try:
                _deep_client = QdrantClient(path=str(DEEP_DB))
            except Exception as e:
                raise RuntimeError(
                    "cannot open deep-docs index (locked by embed_load.py or another "
                    f"server instance? retry when it finishes): {repr(e)[:120]}") from e
        return _deep_client


@lru_cache(maxsize=1)
def _notebooks() -> tuple[dict, dict, dict]:
    """Notebook code recipes attached to datasets (serve-time join, no re-index).

    Returns (by_dataset_id -> [records], by_notebook_id -> record,
    generic_by_store -> [store-level how-to records]). Cached for process
    lifetime: restart the server to pick up newly attached notebooks.
    """
    by_ds: dict = {}
    by_id: dict = {}
    generic: dict = {}
    if NOTEBOOKS_SIDECAR.exists():
        data = json.loads(NOTEBOOKS_SIDECAR.read_text())
        by_ds = data.get("by_dataset", {})
        generic = data.get("generic_by_store", {})
        for recs in by_ds.values():
            for r in recs:
                by_id[r["notebook_id"]] = r
        for recs in generic.values():
            for r in recs:
                by_id.setdefault(r["notebook_id"], r)
    return by_ds, by_id, generic


def _nb_refs(dataset_id: str | None, product_id: str | None = None,
             kind: str | None = None) -> list[dict]:
    """Compact notebook refs attached to a dataset/collection id (for list views)."""
    by_ds, _, _ = _notebooks()
    recs = by_ds.get(dataset_id or "") or by_ds.get(product_id or "") or []
    out = []
    for r in recs:
        if kind and kind not in (r.get("recipe_kinds") or []):
            continue
        out.append({"notebook_id": r["notebook_id"], "title": r.get("title"),
                    "recipe_kinds": r.get("recipe_kinds"),
                    "n_code_lines": r.get("n_code_lines"),
                    "source_repo": r.get("source_repo")})
    return out


_dim_cache: dict[tuple[int, str], int | None] = {}


def _dense_dim_ok(client: QdrantClient, collection: str, qdim: int) -> bool:
    """Guard: the query embedder must match the collection's dense dim.

    A local EMBED_MODEL (e.g. 384-d bge-small) against the gemini-768 corpus
    would silently return garbage — degrade to BM25-only and say why once.
    """
    key = (id(client), collection)
    if key not in _dim_cache:
        try:
            vecs = client.get_collection(collection).config.params.vectors
            _dim_cache[key] = getattr(vecs.get("dense"), "size", None) \
                if isinstance(vecs, dict) else getattr(vecs, "size", None)
        except Exception:
            _dim_cache[key] = None
    cdim = _dim_cache[key]
    if cdim is None or cdim == qdim:
        return True
    _log(f"EMBED_MODEL dim {qdim} != '{collection}' dense dim {cdim} — "
         "BM25-only (re-embed the corpus with this model, or unset EMBED_MODEL)")
    return False


def _query(collection: str, query: str, flt: models.Filter | None,
           top_k: int, prefetch: int = 50, client: QdrantClient | None = None):
    """Hybrid dense+sparse RRF; degrades to sparse-only if dense embed fails.

    Only the embed call may trigger the fallback (SystemExit included: a
    missing API key must not kill the server); Qdrant errors propagate to
    the caller so they are reported as what they are.

    Returns (points, retrieval_mode).
    """
    client = client or _qdrant()
    sparse_vec = S.sparse_query(query)
    dense_vec = None
    try:
        dense_vec = S.embed_query(query)
    except (Exception, SystemExit) as e:
        _log(f"dense embed unavailable ({repr(e)[:120]}); sparse-only fallback")
    if dense_vec is not None and not _dense_dim_ok(client, collection, len(dense_vec)):
        dense_vec = None  # wrong embedder for this corpus — sparse-only
    if dense_vec is not None:
        res = client.query_points(
            collection_name=collection,
            prefetch=[
                models.Prefetch(query=dense_vec, using="dense", limit=prefetch, filter=flt),
                models.Prefetch(query=sparse_vec, using="sparse", limit=prefetch, filter=flt),
            ],
            query=models.FusionQuery(fusion=models.Fusion.RRF),
            limit=top_k, with_payload=True,
        )
        return res.points, "hybrid(dense+bm25)"
    res = client.query_points(
        collection_name=collection, query=sparse_vec, using="sparse",
        limit=top_k, with_payload=True, query_filter=flt,
    )
    return res.points, "bm25-only (dense embed unavailable)"


def _maybe_rerank(query: str, points, top_k: int, rerank: bool):
    if not rerank or not points:
        return points, False
    rr = S.rerank_google(query, points, top_k)
    return (rr, True) if rr is not None else (points, False)


def _err(msg: str, **extra) -> dict:
    return {"ok": False, "error": msg, **extra}


mcp = FastMCP("copernicus-rag")


@mcp.tool()
def search_datasets(query: str, store: str | None = None, top_k: int = 10,
                    rerank: bool = True) -> dict:
    """Semantic (RAG) search for Copernicus datasets by description, across all
    four data stores: CMEMS (marine), CDS (climate/ERA5), ADS (atmosphere),
    EWDS (emergency/flood/fire). One card per dataset (~1415 total).

    Use this FIRST to discover which dataset to work with. Then, for CMEMS
    results, call get_dataset_docs(product_id) to read its quality (EQC)
    documentation before analyzing data.

    Args:
        query: natural-language description of the data you need
               (e.g. "daily arctic sea ice concentration satellite").
        store: optional filter — one of CMEMS, CDS, ADS, EWDS.
        top_k: number of datasets to return (default 10).
        rerank: also rerank with Google semantic-ranker (needs GCP ADC).
    """
    try:
        if store:
            store = store.upper()
            if store not in STORES:
                return _err(f"unknown store '{store}'", valid_stores=list(STORES))
        top_k = max(1, min(int(top_k), 30))
        flt = models.Filter(must=[models.FieldCondition(
            key="store", match=models.MatchValue(value=store))]) if store else None
        points, mode = _query(CARDS_COLLECTION, query, flt, max(top_k, 20))
        points, reranked = _maybe_rerank(query, points, top_k, rerank)
        by_pid, _ = _catalog()
        results = []
        for p in points[:top_k]:
            pl = p.payload
            pid = pl.get("product_id", "")
            has_docs = bool(by_pid.get(pid, {}).get("has_docs"))
            results.append({
                "store": pl.get("store"),
                "dataset_id": pl.get("dataset_id"),
                "product_id": pid,
                "title": pl.get("product_title"),
                "description": (pl.get("text_raw") or "")[:MAX_TEXT],
                "has_eqc_docs": has_docs,
                "notebooks": _nb_refs(pl.get("dataset_id"), pid),
                "score": getattr(p, "score", None),
            })
        return {"ok": True, "query": query, "store": store or "ALL",
                "retrieval": mode, "reranked": reranked,
                "n_results": len(results), "results": results,
                "next_step": ("for CMEMS hits call get_dataset_docs(product_id) "
                              "to read quality docs; where a hit has notebooks[], "
                              "call get_dataset_code(dataset_id) for runnable code")}
    except Exception as e:
        _log(f"search_datasets failed: {repr(e)}")
        return _err(f"search failed: {repr(e)[:200]}")


def _deep_dataset_docs(dataset_id: str, question: str | None,
                       top_k: int, rerank: bool) -> dict | None:
    """Deep CDS/ADS/EWDS documentation (cds_docs) for a collection id.
    Returns a result dict, or None if the deep index is unavailable / has no
    match for this id (so the caller can fall through to 'unknown id')."""
    client = _deep_qdrant()
    if client is None:
        return None
    top_k = max(1, min(int(top_k), 20))
    q = question or (f"{dataset_id} documentation: variables, methodology, accuracy, "
                     "validation, how to use and interpret this dataset")
    must = [models.FieldCondition(key="dataset_ids", match=models.MatchValue(value=dataset_id))]
    points, mode = _query(DEEP_COLLECTION, q, models.Filter(must=must),
                          max(top_k, 20), prefetch=40, client=client)
    if not points:
        return None
    points, reranked = _maybe_rerank(q, points, top_k, rerank)
    results = [{
        "store": p.payload.get("store"),
        "doc_title": p.payload.get("doc_title"),
        "doc_url": p.payload.get("doc_url"),
        "section": p.payload.get("section"),
        "text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
        "score": getattr(p, "score", None),
    } for p in points[:top_k]]
    return {"ok": True, "dataset_id": dataset_id, "layer": "deep_docs (CDS/ADS/EWDS)",
            "query": q, "retrieval": mode, "reranked": reranked,
            "n_results": len(results), "results": results,
            "notebooks": _nb_refs(dataset_id, dataset_id),
            "next_step": ("get_eqc_quality_report(dataset_id) for quality assessment; "
                          "get_dataset_code(dataset_id) for runnable code")}


@mcp.tool()
def get_dataset_docs(dataset_or_product_id: str, question: str | None = None,
                     doc_type: str | None = None, top_k: int = 8,
                     rerank: bool = True) -> dict:
    """Level-2 EQC lookup: retrieve the quality/usage documentation chunks
    (PUM = Product User Manual, QUID = Quality Information Document,
    SQO = Scientific Quality Overview) for one CMEMS product or dataset.

    Call this AFTER search_datasets, BEFORE analyzing data: it tells you the
    variables, units, spatial/temporal coverage, accuracy, validation results
    and known caveats — i.e. how to interpret the numbers you will pull.

    Args:
        dataset_or_product_id: CMEMS product_id or dataset_id
            (e.g. "MEDSEA_ANALYSISFORECAST_PHY_006_013" or a dataset id).
        question: optional focus (e.g. "salinity validation accuracy");
            default surfaces the how-to-analyze essentials.
        doc_type: optional filter — PUM, QUID or SQO.
        top_k: number of doc chunks to return (default 8).
        rerank: also rerank with Google semantic-ranker (needs GCP ADC).
    """
    try:
        pid = resolve_product(dataset_or_product_id)
        if not pid:
            deep = _deep_dataset_docs(dataset_or_product_id, question, top_k, rerank)
            if deep is not None:
                return deep
            return _err(f"unknown dataset/product id: {dataset_or_product_id}",
                        hint="use an id returned by search_datasets")
        by_pid, _ = _catalog()
        prod = by_pid[pid]
        if doc_type:
            doc_type = doc_type.upper()
            if doc_type not in DOC_TYPES:
                return _err(f"unknown doc_type '{doc_type}'", valid=list(DOC_TYPES))
        top_k = max(1, min(int(top_k), 20))
        q = question or (f"{prod['product_title']} variables, spatial and temporal "
                         "coverage, accuracy, validation, how to use and interpret "
                         "this product")
        must = [models.FieldCondition(key="product_id", match=models.MatchValue(value=pid))]
        if doc_type:
            must.append(models.FieldCondition(key="doc_type", match=models.MatchValue(value=doc_type)))
        points, mode = _query(DOCS_COLLECTION, q, models.Filter(must=must), max(top_k, 20), prefetch=40)
        points, reranked = _maybe_rerank(q, points, top_k, rerank)
        results = [{
            "doc_type": p.payload.get("doc_type"),
            "doc_id": p.payload.get("doc_id"),
            "section": p.payload.get("section_path"),
            "text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
            "score": getattr(p, "score", None),
        } for p in points[:top_k]]
        return {"ok": True, "product_id": pid, "product_title": prod["product_title"],
                "matched_by": "product_id" if dataset_or_product_id == pid else "dataset_id/fuzzy",
                "doc_types_available": prod.get("doc_types", []),
                "dataset_ids": prod.get("dataset_ids", []),
                "query": q, "retrieval": mode, "reranked": reranked,
                "n_results": len(results), "results": results,
                "next_step": ("read_document(doc_id) pulls a full document; "
                              "then subset data via the copernicus MCP server")}
    except Exception as e:
        _log(f"get_dataset_docs failed: {repr(e)}")
        return _err(f"lookup failed: {repr(e)[:200]}")


@mcp.tool()
def search_docs(query: str, doc_type: str | None = None, top_k: int = 8,
                rerank: bool = True) -> dict:
    """Global semantic search across ALL CMEMS quality documentation
    (~29k chunks of PUM/QUID/SQO for 306 products), not limited to one product.

    Use for cross-product questions like "which products are validated against
    Argo floats" or "sea level trend uncertainty methodology".

    Args:
        query: natural-language question.
        doc_type: optional filter — PUM, QUID or SQO.
        top_k: number of chunks to return (default 8).
        rerank: also rerank with Google semantic-ranker (needs GCP ADC).
    """
    try:
        if doc_type:
            doc_type = doc_type.upper()
            if doc_type not in DOC_TYPES:
                return _err(f"unknown doc_type '{doc_type}'", valid=list(DOC_TYPES))
        top_k = max(1, min(int(top_k), 20))
        flt = models.Filter(must=[models.FieldCondition(
            key="doc_type", match=models.MatchValue(value=doc_type))]) if doc_type else None
        points, mode = _query(DOCS_COLLECTION, query, flt, max(top_k, 20))
        points, reranked = _maybe_rerank(query, points, top_k, rerank)
        results = [{
            "product_id": p.payload.get("product_id"),
            "product_title": p.payload.get("product_title"),
            "doc_type": p.payload.get("doc_type"),
            "doc_id": p.payload.get("doc_id"),
            "section": p.payload.get("section_path"),
            "text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
            "score": getattr(p, "score", None),
        } for p in points[:top_k]]
        return {"ok": True, "query": query, "retrieval": mode, "reranked": reranked,
                "n_results": len(results), "results": results}
    except Exception as e:
        _log(f"search_docs failed: {repr(e)}")
        return _err(f"search failed: {repr(e)[:200]}")


@mcp.tool()
def list_dataset_documents(dataset_or_product_id: str) -> dict:
    """List the full EQC documents available for a CMEMS product/dataset:
    doc_id, type (PUM/QUID/SQO) and size. Feed a doc_id to read_document
    to pull the complete text.

    Args:
        dataset_or_product_id: CMEMS product_id or dataset_id.
    """
    try:
        pid = resolve_product(dataset_or_product_id)
        if not pid:
            return _err(f"unknown dataset/product id: {dataset_or_product_id}")
        by_pid, _ = _catalog()
        prod = by_pid[pid]
        docs = [{"doc_id": d["doc_id"], "doc_type": d["doc_type"],
                 "size_bytes": d.get("md_bytes"), "available": d.get("has_md", False)}
                for d in prod.get("docs", [])]
        return {"ok": True, "product_id": pid, "product_title": prod["product_title"],
                "dataset_ids": prod.get("dataset_ids", []),
                "doi": prod.get("doi"), "regions": prod.get("regions", []),
                "domains": prod.get("domains", []),
                "n_documents": len(docs), "documents": docs}
    except Exception as e:
        _log(f"list_dataset_documents failed: {repr(e)}")
        return _err(f"lookup failed: {repr(e)[:200]}")


@lru_cache(maxsize=1)
def _unified_meta() -> dict:
    """Full harvested upstream metadata, all 4 stores (meta_harvest)."""
    path = ROOT.parent / "meta_harvest" / "unified_metadata.json"
    return json.loads(path.read_text()) if path.exists() else {}


@mcp.tool()
def dataset_metadata(dataset_or_collection_id: str) -> dict:
    """FULL harvested metadata for one dataset (any store) — much richer than
    the card returned by search_datasets: variables with units/standard_name/
    bbox/depth/time ranges, services, processing level, production centre,
    update frequency, documentation links, scientific references, licence.

    Use before subsetting data: it tells you exact variable names, units and
    coverage bounds. Accepts a CMEMS dataset_id, a CDS/ADS/EWDS collection id,
    or a CMEMS product_id (then lists the product's datasets).

    Args:
        dataset_or_collection_id: e.g. "antarctic_omi_si_extent",
            "reanalysis-era5-single-levels", or a CMEMS product_id.
    """
    try:
        meta = _unified_meta()
        if not meta:
            return _err("unified_metadata.json not found — run the meta_harvest pipeline")
        key = dataset_or_collection_id
        entry = meta.get(key) or meta.get(key.lower())
        if entry is None:
            # maybe a CMEMS product_id → group its datasets
            low = key.lower()
            members = {k: v for k, v in meta.items()
                       if (v.get("product_id") or "").lower() == low}
            if members:
                first = next(iter(members.values()))
                return {"ok": True, "matched_by": "product_id",
                        "product_id": first.get("product_id"),
                        "title": first.get("title"), "doi": first.get("doi"),
                        "store": first.get("store"),
                        "n_datasets": len(members),
                        "dataset_ids": sorted(members),
                        "next_step": "call dataset_metadata with one dataset_id"}
            close = [k for k in meta if low in k.lower()][:10]
            return _err(f"unknown id: {key}",
                        similar_ids=close,
                        hint="use ids from search_datasets / list_dataset_documents")
        out = dict(entry)
        out["dataset_id"] = key if key in meta else key.lower()
        for field, cap in (("variables", 120), ("references", 30),
                           ("documentation_links", 40), ("keywords", 40)):
            v = out.get(field)
            if isinstance(v, list) and len(v) > cap:
                out[field] = v[:cap]
                out[f"{field}_truncated"] = f"{len(v) - cap} more omitted"
        return {"ok": True, "matched_by": "dataset_id", **out}
    except Exception as e:
        _log(f"dataset_metadata failed: {repr(e)}")
        return _err(f"lookup failed: {repr(e)[:200]}")


@lru_cache(maxsize=1)
def _doc_index() -> dict:
    """doc_id -> absolute md path, from the catalog."""
    by_pid, _ = _catalog()
    idx = {}
    for prod in by_pid.values():
        for d in prod.get("docs", []):
            if d.get("has_md") and d.get("md_path"):
                idx[d["doc_id"]] = ROOT.parent / d["md_path"]
    return idx


@mcp.tool()
def read_document(doc_id: str, offset: int = 0, max_chars: int = READ_DEFAULT) -> dict:
    """Pull the full markdown text of one EQC document (PUM/QUID/SQO), paginated.
    Get doc_id from list_dataset_documents or from get_dataset_docs results.
    The first page includes an outline (headings + char offsets) so you can jump
    straight to a section with the offset argument.

    Args:
        doc_id: e.g. "CMEMS-MED-QUID-006-013".
        offset: character offset to start from (default 0).
        max_chars: page size (default 20000, max 60000).
    """
    try:
        path = _doc_index().get(doc_id)
        if path is None:
            return _err(f"unknown doc_id: {doc_id}",
                        hint="use list_dataset_documents to get valid doc_ids")
        if not path.exists():
            return _err(f"document file missing on disk: {path.name}")
        text = path.read_text(encoding="utf-8", errors="replace")
        offset = max(0, int(offset))
        max_chars = max(1000, min(int(max_chars), 60_000))
        page = text[offset:offset + max_chars]
        out = {"ok": True, "doc_id": doc_id, "total_chars": len(text),
               "offset": offset, "returned_chars": len(page),
               "next_offset": offset + len(page) if offset + len(page) < len(text) else None,
               "text": page}
        if offset == 0:
            outline, pos = [], 0
            for line in text.splitlines(keepends=True):
                if line.startswith("#"):
                    outline.append({"heading": line.strip()[:120], "offset": pos})
                pos += len(line)
            out["outline"] = outline[:60]
        return out
    except Exception as e:
        _log(f"read_document failed: {repr(e)}")
        return _err(f"read failed: {repr(e)[:200]}")


@lru_cache(maxsize=1)
def _registry() -> list[dict]:
    # cached for process lifetime: restart server to pick up registry updates
    if not REGISTRY.exists():
        return []
    return [json.loads(l) for l in REGISTRY.read_text().splitlines() if l.strip()]


@lru_cache(maxsize=1)
def _links_by_dataset() -> dict:
    # dataset_id -> [paper records] materialized by pubs_rag/build_links_sidecar.py
    # (registry direct + flagship citations, same logic as relink_full.py)
    if not LINKS_SIDECAR.exists():
        return {}
    return json.loads(LINKS_SIDECAR.read_text(encoding="utf-8"))


@lru_cache(maxsize=1)
def _papers_by_id() -> dict:
    """Orphan-corpus parsed papers: paper_id and doi -> record with md_path.

    Cached for process lifetime (like _registry): restart to pick up new papers.
    """
    idx = {}
    if PAPERS.exists():
        for line in PAPERS.read_text().splitlines():
            if not line.strip():
                continue
            p = json.loads(line)
            idx[p["paper_id"]] = p
            if p.get("doi"):
                idx[p["doi"].lower()] = p
    return idx


@mcp.tool()
def search_publications(query: str, domain: str | None = None,
                        dataset_or_product_id: str | None = None,
                        orphan_only: bool = False, top_k: int = 8,
                        rerank: bool = True) -> dict:
    """Level-3 METHODOLOGY search: semantic search over the scientific
    publications RAG (parsed full-text paper chunks). Use it to learn HOW to
    analyze data: methods, validation approaches, known analysis pitfalls.

    Args:
        query: natural-language question (e.g. "how to compute ocean heat
            content trends from reanalysis").
        domain: optional filter — one of ocean/marine, atmosphere, cryosphere,
            land, climate-modeling, climate-general, emergency.
        dataset_or_product_id: only papers LINKED to this Copernicus
            product/collection (cited in its documentation).
        orphan_only: only the general (non-dataset-linked) methodology corpus.
        top_k: number of chunks to return (default 8).
        rerank: also rerank with Google semantic-ranker (needs GCP ADC).
    """
    try:
        client = _pubs_qdrant()
        if client is None:
            return _err("publications index not built yet", status=_pubs_status())
        if domain and domain not in PUB_DOMAINS:
            return _err(f"unknown domain '{domain}'", valid=list(PUB_DOMAINS))
        top_k = max(1, min(int(top_k), 20))
        must = []
        if domain:
            must.append(models.FieldCondition(key="domains", match=models.MatchValue(value=domain)))
        if orphan_only:
            must.append(models.FieldCondition(key="orphan", match=models.MatchValue(value=True)))
        if dataset_or_product_id:
            pid = resolve_product(dataset_or_product_id) or dataset_or_product_id
            must.append(models.FieldCondition(key="linked_products", match=models.MatchValue(value=pid)))
        flt = models.Filter(must=must) if must else None
        points, mode = _query(PUBS_COLLECTION, query, flt, max(top_k, 20), client=client)
        points, reranked = _maybe_rerank(query, points, top_k, rerank)
        results = [{
            "doi": p.payload.get("doi"),
            "title": p.payload.get("title"),
            "journal": p.payload.get("journal"),
            "year": p.payload.get("year"),
            "domains": p.payload.get("domains"),
            "section": p.payload.get("section"),
            "orphan": p.payload.get("orphan"),
            "linked_products": (p.payload.get("linked_products") or [])[:8],
            "text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
            "score": getattr(p, "score", None),
        } for p in points[:top_k]]
        return {"ok": True, "query": query, "retrieval": mode, "reranked": reranked,
                "n_results": len(results), "results": results,
                "next_step": "read_publication(doi) pulls a paper's full parsed text"}
    except Exception as e:
        _log(f"search_publications failed: {repr(e)}")
        return _err(f"search failed: {repr(e)[:200]}")


@mcp.tool()
def get_dataset_publications(dataset_or_product_id: str, top_k: int = 15) -> dict:
    """List the scientific publications LINKED to one Copernicus dataset —
    i.e. papers cited in its quality documentation (CMEMS PUM/QUID/SQO) or on
    its CDS/ADS/EWDS references section. This is the dataset's literature:
    validation papers, method papers, foundational references.

    Args:
        dataset_or_product_id: CMEMS product/dataset id or CDS/ADS/EWDS
            collection id.
        top_k: max publications to return (default 15), most-cited first.
    """
    try:
        pid = resolve_product(dataset_or_product_id) or dataset_or_product_id
        low = {pid.lower(), dataset_or_product_id.lower()}
        parsed = _papers_by_id()

        # primary: materialized links sidecar (registry direct + flagship citers)
        seen: set[str] = set()
        merged: list[dict] = []
        by_ds = _links_by_dataset()
        for ds, recs in by_ds.items():
            if ds.lower() not in low:
                continue
            for r in recs:
                doi = (r.get("doi") or "").lower()
                if doi in seen:
                    continue
                seen.add(doi)
                merged.append({
                    "doi": r.get("doi"), "title": r.get("title"),
                    "journal": r.get("journal"), "year": r.get("year"),
                    "citations_count": r.get("cited_by_count"),
                    "link_via": r.get("via"),
                    "flagship_labels": r.get("flagship_labels") or None,
                    "full_text_available": doi in parsed,
                })

        # secondary: registry papers not in the parsed corpus (metadata-only)
        for r in _registry():
            doi = (r.get("doi") or "").lower()
            if doi in seen:
                continue
            if not any((p or "").lower() in low for p in r.get("linked_products", [])):
                continue
            seen.add(doi)
            merged.append({
                "doi": r["doi"], "title": r.get("title"),
                "journal": r.get("journal"), "year": r.get("year"),
                "authors": (r.get("authors") or [])[:6],
                "n_mentions": r.get("n_mentions"),
                "citations_count": r.get("citations_count"),
                "pdf_status": r.get("pdf_status"),
                "link_via": ["registry"],
                "full_text_available": doi in parsed,
            })

        merged.sort(key=lambda r: (-int(bool(r.get("full_text_available"))),
                                   -(r.get("citations_count") or 0)))
        results = merged[:max(1, min(int(top_k), 50))]
        return {"ok": True, "id": pid, "n_linked_publications": len(merged),
                "results": results,
                "next_step": ("read_publication(doi) for full text where "
                              "full_text_available; otherwise metadata only for now")}
    except Exception as e:
        _log(f"get_dataset_publications failed: {repr(e)}")
        return _err(f"lookup failed: {repr(e)[:200]}")


@mcp.tool()
def read_publication(doi_or_paper_id: str, offset: int = 0,
                     max_chars: int = READ_DEFAULT) -> dict:
    """Pull the full parsed markdown text of one publication, paginated
    (same contract as read_document: page 0 includes a heading outline).
    Works for papers in the parsed corpus; for registry papers whose PDF is
    not parsed yet it returns their metadata + abstract instead.

    Args:
        doi_or_paper_id: canonical DOI ("10.x/...") or underscored paper_id.
        offset: character offset (default 0).
        max_chars: page size (default 20000, max 60000).
    """
    try:
        key = doi_or_paper_id.strip()
        paper = _papers_by_id().get(key) or _papers_by_id().get(key.lower())
        if paper and paper.get("md_path") and Path(paper["md_path"]).exists():
            text = Path(paper["md_path"]).read_text(encoding="utf-8", errors="replace")
            offset = max(0, int(offset))
            max_chars = max(1000, min(int(max_chars), 60_000))
            page = text[offset:offset + max_chars]
            out = {"ok": True, "doi": paper.get("doi"), "title": paper.get("title"),
                   "journal": paper.get("journal"), "year": paper.get("year"),
                   "total_chars": len(text), "offset": offset,
                   "returned_chars": len(page),
                   "next_offset": offset + len(page) if offset + len(page) < len(text) else None,
                   "text": page}
            if offset == 0:
                outline, pos = [], 0
                for line in text.splitlines(keepends=True):
                    if line.startswith("#"):
                        outline.append({"heading": line.strip()[:120], "offset": pos})
                    pos += len(line)
                out["outline"] = outline[:60]
            return out
        # not parsed — fall back to registry metadata
        low = key.lower()
        rec = next((r for r in _registry() if r["doi"].lower() == low), None)
        if rec:
            return {"ok": True, "full_text": False,
                    "reason": f"not parsed yet (pdf_status: {rec.get('pdf_status')})",
                    "doi": rec["doi"], "title": rec.get("title"),
                    "journal": rec.get("journal"), "year": rec.get("year"),
                    "authors": rec.get("authors"), "abstract": rec.get("abstract"),
                    "linked_products": (rec.get("linked_products") or [])[:15]}
        return _err(f"unknown publication: {key}",
                    hint="use a DOI from search_publications / get_dataset_publications")
    except Exception as e:
        _log(f"read_publication failed: {repr(e)}")
        return _err(f"read failed: {repr(e)[:200]}")


@mcp.tool()
def get_eqc_quality_report(query: str, dataset_id: str | None = None,
                           aspect: str | None = None, top_k: int = 8,
                           rerank: bool = True) -> dict:
    """CDS/C3S EQC Quality Assessment reports — the curated fitness-for-purpose
    assessments (consistency, completeness, etc.) for ~27 climate datasets that
    carry the "Quality Assurance" badge in the CDS catalogue. Use this to judge
    whether a CDS/ADS/EWDS dataset is suitable for a use case, to compare
    alternative datasets on quality criteria, or to surface known limitations.

    Complements get_dataset_docs (which serves CMEMS Marine PUM/QUID/SQO):
    this tool serves the CDS-side quality knowledge.

    Args:
        query: natural-language question (e.g. "is the C3S atlas temperature
            consistent across origins", "completeness of satellite soil moisture").
        dataset_id: optional filter — a CDS collection id (e.g.
            "multi-origin-c3s-atlas", "satellite-sea-surface-temperature").
        aspect: optional filter — quality aspect prefix (e.g. "consistency",
            "completeness").
        top_k: number of report chunks to return (default 8).
        rerank: also rerank with Google semantic-ranker (needs GCP ADC).
    """
    try:
        client = _eqc_qdrant()
        if client is None:
            return _err("EQC-QA index not built yet",
                        status="CDS quality-assessment reports are being embedded "
                               "and indexed — retry shortly")
        top_k = max(1, min(int(top_k), 20))
        must = []
        if dataset_id:
            must.append(models.FieldCondition(key="dataset_id",
                                              match=models.MatchValue(value=dataset_id)))
        if aspect:
            must.append(models.FieldCondition(key="aspect_base",
                                              match=models.MatchValue(value=aspect.lower())))
        flt = models.Filter(must=must) if must else None
        points, mode = _query(EQC_QA_COLLECTION, query, flt, max(top_k, 20), client=client)
        points, reranked = _maybe_rerank(query, points, top_k, rerank)
        results = [{
            "dataset_id": p.payload.get("dataset_id"),
            "report_id": p.payload.get("report_id"),
            "aspect": p.payload.get("aspect"),
            "title": p.payload.get("title"),
            "section": p.payload.get("section"),
            "text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
            "code_notebooks": _nb_refs(p.payload.get("dataset_id")),
            "score": getattr(p, "score", None),
        } for p in points[:top_k]]
        return {"ok": True, "query": query, "retrieval": mode, "reranked": reranked,
                "n_results": len(results), "results": results,
                "source": "c3s2-eqc-quality-assessment (CDS EQC QA reports)",
                "next_step": ("where a result has code_notebooks[], call "
                              "get_dataset_code(dataset_id, notebook_id=...) for the runnable code")}
    except Exception as e:
        _log(f"get_eqc_quality_report failed: {repr(e)}")
        return _err(f"lookup failed: {repr(e)[:200]}")


@mcp.tool()
def get_dataset_code(dataset_id: str, notebook_id: str | None = None,
                     kind: str | None = None, offset: int = 0,
                     max_chars: int = READ_DEFAULT) -> dict:
    """Runnable CODE examples (Jupyter notebook cells) ATTACHED to a Copernicus
    dataset: how to DOWNLOAD and ANALYZE it. Code is not embedded/searched on its
    own — it rides along on the dataset, sourced from official example notebooks
    (e.g. the C3S EQC quality-assessment notebooks). Reach it from a
    search_datasets / get_eqc_quality_report hit whose notebooks[] is non-empty.

    Two modes:
      • dataset_id only  -> LIST the notebooks attached to that dataset (id, title,
        recipe kinds download/analyze/plot, size, source repo + licence).
      • + notebook_id    -> the FULL reconstructed notebook (verbatim ```python
        cells + markdown + text outputs), paginated like read_document.

    Args:
        dataset_id: a CDS/ADS/EWDS collection id or CMEMS product/dataset id
            (e.g. "satellite-sea-surface-temperature", "projections-cmip6").
        notebook_id: pull one notebook's full code (from the list mode).
        kind: optional filter for list mode — download, analyze or plot.
        offset: character offset for the full-notebook mode (default 0).
        max_chars: page size for the full-notebook mode (default 20000, max 60000).
    """
    try:
        by_ds, by_id, generic = _notebooks()
        if not by_ds and not generic:
            return _err("notebook code layer not built yet",
                        status="example notebooks are being extracted and attached")
        if notebook_id:
            rec = by_id.get(notebook_id)
            if not rec:
                return _err(f"unknown notebook_id: {notebook_id}",
                            hint="call get_dataset_code(dataset_id) to list attached notebooks")
            path = ROOT.parent / rec["md_path"]
            if not path.exists():
                return _err(f"notebook file missing on disk: {path.name}")
            text = path.read_text(encoding="utf-8", errors="replace")
            offset = max(0, int(offset))
            max_chars = max(1000, min(int(max_chars), 60_000))
            page = text[offset:offset + max_chars]
            return {"ok": True, "notebook_id": notebook_id, "title": rec.get("title"),
                    "dataset_id": rec.get("matched_dataset_id"), "store": rec.get("store"),
                    "recipe_kinds": rec.get("recipe_kinds"),
                    "source_repo": rec.get("source_repo"), "license": rec.get("license"),
                    "src_path": rec.get("src_path"),
                    "total_chars": len(text), "offset": offset,
                    "returned_chars": len(page),
                    "next_offset": offset + len(page) if offset + len(page) < len(text) else None,
                    "text": page}
        # list mode — dataset-specific notebooks + a store-level generic how-to fallback
        recs = by_ds.get(dataset_id) or by_ds.get(dataset_id.lower())
        if not recs:
            pid = resolve_product(dataset_id)
            if pid:
                recs = by_ds.get(pid)
        recs = recs or []
        store = next((r.get("store") for r in recs if r.get("store")), None)
        if not store:
            store = "CMEMS" if resolve_product(dataset_id) else None

        def _brief(r, scope):
            return {"notebook_id": r["notebook_id"], "title": r.get("title"),
                    "scope": scope, "recipe_kinds": r.get("recipe_kinds"),
                    "n_code_cells": r.get("n_code_cells"),
                    "n_code_lines": r.get("n_code_lines"), "aspect": r.get("aspect"),
                    "source_repo": r.get("source_repo"), "license": r.get("license")}

        notebooks = [_brief(r, "dataset") for r in recs
                     if not kind or kind in (r.get("recipe_kinds") or [])]
        generic_how_to = [_brief(r, "generic") for r in (generic.get(store) or [])
                          if not kind or kind in (r.get("recipe_kinds") or [])]
        if not notebooks and not generic_how_to:
            return _err(f"no notebooks attached to '{dataset_id}'",
                        hint="notebooks cover CDS/ADS/EWDS + CMEMS example datasets",
                        example_ids=sorted(by_ds)[:12])
        return {"ok": True, "dataset_id": dataset_id, "store": store,
                "n_notebooks": len(notebooks), "notebooks": notebooks,
                "generic_how_to": generic_how_to,
                "next_step": ("call get_dataset_code(dataset_id, notebook_id=...) "
                              "for one notebook's full runnable code")}
    except Exception as e:
        _log(f"get_dataset_code failed: {repr(e)}")
        return _err(f"lookup failed: {repr(e)[:200]}")


@mcp.tool()
def search_deep_docs(query: str, store: str | None = None, top_k: int = 8,
                     rerank: bool = True) -> dict:
    """Global semantic search across the DEEP documentation of the non-marine
    stores — CDS (climate/ERA5), ADS (atmosphere/CAMS), EWDS (emergency/flood/
    fire): Confluence user guides, ATBDs, product specs and PDFs (~23k chunks
    over 165 datasets). The non-marine counterpart to search_docs (which covers
    CMEMS PUM/QUID/SQO). Use for cross-dataset climate/atmosphere/emergency
    questions ("ERA5-Land soil moisture accuracy", "CAMS aerosol assimilation").

    Args:
        query: natural-language question.
        store: optional filter — CDS, ADS or EWDS.
        top_k: number of chunks to return (default 8).
        rerank: also rerank with Google semantic-ranker (needs GCP ADC).
    """
    try:
        client = _deep_qdrant()
        if client is None:
            return _err("deep-docs index not built yet",
                        status="CDS/ADS/EWDS documentation is being fetched, chunked "
                               "and embedded — retry shortly")
        if store:
            store = store.upper()
            if store not in ("CDS", "ADS", "EWDS"):
                return _err(f"unknown store '{store}'", valid=["CDS", "ADS", "EWDS"])
        top_k = max(1, min(int(top_k), 20))
        flt = models.Filter(must=[models.FieldCondition(
            key="store", match=models.MatchValue(value=store))]) if store else None
        points, mode = _query(DEEP_COLLECTION, query, flt, max(top_k, 20), client=client)
        points, reranked = _maybe_rerank(query, points, top_k, rerank)
        results = [{
            "store": p.payload.get("store"),
            "dataset_ids": (p.payload.get("dataset_ids") or [])[:6],
            "doc_title": p.payload.get("doc_title"),
            "doc_url": p.payload.get("doc_url"),
            "section": p.payload.get("section"),
            "text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
            "score": getattr(p, "score", None),
        } for p in points[:top_k]]
        return {"ok": True, "query": query, "store": store or "CDS/ADS/EWDS",
                "retrieval": mode, "reranked": reranked,
                "n_results": len(results), "results": results}
    except Exception as e:
        _log(f"search_deep_docs failed: {repr(e)}")
        return _err(f"search failed: {repr(e)[:200]}")


if __name__ == "__main__":
    _log("starting copernicus-rag MCP server (stdio)")
    mcp.run()