File size: 46,384 Bytes
0cfdea5
7a064ce
 
 
fc3bf2a
7a064ce
 
 
 
 
 
fc3bf2a
7a064ce
 
 
 
 
45abfac
fc3bf2a
45abfac
fc3bf2a
34d9afb
fc3bf2a
 
c565f55
fc3bf2a
 
7a064ce
 
fc3bf2a
 
7a064ce
 
0cfdea5
fc3bf2a
7a064ce
 
 
 
 
 
 
 
fc3bf2a
 
 
7a064ce
 
fc3bf2a
 
 
 
7a064ce
 
 
 
 
 
 
 
 
fc3bf2a
 
34d9afb
 
 
 
 
7a064ce
 
fc3bf2a
 
 
 
7a064ce
 
fc3bf2a
 
 
 
 
7a064ce
fc3bf2a
20930c0
0cfdea5
 
 
 
 
 
 
 
 
 
7a064ce
 
20930c0
7a064ce
 
20930c0
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cfdea5
7a064ce
 
 
 
 
 
 
 
 
 
 
 
0cfdea5
 
 
7a064ce
34d9afb
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
7a064ce
 
 
 
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
 
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
34d9afb
 
 
 
7a064ce
 
 
 
 
 
20930c0
 
ca2ea72
7a064ce
ca2ea72
7a064ce
 
ca2ea72
7a064ce
 
ca2ea72
 
 
7a064ce
 
 
20930c0
 
7a064ce
 
 
 
 
fc3bf2a
 
7a064ce
 
 
 
 
 
 
 
c565f55
7a064ce
 
 
 
5e3673b
fc3bf2a
7a064ce
 
 
 
 
 
 
0cfdea5
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
 
 
 
 
7a064ce
 
 
 
0cfdea5
 
7a064ce
2837fde
7a064ce
 
 
34d9afb
 
 
7a064ce
fc3bf2a
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cfdea5
 
7a064ce
 
0cfdea5
7a064ce
 
 
 
 
 
 
 
 
0cfdea5
 
7a064ce
 
 
 
 
 
 
 
0cfdea5
 
7a064ce
 
 
 
 
 
 
 
 
0cfdea5
 
7a064ce
 
 
0cfdea5
7a064ce
0cfdea5
 
7a064ce
 
 
 
fc3bf2a
0cfdea5
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
 
 
 
 
7a064ce
 
 
34d9afb
 
 
 
 
 
 
 
7a064ce
 
 
fc3bf2a
7a064ce
 
 
 
 
 
 
 
 
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
 
7a064ce
fc3bf2a
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
4e10575
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
179360e
 
 
 
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
179360e
7a064ce
 
 
 
 
 
 
fc3bf2a
0ee86b0
317e100
7a064ce
 
0ee86b0
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
ee1b1b5
317e100
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179360e
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee86b0
 
7a064ce
0ee86b0
 
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
 
 
 
 
7a064ce
 
 
 
34d9afb
 
 
 
 
 
 
 
 
7a064ce
 
 
 
 
34d9afb
 
7a064ce
0ee86b0
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
bd2eab1
 
 
 
 
 
 
 
 
 
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd2eab1
fc3bf2a
7a064ce
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
7a064ce
 
 
 
 
0cfdea5
7a064ce
 
 
 
 
 
 
 
 
 
 
 
 
34d9afb
7a064ce
 
 
 
 
 
 
 
 
 
 
34d9afb
 
7a064ce
 
 
 
 
34d9afb
fc3bf2a
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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
"""Neon Postgres persistence for documents, chunks, and embeddings."""

from __future__ import annotations

import contextlib
import os
from collections.abc import Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from datetime import date, datetime, timezone
from typing import Any

import numpy as np
import psycopg
from pgvector.psycopg import register_vector
from psycopg import sql
from psycopg.rows import DictRow, dict_row

from infrastructure.logger import get_logger

_logger = get_logger()

TOK_VER = int(os.getenv("TOK_VER", "2"))
SEG_VER = int(os.getenv("SEG_VER", "1"))


@dataclass
class Document:
    """Stored document metadata."""

    doc_id: int
    sha256: str
    title: str | None = None
    source_path: str | None = None
    object_key: str | None = None
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    doc_type: str | None = None
    jurisdiction: str | None = None
    governing_law: str | None = None
    party_roles: str | None = None
    industry: str | None = None
    effective_date: date | datetime | None = None
    chunks: list[Chunk] = field(default_factory=list)


@dataclass
class Chunk:
    """Stored document chunk and its searchable metadata."""

    chunk_id: int
    doc_id: int
    chunk_index: int
    text: str
    token_count: int | None = None
    page_start: int | None = None
    page_end: int | None = None
    section_number: str | None = None
    section_title: str | None = None
    path: str | None = None
    numbers_present: bool | None = None
    definition_terms: str | None = None
    clause_type: str | None = None
    tok_ver: int = TOK_VER
    seg_ver: int = SEG_VER
    embedding_input_version: int | None = None
    embedding_input_sha256: str | None = None
    embedding_model: str | None = None
    embedding_dim: int | None = None
    has_embedding: bool = False
    document: Document | None = None
    embedding: Embedding | None = None


@dataclass
class Embedding:
    """Embedding associated one-to-one with a chunk."""

    id: int
    chunk_id: int
    model: str
    dim: int
    vector: list[float]
    chunk: Chunk | None = None


@dataclass(frozen=True)
class RawDocumentRecord:
    """Storage metadata for an original uploaded document."""

    object_key: str | None
    source_filename: str
    content_type: str | None
    legacy_content: bytes | None = None


def _database_url() -> str:
    """Return the configured Neon connection string.

    Raises:
        RuntimeError: If no database connection string is configured.
    """
    value = os.getenv("DATABASE_URL") or os.getenv("NEON_DATABASE_URL")
    if not value:
        raise RuntimeError(
            "DATABASE_URL is required; set it to the Neon Postgres connection string"
        )
    return value


def _connect(*, register_types: bool = True) -> psycopg.Connection[DictRow]:
    """Open a short-lived Neon connection suitable for pooled URLs."""
    timeout = int(os.getenv("DATABASE_CONNECT_TIMEOUT", "10"))
    connection = psycopg.Connection[DictRow].connect(
        _database_url(),
        connect_timeout=timeout,
        prepare_threshold=None,
        row_factory=dict_row,
    )
    if register_types:
        register_vector(connection)
    return connection


@contextlib.contextmanager
def session_scope() -> Iterator[psycopg.Connection[DictRow]]:
    """Provide a committing transaction with automatic rollback on failure."""
    with _connect() as connection, connection.transaction():
        yield connection


def get_session() -> psycopg.Connection[DictRow]:
    """Return a new database connection owned by the caller."""
    return _connect()


def get_db() -> psycopg.Connection[DictRow]:
    """Return a new database connection owned by the caller."""
    return _connect()


def init_db() -> None:
    """Create the pgvector extension and application tables when absent."""
    with _connect(register_types=False) as connection:
        with connection.cursor() as cursor:
            cursor.execute("CREATE EXTENSION IF NOT EXISTS vector")
            cursor.execute(
                """
                CREATE TABLE IF NOT EXISTS documents (
                    doc_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
                    sha256 TEXT NOT NULL UNIQUE,
                    title TEXT,
                    source_path TEXT,
                    source_filename TEXT,
                    content_type TEXT,
                    size_bytes BIGINT,
                    object_key TEXT,
                    raw_content BYTEA,
                    clean_text TEXT,
                    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
                    doc_type TEXT,
                    jurisdiction TEXT,
                    governing_law TEXT,
                    party_roles TEXT,
                    industry TEXT,
                    effective_date DATE
                )
                """
            )
            cursor.execute(
                "ALTER TABLE documents ADD COLUMN IF NOT EXISTS object_key TEXT"
            )
            cursor.execute(
                f"""
                CREATE TABLE IF NOT EXISTS chunks (
                    chunk_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
                    doc_id BIGINT NOT NULL REFERENCES documents(doc_id)
                        ON DELETE CASCADE,
                    chunk_index INTEGER NOT NULL,
                    text TEXT NOT NULL,
                    token_count INTEGER,
                    page_start INTEGER,
                    page_end INTEGER,
                    section_number TEXT,
                    section_title TEXT,
                    path TEXT,
                    numbers_present BOOLEAN,
                    definition_terms TEXT,
                    clause_type TEXT,
                    tok_ver INTEGER NOT NULL DEFAULT {TOK_VER},
                    seg_ver INTEGER NOT NULL DEFAULT 1,
                    embedding_model TEXT,
                    embedding_dim INTEGER,
                    embedding vector,
                    embedding_input_version SMALLINT DEFAULT 1,
                    embedding_input_sha256 TEXT,
                    search_tsv TSVECTOR GENERATED ALWAYS AS (
                        setweight(
                            to_tsvector('simple', COALESCE(section_title, '')),
                            'A'
                        ) ||
                        setweight(
                            to_tsvector('simple', COALESCE(clause_type, '')),
                            'A'
                        ) ||
                        setweight(
                            to_tsvector('simple', COALESCE(definition_terms, '')),
                            'A'
                        ) ||
                        setweight(
                            to_tsvector(
                                'simple',
                                COALESCE(section_number, '') || ' ' ||
                                COALESCE(path, '')
                            ),
                            'B'
                        ) ||
                        setweight(to_tsvector('simple', text), 'D')
                    ) STORED,
                    UNIQUE (doc_id, chunk_index)
                )
                """
            )
            cursor.execute(
                "ALTER TABLE chunks ADD COLUMN IF NOT EXISTS "
                "embedding_input_version SMALLINT DEFAULT 1"
            )
            cursor.execute(
                "ALTER TABLE chunks ADD COLUMN IF NOT EXISTS "
                "embedding_input_sha256 TEXT"
            )
            cursor.execute(
                f"ALTER TABLE chunks ALTER COLUMN tok_ver SET DEFAULT {TOK_VER}"
            )
            cursor.execute(
                """
                ALTER TABLE chunks ADD COLUMN IF NOT EXISTS search_tsv TSVECTOR
                GENERATED ALWAYS AS (
                    setweight(
                        to_tsvector('simple', COALESCE(section_title, '')), 'A'
                    ) ||
                    setweight(
                        to_tsvector('simple', COALESCE(clause_type, '')), 'A'
                    ) ||
                    setweight(
                        to_tsvector('simple', COALESCE(definition_terms, '')), 'A'
                    ) ||
                    setweight(
                        to_tsvector(
                            'simple',
                            COALESCE(section_number, '') || ' ' ||
                            COALESCE(path, '')
                        ),
                        'B'
                    ) ||
                    setweight(to_tsvector('simple', text), 'D')
                ) STORED
                """
            )
            cursor.execute(
                "CREATE INDEX IF NOT EXISTS chunks_doc_id_idx ON chunks (doc_id)"
            )
            cursor.execute(
                "CREATE INDEX IF NOT EXISTS chunks_search_tsv_idx "
                "ON chunks USING GIN (search_tsv)"
            )
            cursor.execute(
                "CREATE INDEX IF NOT EXISTS documents_created_at_idx "
                "ON documents (created_at DESC)"
            )
        connection.commit()
    _logger.info("Neon Postgres schema initialized")


def reset_database() -> bool:
    """Delete all application data while retaining the schema."""
    try:
        with session_scope() as connection:
            connection.execute("TRUNCATE TABLE chunks, documents RESTART IDENTITY")
        return True
    except (psycopg.Error, RuntimeError, ValueError) as exc:
        _logger.error("Failed to reset Neon database: %s", exc)
        return False


def full_reset_database() -> bool:
    """Delete all persistent application records."""
    return reset_database()


def _normalize_text_value(value: Any) -> Any:
    """Normalize list metadata to the comma-delimited representation used by the UI."""
    if isinstance(value, list):
        return ", ".join(str(item) for item in value)
    return value


def _normalize_effective_date(value: Any) -> date | None:
    """Coerce supported effective-date values into a Postgres date."""
    if value is None or value == "" or str(value).lower() == "none":
        return None
    if isinstance(value, datetime):
        return value.date()
    if isinstance(value, date):
        return value
    try:
        return date.fromisoformat(str(value)[:10])
    except ValueError:
        _logger.warning("Ignoring invalid effective date: %s", value)
        return None


def _document_from_row(row: Mapping[str, Any]) -> Document:
    """Convert a database row into a document domain object."""
    return Document(
        doc_id=int(row["doc_id"]),
        sha256=str(row["sha256"]),
        title=row.get("title"),
        source_path=row.get("source_path"),
        object_key=row.get("object_key"),
        created_at=row.get("created_at") or datetime.now(timezone.utc),
        doc_type=row.get("doc_type"),
        jurisdiction=row.get("jurisdiction"),
        governing_law=row.get("governing_law"),
        party_roles=row.get("party_roles"),
        industry=row.get("industry"),
        effective_date=row.get("effective_date"),
    )


def _chunk_from_row(row: Mapping[str, Any]) -> Chunk:
    """Convert a database row into a chunk domain object."""
    return Chunk(
        chunk_id=int(row["chunk_id"]),
        doc_id=int(row["doc_id"]),
        chunk_index=int(row["chunk_index"]),
        text=str(row.get("text") or ""),
        token_count=row.get("token_count"),
        page_start=row.get("page_start"),
        page_end=row.get("page_end"),
        section_number=row.get("section_number"),
        section_title=row.get("section_title"),
        path=row.get("path"),
        numbers_present=row.get("numbers_present"),
        definition_terms=row.get("definition_terms"),
        clause_type=row.get("clause_type"),
        tok_ver=int(row.get("tok_ver") or TOK_VER),
        seg_ver=int(row.get("seg_ver") or SEG_VER),
        embedding_input_version=row.get("embedding_input_version"),
        embedding_input_sha256=row.get("embedding_input_sha256"),
        embedding_model=row.get("embedding_model"),
        embedding_dim=row.get("embedding_dim"),
        has_embedding=bool(row.get("has_embedding", False)),
    )


_DOCUMENT_COLUMNS = """
    doc_id, sha256, title, source_path, object_key, created_at, doc_type,
    jurisdiction, governing_law, party_roles, industry, effective_date
"""

_CHUNK_COLUMNS = """
    chunk_id, doc_id, chunk_index, text, token_count, page_start, page_end,
    section_number, section_title, path, numbers_present, definition_terms,
    clause_type, tok_ver, seg_ver, embedding_input_version,
    embedding_input_sha256, embedding_model, embedding_dim,
    (embedding IS NOT NULL) AS has_embedding
"""


def add_document(
    *,
    sha256: str,
    title: str | None = None,
    source_path: str | None = None,
    doc_type: str | list[str] | None = None,
    jurisdiction: str | list[str] | None = None,
    industry: str | list[str] | None = None,
    party_roles: str | list[str] | None = None,
    governing_law: str | list[str] | None = None,
    effective_date: Any = None,
) -> Document:
    """Insert a document or enrich missing metadata for an existing hash."""
    values = {
        "sha256": sha256,
        "title": _normalize_text_value(title),
        "source_path": source_path,
        "doc_type": _normalize_text_value(doc_type),
        "jurisdiction": _normalize_text_value(jurisdiction),
        "industry": _normalize_text_value(industry),
        "party_roles": _normalize_text_value(party_roles),
        "governing_law": _normalize_text_value(governing_law),
        "effective_date": _normalize_effective_date(effective_date),
    }
    with session_scope() as connection:
        row = connection.execute(
            f"""
            INSERT INTO documents (
                sha256, title, source_path, doc_type, jurisdiction, industry,
                party_roles, governing_law, effective_date
            ) VALUES (
                %(sha256)s, %(title)s, %(source_path)s, %(doc_type)s,
                %(jurisdiction)s, %(industry)s, %(party_roles)s,
                %(governing_law)s, %(effective_date)s
            )
            ON CONFLICT (sha256) DO UPDATE SET
                title = COALESCE(documents.title, EXCLUDED.title),
                source_path = COALESCE(documents.source_path, EXCLUDED.source_path),
                doc_type = COALESCE(documents.doc_type, EXCLUDED.doc_type),
                jurisdiction = COALESCE(documents.jurisdiction, EXCLUDED.jurisdiction),
                industry = COALESCE(documents.industry, EXCLUDED.industry),
                party_roles = COALESCE(documents.party_roles, EXCLUDED.party_roles),
                governing_law = COALESCE(
                    documents.governing_law, EXCLUDED.governing_law
                ),
                effective_date = COALESCE(
                    documents.effective_date, EXCLUDED.effective_date
                )
            RETURNING {_DOCUMENT_COLUMNS}
            """,
            values,
        ).fetchone()
    if row is None:
        raise RuntimeError("Neon did not return the inserted document")
    return _document_from_row(row)


def store_document_content(
    doc_id: int,
    *,
    source_filename: str,
    content_type: str | None,
    object_key: str,
    size_bytes: int,
    clean_text: str,
) -> Document:
    """Persist object metadata and extracted text in Neon Postgres."""
    source_path = f"/api/raw/{doc_id}/{source_filename}"
    with session_scope() as connection:
        row = connection.execute(
            f"""
            UPDATE documents
            SET source_path = %s,
                source_filename = %s,
                content_type = %s,
                size_bytes = %s,
                object_key = %s,
                raw_content = NULL,
                clean_text = %s
            WHERE doc_id = %s
            RETURNING {_DOCUMENT_COLUMNS}
            """,
            (
                source_path,
                source_filename,
                content_type,
                size_bytes,
                object_key,
                clean_text,
                doc_id,
            ),
        ).fetchone()
    if row is None:
        raise KeyError(f"Document {doc_id} does not exist")
    return _document_from_row(row)


def get_raw_document(doc_id: int) -> RawDocumentRecord | None:
    """Return object metadata or legacy database bytes for an original upload."""
    with _connect() as connection:
        row = connection.execute(
            """
            SELECT object_key, raw_content, source_filename, content_type
            FROM documents
            WHERE doc_id = %s
              AND (object_key IS NOT NULL OR raw_content IS NOT NULL)
            """,
            (doc_id,),
        ).fetchone()
    if row is None:
        return None
    legacy_content = row["raw_content"]
    return RawDocumentRecord(
        object_key=row["object_key"],
        source_filename=str(row["source_filename"] or "document"),
        content_type=row["content_type"],
        legacy_content=bytes(legacy_content) if legacy_content is not None else None,
    )


def add_chunk(
    doc_id: int,
    chunk_id: int | None,
    text: str,
    chunk_index: int,
    token_count: int | None = None,
    page_start: int | None = None,
    page_end: int | None = None,
    section_number: str | None = None,
    section_title: str | None = None,
    path: str | None = None,
    numbers_present: bool | None = None,
    definition_terms: str | list[str] | None = None,
    clause_type: str | None = None,
    tok_ver: int = TOK_VER,
    seg_ver: int = SEG_VER,
) -> Chunk:
    """Insert or replace the chunk at a document-relative index."""
    definition_terms_value = _normalize_text_value(definition_terms)
    columns = [
        "doc_id",
        "chunk_index",
        "text",
        "token_count",
        "page_start",
        "page_end",
        "section_number",
        "section_title",
        "path",
        "numbers_present",
        "definition_terms",
        "clause_type",
        "tok_ver",
        "seg_ver",
    ]
    values: list[Any] = [
        doc_id,
        chunk_index,
        text,
        token_count,
        page_start,
        page_end,
        section_number,
        section_title,
        path,
        numbers_present,
        definition_terms_value,
        clause_type,
        tok_ver,
        seg_ver,
    ]
    if chunk_id is not None:
        columns.insert(0, "chunk_id")
        values.insert(0, chunk_id)

    insert = sql.SQL(
        """
        INSERT INTO chunks ({columns}) VALUES ({placeholders})
        ON CONFLICT (doc_id, chunk_index) DO UPDATE SET
            text = EXCLUDED.text,
            token_count = EXCLUDED.token_count,
            page_start = EXCLUDED.page_start,
            page_end = EXCLUDED.page_end,
            section_number = EXCLUDED.section_number,
            section_title = EXCLUDED.section_title,
            path = EXCLUDED.path,
            numbers_present = EXCLUDED.numbers_present,
            definition_terms = EXCLUDED.definition_terms,
            clause_type = EXCLUDED.clause_type,
            tok_ver = EXCLUDED.tok_ver,
            seg_ver = EXCLUDED.seg_ver,
            embedding = CASE
                WHEN ROW(
                    chunks.text,
                    chunks.section_number,
                    chunks.section_title,
                    chunks.clause_type,
                    chunks.definition_terms,
                    chunks.path
                ) IS NOT DISTINCT FROM ROW(
                    EXCLUDED.text,
                    EXCLUDED.section_number,
                    EXCLUDED.section_title,
                    EXCLUDED.clause_type,
                    EXCLUDED.definition_terms,
                    EXCLUDED.path
                ) THEN chunks.embedding
                ELSE NULL
            END,
            embedding_model = CASE
                WHEN ROW(
                    chunks.text,
                    chunks.section_number,
                    chunks.section_title,
                    chunks.clause_type,
                    chunks.definition_terms,
                    chunks.path
                ) IS NOT DISTINCT FROM ROW(
                    EXCLUDED.text,
                    EXCLUDED.section_number,
                    EXCLUDED.section_title,
                    EXCLUDED.clause_type,
                    EXCLUDED.definition_terms,
                    EXCLUDED.path
                ) THEN chunks.embedding_model
                ELSE NULL
            END,
            embedding_dim = CASE
                WHEN ROW(
                    chunks.text,
                    chunks.section_number,
                    chunks.section_title,
                    chunks.clause_type,
                    chunks.definition_terms,
                    chunks.path
                ) IS NOT DISTINCT FROM ROW(
                    EXCLUDED.text,
                    EXCLUDED.section_number,
                    EXCLUDED.section_title,
                    EXCLUDED.clause_type,
                    EXCLUDED.definition_terms,
                    EXCLUDED.path
                ) THEN chunks.embedding_dim
                ELSE NULL
            END,
            embedding_input_version = CASE
                WHEN ROW(
                    chunks.text,
                    chunks.section_number,
                    chunks.section_title,
                    chunks.clause_type,
                    chunks.definition_terms,
                    chunks.path
                ) IS NOT DISTINCT FROM ROW(
                    EXCLUDED.text,
                    EXCLUDED.section_number,
                    EXCLUDED.section_title,
                    EXCLUDED.clause_type,
                    EXCLUDED.definition_terms,
                    EXCLUDED.path
                ) THEN chunks.embedding_input_version
                ELSE NULL
            END,
            embedding_input_sha256 = CASE
                WHEN ROW(
                    chunks.text,
                    chunks.section_number,
                    chunks.section_title,
                    chunks.clause_type,
                    chunks.definition_terms,
                    chunks.path
                ) IS NOT DISTINCT FROM ROW(
                    EXCLUDED.text,
                    EXCLUDED.section_number,
                    EXCLUDED.section_title,
                    EXCLUDED.clause_type,
                    EXCLUDED.definition_terms,
                    EXCLUDED.path
                ) THEN chunks.embedding_input_sha256
                ELSE NULL
            END
        RETURNING {returning}
        """
    ).format(
        columns=sql.SQL(", ").join(map(sql.Identifier, columns)),
        placeholders=sql.SQL(", ").join(sql.Placeholder() for _ in columns),
        returning=sql.SQL(_CHUNK_COLUMNS),
    )

    with session_scope() as connection:
        row = connection.execute(insert, values).fetchone()
        if chunk_id is not None:
            connection.execute(
                """
                SELECT setval(
                    pg_get_serial_sequence('chunks', 'chunk_id'),
                    GREATEST((SELECT COALESCE(MAX(chunk_id), 1) FROM chunks), 1),
                    true
                )
                """
            )
    if row is None:
        raise RuntimeError("Neon did not return the inserted chunk")
    return _chunk_from_row(row)


def upsert_embedding(
    chunk_id: int,
    model: str,
    dim: int,
    vector_bytes: bytes | Sequence[float],
    *,
    input_version: int = 1,
    input_sha256: str | None = None,
) -> Embedding | None:
    """Persist an embedding in the pgvector column for a chunk."""
    if isinstance(vector_bytes, bytes):
        vector = np.frombuffer(vector_bytes, dtype=np.float32).tolist()
    else:
        vector = [float(value) for value in vector_bytes]
    if len(vector) != dim:
        raise ValueError(f"Embedding dimension {len(vector)} does not match {dim}")
    database_vector = np.asarray(vector, dtype=np.float32)
    with session_scope() as connection:
        row = connection.execute(
            """
            UPDATE chunks
            SET embedding = %s,
                embedding_model = %s,
                embedding_dim = %s,
                embedding_input_version = %s,
                embedding_input_sha256 = %s
            WHERE chunk_id = %s
            RETURNING chunk_id
            """,
            (
                database_vector,
                model,
                dim,
                input_version,
                input_sha256,
                chunk_id,
            ),
        ).fetchone()
    if row is None:
        _logger.error("Cannot upsert embedding for missing chunk_id=%s", chunk_id)
        return None
    return Embedding(
        id=chunk_id,
        chunk_id=chunk_id,
        model=model,
        dim=dim,
        vector=vector,
    )


def upsert_embeddings(records: Sequence[Mapping[str, Any]]) -> int:
    """Atomically replace a batch of successfully generated embeddings."""
    if not records:
        return 0
    with session_scope() as connection:
        for record in records:
            vector = [float(value) for value in record["vector"]]
            dim = int(record["dim"])
            if len(vector) != dim:
                raise ValueError(
                    f"Embedding dimension {len(vector)} does not match {dim}"
                )
            row = connection.execute(
                """
                UPDATE chunks
                SET embedding = %s,
                    embedding_model = %s,
                    embedding_dim = %s,
                    embedding_input_version = %s,
                    embedding_input_sha256 = %s,
                    token_count = COALESCE(%s, token_count),
                    tok_ver = COALESCE(%s, tok_ver)
                WHERE chunk_id = %s
                RETURNING chunk_id
                """,
                (
                    np.asarray(vector, dtype=np.float32),
                    str(record["model"]),
                    dim,
                    int(record["input_version"]),
                    str(record["input_sha256"]),
                    record.get("token_count"),
                    record.get("tok_ver"),
                    int(record["chunk_id"]),
                ),
            ).fetchone()
            if row is None:
                raise RuntimeError(
                    f"Cannot upsert embedding for missing chunk_id={record['chunk_id']}"
                )
    return len(records)


def get_document(doc_id: int) -> Document | None:
    """Return one document by identifier."""
    with _connect() as connection:
        row = connection.execute(
            f"SELECT {_DOCUMENT_COLUMNS} FROM documents WHERE doc_id = %s",
            (doc_id,),
        ).fetchone()
    return _document_from_row(row) if row else None


def get_document_by_sha(sha256: str) -> Document | None:
    """Return one document by its cleaned-content hash."""
    with _connect() as connection:
        row = connection.execute(
            f"SELECT {_DOCUMENT_COLUMNS} FROM documents WHERE sha256 = %s",
            (sha256,),
        ).fetchone()
    return _document_from_row(row) if row else None


def get_chunks_for_doc(doc_id: int) -> list[Chunk]:
    """Return all chunks for a document in source order."""
    with _connect() as connection:
        rows = connection.execute(
            f"""
            SELECT {_CHUNK_COLUMNS}
            FROM chunks
            WHERE doc_id = %s
            ORDER BY chunk_index
            """,
            (doc_id,),
        ).fetchall()
    return [_chunk_from_row(row) for row in rows]


def get_chunks_by_ids(chunk_ids: list[int]) -> list[Chunk]:
    """Return chunks with parent document metadata, preserving requested order."""
    if not chunk_ids:
        return []
    with _connect() as connection:
        rows = connection.execute(
            f"""
            SELECT {_CHUNK_COLUMNS}
            FROM chunks
            WHERE chunk_id = ANY(%s)
            """,
            (chunk_ids,),
        ).fetchall()
        chunks = [_chunk_from_row(row) for row in rows]
        document_ids = list({chunk.doc_id for chunk in chunks})
        document_rows = connection.execute(
            f"""
            SELECT {_DOCUMENT_COLUMNS}
            FROM documents
            WHERE doc_id = ANY(%s)
            """,
            (document_ids,),
        ).fetchall()
    documents = {int(row["doc_id"]): _document_from_row(row) for row in document_rows}
    chunks_by_id = {chunk.chunk_id: chunk for chunk in chunks}
    for chunk in chunks:
        chunk.document = documents.get(chunk.doc_id)
    return [
        chunks_by_id[chunk_id] for chunk_id in chunk_ids if chunk_id in chunks_by_id
    ]


def get_documents(limit: int = 100, offset: int = 0) -> list[Document]:
    """Return a newest-first page of documents."""
    with _connect() as connection:
        rows = connection.execute(
            f"""
            SELECT {_DOCUMENT_COLUMNS}
            FROM documents
            ORDER BY created_at DESC, doc_id DESC
            LIMIT %s OFFSET %s
            """,
            (limit, offset),
        ).fetchall()
    return [_document_from_row(row) for row in rows]


def get_document_chunk_counts(doc_ids: list[int]) -> dict[int, int]:
    """Return chunk counts for the supplied document identifiers."""
    counts = {doc_id: 0 for doc_id in doc_ids}
    if not doc_ids:
        return counts
    with _connect() as connection:
        rows = connection.execute(
            """
            SELECT doc_id, count(*) AS chunk_count
            FROM chunks
            WHERE doc_id = ANY(%s)
            GROUP BY doc_id
            """,
            (doc_ids,),
        ).fetchall()
    for row in rows:
        counts[int(row["doc_id"])] = int(row["chunk_count"])
    return counts


def get_max_document_id() -> int:
    """Return the greatest assigned document identifier."""
    with _connect() as connection:
        row = connection.execute(
            "SELECT COALESCE(MAX(doc_id), 0) AS max_id FROM documents"
        ).fetchone()
    return int(row["max_id"]) if row else 0


def get_all_chunks(limit: int = 200, offset: int = 0) -> list[Chunk]:
    """Return an identifier-ordered page of chunks."""
    with _connect() as connection:
        rows = connection.execute(
            f"""
            SELECT {_CHUNK_COLUMNS}
            FROM chunks
            ORDER BY chunk_id
            LIMIT %s OFFSET %s
            """,
            (limit, offset),
        ).fetchall()
    return [_chunk_from_row(row) for row in rows]


def get_embedding_backfill_batch(
    *, after_chunk_id: int = 0, limit: int = 64
) -> list[Chunk]:
    """Return a stable chunk-ID batch for resumable embedding backfills."""
    with _connect() as connection:
        rows = connection.execute(
            f"""
            SELECT {_CHUNK_COLUMNS}
            FROM chunks
            WHERE chunk_id > %s
            ORDER BY chunk_id
            LIMIT %s
            """,
            (after_chunk_id, limit),
        ).fetchall()
    return [_chunk_from_row(row) for row in rows]


def get_max_chunk_id() -> int:
    """Return the greatest assigned chunk identifier."""
    with _connect() as connection:
        row = connection.execute(
            "SELECT COALESCE(MAX(chunk_id), -1) AS max_id FROM chunks"
        ).fetchone()
    return int(row["max_id"]) if row else -1


def _embedding_values(value: Any) -> list[float] | None:
    """Normalize pgvector wrappers and sequence-like vectors to plain floats."""
    if value is None:
        return None
    to_list = getattr(value, "to_list", None)
    if callable(to_list):
        value = to_list()
    return [float(item) for item in value]


def get_embedding_for_chunk(chunk_id: int) -> Embedding | None:
    """Return a chunk embedding if one has been generated."""
    with _connect() as connection:
        row = connection.execute(
            """
            SELECT chunk_id, embedding_model, embedding_dim, embedding
            FROM chunks
            WHERE chunk_id = %s AND embedding IS NOT NULL
            """,
            (chunk_id,),
        ).fetchone()
    if row is None:
        return None
    vector = _embedding_values(row["embedding"]) or []
    return Embedding(
        id=chunk_id,
        chunk_id=chunk_id,
        model=str(row["embedding_model"] or "unknown"),
        dim=int(row["embedding_dim"] or len(vector)),
        vector=vector,
    )


def get_embedding_counts_for_chunks(chunk_ids: list[int]) -> dict[int, int]:
    """Return zero-or-one embedding counts for supplied chunks."""
    counts = {chunk_id: 0 for chunk_id in chunk_ids}
    if not chunk_ids:
        return counts
    with _connect() as connection:
        rows = connection.execute(
            """
            SELECT chunk_id
            FROM chunks
            WHERE chunk_id = ANY(%s) AND embedding IS NOT NULL
            """,
            (chunk_ids,),
        ).fetchall()
    for row in rows:
        counts[int(row["chunk_id"])] = 1
    return counts


_SEARCH_FILTER_FIELDS = {"doc_type", "jurisdiction", "governing_law", "industry"}


def _search_conditions(
    filters: Mapping[str, Any] | None,
) -> tuple[list[sql.Composable], list[Any]]:
    """Build parameterized document-filter conditions for candidate searches."""
    conditions: list[sql.Composable] = []
    parameters: list[Any] = []
    if not filters:
        return conditions, parameters

    if filters.get("doc_id") is not None:
        conditions.append(sql.SQL("c.doc_id = %s"))
        parameters.append(int(filters["doc_id"]))
    for metadata_field in sorted(_SEARCH_FILTER_FIELDS):
        value = filters.get(metadata_field)
        if value is None:
            continue
        conditions.append(
            sql.SQL(
                "%s = ANY(regexp_split_to_array("
                "lower(trim(COALESCE(d.{field}, ''))), '\\s*,\\s*'))"
            ).format(field=sql.Identifier(metadata_field))
        )
        parameters.append(str(value).strip().lower())
    return conditions, parameters


def _candidate_from_row(row: Mapping[str, Any]) -> dict[str, Any]:
    """Normalize a database candidate for rank fusion."""
    vector = _embedding_values(row.get("embedding"))
    candidate = {
        "chunk_id": int(row["chunk_id"]),
        "doc_id": int(row["doc_id"]),
        "chunk_index": int(row["chunk_index"]),
        "text": str(row.get("text") or ""),
        "token_count": row.get("token_count"),
        "page_start": row.get("page_start"),
        "page_end": row.get("page_end"),
        "section_number": row.get("section_number"),
        "section_title": row.get("section_title"),
        "clause_type": row.get("clause_type"),
        "path": row.get("path"),
        "definition_terms": row.get("definition_terms"),
        "document_sha256": str(row.get("document_sha256") or ""),
        "title": row.get("title"),
        "doc_type": row.get("doc_type"),
        "jurisdiction": row.get("jurisdiction"),
        "governing_law": row.get("governing_law"),
        "industry": row.get("industry"),
        "embedding": vector,
    }
    if row.get("distance") is not None:
        candidate["distance"] = float(row["distance"])
    if row.get("lexical_score") is not None:
        candidate["lexical_score"] = float(row["lexical_score"])
    return candidate


_CANDIDATE_COLUMNS = """
    c.chunk_id, c.doc_id, c.chunk_index, c.text, c.token_count,
    c.page_start, c.page_end, c.section_number, c.section_title,
    c.clause_type, c.path, c.definition_terms, c.embedding,
    d.sha256 AS document_sha256, d.title, d.doc_type, d.jurisdiction,
    d.governing_law, d.industry
"""


def search_vector_candidates(
    query_vector: Sequence[float],
    *,
    model: str,
    limit: int,
    filters: Mapping[str, Any] | None = None,
) -> list[dict[str, Any]]:
    """Return an exact cosine-ranked candidate pool with document filters."""
    vector = [float(value) for value in query_vector]
    database_vector = np.asarray(vector, dtype=np.float32)
    filter_conditions, filter_parameters = _search_conditions(filters)
    conditions = [
        sql.SQL("c.embedding IS NOT NULL"),
        sql.SQL("c.embedding_model = %s"),
        sql.SQL("c.embedding_dim = %s"),
        *filter_conditions,
    ]
    statement = sql.SQL(
        """
        SELECT {columns}, c.embedding <=> %s AS distance
        FROM chunks c
        JOIN documents d ON d.doc_id = c.doc_id
        WHERE {conditions}
        ORDER BY c.embedding <=> %s, c.chunk_id
        LIMIT %s
        """
    ).format(
        columns=sql.SQL(_CANDIDATE_COLUMNS),
        conditions=sql.SQL(" AND ").join(conditions),
    )
    parameters = [
        database_vector,
        model,
        len(vector),
        *filter_parameters,
        database_vector,
        limit,
    ]
    with _connect() as connection:
        rows = connection.execute(statement, parameters).fetchall()
    return [_candidate_from_row(row) for row in rows]


def search_lexical_candidates(
    query: str,
    *,
    limit: int,
    filters: Mapping[str, Any] | None = None,
) -> list[dict[str, Any]]:
    """Return a weighted Postgres full-text candidate pool."""
    filter_conditions, filter_parameters = _search_conditions(filters)
    conditions = [sql.SQL("c.search_tsv @@ query.value"), *filter_conditions]
    statement = sql.SQL(
        """
        WITH query AS (
            SELECT websearch_to_tsquery('simple', %s) AS value
        )
        SELECT {columns},
               ts_rank_cd(c.search_tsv, query.value, 32) AS lexical_score
        FROM chunks c
        JOIN documents d ON d.doc_id = c.doc_id
        CROSS JOIN query
        WHERE {conditions}
        ORDER BY lexical_score DESC, c.chunk_id
        LIMIT %s
        """
    ).format(
        columns=sql.SQL(_CANDIDATE_COLUMNS),
        conditions=sql.SQL(" AND ").join(conditions),
    )
    parameters = [query, *filter_parameters, limit]
    with _connect() as connection:
        rows = connection.execute(statement, parameters).fetchall()
    return [_candidate_from_row(row) for row in rows]


def search_chunks(
    query_vector: Sequence[float],
    *,
    model: str,
    limit: int,
    doc_id: int | None = None,
) -> list[dict[str, Any]]:
    """Run exact cosine-distance search over compatible pgvector rows."""
    vector = [float(value) for value in query_vector]
    database_vector = np.asarray(vector, dtype=np.float32)
    conditions = [
        sql.SQL("embedding IS NOT NULL"),
        sql.SQL("embedding_model = %s"),
        sql.SQL("embedding_dim = %s"),
    ]
    filter_params: list[Any] = [model, len(vector)]
    if doc_id is not None:
        conditions.append(sql.SQL("doc_id = %s"))
        filter_params.append(doc_id)
    statement = sql.SQL(
        """
        SELECT chunk_id, text, doc_id, embedding <=> %s AS distance
        FROM chunks
        WHERE {conditions}
        ORDER BY embedding <=> %s
        LIMIT %s
        """
    ).format(conditions=sql.SQL(" AND ").join(conditions))
    params = [database_vector, *filter_params, database_vector, limit]
    with _connect() as connection:
        rows = connection.execute(statement, params).fetchall()
    return [
        {
            "id": str(row["chunk_id"]),
            "distance": float(row["distance"]),
            "document": row["text"],
            "metadata": {"doc_id": int(row["doc_id"])},
        }
        for row in rows
    ]


def delete_document(doc_id: int) -> bool:
    """Delete a document and all cascading chunks and embeddings."""
    with session_scope() as connection:
        result = connection.execute(
            "DELETE FROM documents WHERE doc_id = %s", (doc_id,)
        )
    return result.rowcount > 0


def update_chunk(chunk_id: int, updates: Mapping[str, Any]) -> Chunk | None:
    """Update editable chunk fields and invalidate a changed-text embedding."""
    allowed = {
        "text",
        "section_number",
        "section_title",
        "clause_type",
        "definition_terms",
        "page_start",
        "page_end",
        "path",
        "numbers_present",
    }
    normalized: dict[str, Any] = {}
    for key, value in updates.items():
        if key not in allowed:
            continue
        if key in {"page_start", "page_end"}:
            normalized[key] = int(value) if value is not None and value != "" else None
        elif key == "numbers_present" and isinstance(value, str):
            normalized[key] = value.strip().lower() in {"1", "true", "yes"}
        elif key == "definition_terms":
            normalized[key] = _normalize_text_value(value)
        elif value is None:
            normalized[key] = None
        else:
            normalized[key] = str(value)
    if not normalized:
        chunks = get_chunks_by_ids([chunk_id])
        return chunks[0] if chunks else None
    if "text" in normalized:
        from infrastructure.retrieval_text import count_tokens

        normalized["token_count"] = count_tokens(str(normalized["text"] or ""))
        normalized["tok_ver"] = TOK_VER
    assignments: list[sql.Composable] = [
        sql.SQL("{} = %s").format(sql.Identifier(key)) for key in normalized
    ]
    values = list(normalized.values())
    retrieval_fields = {
        "text",
        "section_number",
        "section_title",
        "clause_type",
        "definition_terms",
        "path",
    }
    if retrieval_fields.intersection(normalized):
        assignments.extend(
            [
                sql.SQL("embedding = NULL"),
                sql.SQL("embedding_model = NULL"),
                sql.SQL("embedding_dim = NULL"),
                sql.SQL("embedding_input_version = NULL"),
                sql.SQL("embedding_input_sha256 = NULL"),
            ]
        )
    statement = sql.SQL(
        "UPDATE chunks SET {assignments} WHERE chunk_id = %s RETURNING {columns}"
    ).format(
        assignments=sql.SQL(", ").join(assignments),
        columns=sql.SQL(_CHUNK_COLUMNS),
    )
    values.append(chunk_id)
    with session_scope() as connection:
        row = connection.execute(statement, values).fetchone()
    return _chunk_from_row(row) if row else None


def update_document(doc_id: int, updates: Mapping[str, Any]) -> Document | None:
    """Update editable document metadata."""
    allowed = {
        "title",
        "doc_type",
        "jurisdiction",
        "governing_law",
        "party_roles",
        "industry",
        "effective_date",
        "source_path",
    }
    normalized = {
        key: (
            _normalize_effective_date(value)
            if key == "effective_date"
            else _normalize_text_value(value)
        )
        for key, value in updates.items()
        if key in allowed
    }
    if not normalized:
        return get_document(doc_id)
    assignments = sql.SQL(", ").join(
        sql.SQL("{} = %s").format(sql.Identifier(key)) for key in normalized
    )
    statement = sql.SQL(
        "UPDATE documents SET {assignments} WHERE doc_id = %s RETURNING {columns}"
    ).format(assignments=assignments, columns=sql.SQL(_DOCUMENT_COLUMNS))
    values = [*normalized.values(), doc_id]
    with session_scope() as connection:
        row = connection.execute(statement, values).fetchone()
    return _document_from_row(row) if row else None


def get_manifest_records() -> list[dict[str, Any]]:
    """Return the document manifest directly from durable database records."""
    with _connect() as connection:
        rows = connection.execute(
            """
            SELECT doc_id, title, sha256, source_path, size_bytes, content_type,
                   doc_type, party_roles, jurisdiction, governing_law, industry,
                   effective_date, created_at
            FROM documents
            ORDER BY created_at DESC, doc_id DESC
            """
        ).fetchall()
    records: list[dict[str, Any]] = []
    for row in rows:
        effective_date_value = row["effective_date"]
        created_at_value = row["created_at"]
        records.append(
            {
                "doc_id": str(row["doc_id"]),
                "title": row["title"],
                "sha256": row["sha256"],
                "source_path": row["source_path"],
                "clean_path": f"database://documents/{row['doc_id']}/clean_text",
                "bytes": str(row["size_bytes"] or 0),
                "content_type": row["content_type"],
                "doc_type": row["doc_type"],
                "party_roles": row["party_roles"],
                "jurisdiction": row["jurisdiction"],
                "governing_law": row["governing_law"],
                "industry": row["industry"],
                "effective_date": (
                    effective_date_value.isoformat() if effective_date_value else None
                ),
                "created_at": created_at_value.isoformat(),
            }
        )
    return records


def clear_database() -> None:
    """Delete all application data."""
    if not reset_database():
        raise RuntimeError("Failed to clear Neon database")


def ping() -> None:
    """Verify that Neon accepts a query."""
    with _connect() as connection:
        connection.execute("SELECT 1").fetchone()


__all__ = [
    "SEG_VER",
    "TOK_VER",
    "Chunk",
    "Document",
    "Embedding",
    "RawDocumentRecord",
    "add_chunk",
    "add_document",
    "clear_database",
    "delete_document",
    "full_reset_database",
    "get_all_chunks",
    "get_chunks_by_ids",
    "get_chunks_for_doc",
    "get_db",
    "get_document",
    "get_document_by_sha",
    "get_document_chunk_counts",
    "get_documents",
    "get_embedding_backfill_batch",
    "get_embedding_counts_for_chunks",
    "get_embedding_for_chunk",
    "get_manifest_records",
    "get_max_chunk_id",
    "get_max_document_id",
    "get_raw_document",
    "get_session",
    "init_db",
    "ping",
    "reset_database",
    "search_chunks",
    "search_lexical_candidates",
    "search_vector_candidates",
    "session_scope",
    "store_document_content",
    "update_chunk",
    "update_document",
    "upsert_embedding",
    "upsert_embeddings",
]