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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
"""Step 2c: turn the parsed DoclingDocuments into retrieval chunks.



Three stages per document:



1. read_items(): Docling's body items as a flat list of Raw items (heading, list

   item, text, table), cleaned with text.prepare_item(). Tables of contents go.

2. structure_*(): our rules (SPEC "Step 2 status and plan", R1-R4) decide which

   headings are real, what each heading's level is, and which section every item

   belongs to. The result is a list of Pieces: headings and body, each tagged with

   a section number. FSRA's PDFs need these rules (Docling's heading levels and

   reading order are wrong in places); the laws are already clean (parse.py).

3. rebuild() writes the Pieces into a fresh DoclingDocument, and Docling's

   HybridChunker cuts that into chunks of at most MAX_CHUNK_TOKENS tokens (counted

   with the embedding model's own tokenizer, headings included). Because every

   section starts with its own heading, a chunk never spans two sections.



Outputs (data/index/):

  chunks.parquet        one row per chunk (System B/C retrieval), xrefs filled by xref.py

  sections.parquet      full text of every citable section (citation checker, Step 8)

  xrefs.parquet         every cross-reference found, with its target or why it has none

  naive_chunks.parquet  fixed 800-character windows over Docling's raw text (System A)



Run:  uv run python -m coveragecheck.ingest.chunk

"""

import re
import sys
from collections.abc import Iterator
from dataclasses import dataclass, field
from functools import cache
from pathlib import Path

import pandas as pd
from docling_core.transforms.chunker.hybrid_chunker import HybridChunker
from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer
from docling_core.types.doc import (
    DocItem,
    DocItemLabel,
    DoclingDocument,
    ListItem,
    SectionHeaderItem,
    TableCell,
    TableItem,
    TextItem,
    TitleItem,
)

from coveragecheck import config
from coveragecheck.ingest import xref
from coveragecheck.ingest.download import read_manifest
from coveragecheck.text import prepare_item

# --- 1. reading Docling items ----------------------------------------------------------


@dataclass(frozen=True)
class Raw:
    """One Docling body item, cleaned. kind: "heading", "list", "text" or "table" (one

    row of a table); "title" once classify_headings() has found the form's own title."""

    kind: str
    text: str
    item: DocItem
    marker: str = ""  # list items only: "1.", "2.1", "(a)", ...


# Docling labels whose items carry prose we keep as body text.
TEXT_LABELS = {
    DocItemLabel.TEXT, DocItemLabel.PARAGRAPH, DocItemLabel.CAPTION, DocItemLabel.FOOTNOTE,
    DocItemLabel.CODE, DocItemLabel.FORMULA, DocItemLabel.REFERENCE,
    DocItemLabel.CHECKBOX_SELECTED, DocItemLabel.CHECKBOX_UNSELECTED,
}  # fmt: skip


def cell_text(cell: TableCell) -> str:
    return prepare_item(cell.text) or ""


def distinct_cells(row: list[TableCell]) -> list[TableCell]:
    """Docling's grid repeats a merged cell in every column it spans; keep it once.

    (Two different cells that both say "Yes" are both kept.)"""
    seen: set[tuple[int, int]] = set()
    out = []
    for c in row:
        key = (c.start_row_offset_idx, c.start_col_offset_idx)
        if key not in seen:
            seen.add(key)
            out.append(c)
    return out


def grid_is_unreliable(body_rows: list[list[TableCell]]) -> bool:
    """A body cell that starts in the first column and spans several columns means

    Docling fused a row label into the value columns (OAP 1's "What Types of Coverage

    Extend to Other Automobiles?" table on p17: 5 columns for a 6-column table), or

    the table has full-width sub-heading rows (OPCF 29). Either way, column names

    can't be trusted for the rows. Measured: flags OAP 1 p17, OPCF 3, 21B, 25A and 29,

    exactly the tables whose labelled rows were wrong, and no correct table."""
    return any(
        c.start_col_offset_idx == 0 and c.col_span > 1 and c.text.strip()
        for row in body_rows
        for c in row
    )


def table_lines(table: TableItem) -> list[str]:
    """A table as one self-contained line per row: "Column: value; Column: value".



    Docling's table structure (grid, header flags, merged-cell spans) is used as is;

    only the text format is ours. Docling's default chunk format repeats a merged

    cell's text once per column it spans, and splits tables mid-cell. One line per

    row lets the chunker split only between rows, and each row keeps the meaning of

    its columns when it is retrieved alone. A merged cell is written once, under all

    its column names ("Accident Benefits / Uninsured Automobile: Yes"). A header

    spanning the whole table ("Insurance Required by Law") becomes a title line.



    When Docling got the grid wrong, column names would be attached to the wrong

    values, which is worse than none: see grid_is_unreliable(). Such a table is

    written plainly, one "a | b | c" line per row (header rows included), in the

    order the PDF prints it.

    """
    grid = table.data.grid
    n_cols = table.data.num_cols
    n_head = 0
    while n_head < len(grid) and all(c.column_header or not c.text.strip() for c in grid[n_head]):
        n_head += 1
    if grid_is_unreliable(grid[n_head:]):
        plain = (" | ".join(filter(None, map(cell_text, distinct_cells(row)))) for row in grid)
        return [line for line in plain if line]
    lines: list[str] = []
    names: list[list[str]] = [[] for _ in range(n_cols)]
    for row in grid[:n_head]:
        spans = {(c.start_col_offset_idx, c.end_col_offset_idx) for c in row}
        if spans == {(0, n_cols)} and n_cols > 1:  # one cell across the table: a title
            lines.append(prepare_item(row[0].text) or "")
            continue
        for col, cell in enumerate(row):
            name = prepare_item(cell.text)
            if name and name not in names[col]:
                names[col].append(name)
    for row in grid[n_head:]:
        groups: dict[tuple[int, int], tuple[list[str], str]] = {}
        for col, cell in enumerate(row):
            text = prepare_item(cell.text)
            if not text:
                continue
            key = (cell.start_row_offset_idx, cell.start_col_offset_idx)
            cols, _ = groups.setdefault(key, ([], text))
            cols.append(" - ".join(names[col]))
        parts = []
        for cols, text in groups.values():
            label = " / ".join(dict.fromkeys(c for c in cols if c))
            parts.append(f"{label}: {text}" if label else text)
        if parts:
            lines.append("; ".join(parts) if n_head else " | ".join(parts))
    return [line for line in lines if line]


def read_items(doc: DoclingDocument) -> list[Raw]:
    """Docling's body items in reading order, cleaned; junk and tables of contents dropped.



    A heading directly followed by a table of contents ("Table of Contents") goes with it.

    """
    items = [item for item, _ in doc.iterate_items() if isinstance(item, DocItem)]
    raws: list[Raw] = []
    for i, item in enumerate(items):
        if item.label == DocItemLabel.DOCUMENT_INDEX:
            continue
        if isinstance(item, TableItem):
            raws += [Raw("table", line, item) for line in table_lines(item)]
            continue
        if not isinstance(item, TextItem):  # pictures, key-value areas: no prose
            continue
        text = prepare_item(item.text)
        if text is None:
            continue
        if isinstance(item, (SectionHeaderItem, TitleItem)):
            nxt = items[i + 1] if i + 1 < len(items) else None
            if nxt is not None and nxt.label == DocItemLabel.DOCUMENT_INDEX:
                continue
            raws.append(Raw("heading", text, item))
        elif isinstance(item, ListItem):
            marker = prepare_item(item.marker or "") or ""
            raws.append(Raw("list", text, item, marker))
        elif item.label in TEXT_LABELS:
            raws.append(Raw("text", text, item))
    return raws


# --- 2. structure rules -----------------------------------------------------------------


@dataclass
class Piece:
    """One element of the corrected document.



    kind "heading": a path element at `level` (1 = just under the document root).

    kind "body": text that belongs to `section` (None = no section number: cite the

    whole document).

    """

    kind: str
    text: str
    section: str | None
    level: int = 0
    items: list[DocItem] = field(default_factory=list)  # source items (page provenance)


def is_label(raw: Raw) -> bool:
    """A short title for what follows it. Either Docling read it as a heading and the

    rules turned it into text (Builder.body() only receives such headings: "Example",

    "Spouse", "Note: ..."), or it is a law headnote that parse.py kept as a caption

    ("Choice of insurer" before subsection 268 (4))."""
    return (
        isinstance(raw.item, (SectionHeaderItem, TitleItem))
        or raw.item.label == DocItemLabel.CAPTION
    )


@dataclass
class Builder:
    """Collects Pieces while the structure rules walk a document.



    A label is glued to the next body item of the same section ("Example #1*" + the

    example, "Spouse" + its definition, a headnote + its subsection), so the chunker

    can never put a cut between them.

    """

    pieces: list[Piece] = field(default_factory=list)
    labels: list[tuple[Raw, str | None]] = field(default_factory=list)

    def flush(self) -> None:
        """Labels with nothing after them in their section stay as text of their own."""
        for raw, section in self.labels:
            self.pieces.append(Piece("body", raw.text, section, items=[raw.item]))
        self.labels = []

    def heading(self, text: str, level: int, section: str | None) -> None:
        self.flush()
        self.pieces.append(Piece("heading", text, section, level))

    def body(self, raw: Raw, section: str | None) -> None:
        if any(s != section for _, s in self.labels):
            self.flush()
        if is_label(raw):
            self.labels.append((raw, section))
            return
        texts = [r.text for r, _ in self.labels] + [body_text(raw)]
        items = [r.item for r, _ in self.labels] + [raw.item]
        self.labels = []
        self.pieces.append(Piece("body", "\n".join(texts), section, items=items))

    def done(self) -> list[Piece]:
        self.flush()
        return self.pieces


def body_text(raw: Raw) -> str:
    """List items keep their marker: the forms cite these numbers ("1.10 Spouse means")."""
    return f"{raw.marker} {raw.text}" if raw.marker else raw.text


# R2: headings that are really body text.
FALSE_HEADING_START = ("Note:", "(", "Please")
# "6.2 What We Will Cover", "2. Who Is Covered", "3.1. What We Will Cover"
NUMBERED = re.compile(r"^(\d+(?:\.\d+)*)\.?\s+(\S.*)$")
CLEAN_NUMBERED = re.compile(r"^\d+(?:\.\d+)*\.?\s+[A-Z][a-z]")


def is_false_heading(text: str) -> bool:
    """R2: a "heading" that is really a sentence, a note or a definition.



    Examples: '1.6 "insured person" means', "Note: You should be aware...",

    "Special Conditions: ... apply:", "(you are fully responsible ...)".

    Long headings are false too, unless they are clean numbered headings

    ("4. Providing Other Coverage When Insured Persons Drive, ..." in OPCF 27).

    """
    if re.search(r"\bmeans\b", text) or text.startswith(FALSE_HEADING_START):
        return True
    if text.endswith(":"):
        return True
    return len(text) > 80 and not CLEAN_NUMBERED.match(text)


def continues_sentence(nxt: Raw | None) -> bool:
    """The next item carries on a sentence: "Where" + "1. the lessee as applicant ..."

    (OPCF 5). A heading in front of it is the sentence's first word, not a heading."""
    return nxt is not None and nxt.kind in ("text", "list") and nxt.text[:1].islower()


def is_title_heading(text: str, row: dict[str, str]) -> bool:
    """The form's own title, printed as a heading: "OPCF 44R FAMILY PROTECTION

    COVERAGE", "Removing Depreciation Deduction for Specified Lessee(s)". It repeats

    the path root (form_id + title), so it is never a path element."""
    has_form_id = re.search(rf"{re.escape(row['form_id'])}(?![\w.])", text, re.I)
    return bool(has_form_id) or row["title"].casefold().startswith(text.casefold())


def classify_headings(raws: list[Raw], row: dict[str, str]) -> list[Raw]:
    """R2 for the PDFs, run before any numbering logic: false headings become text

    (kept in place, so nothing is lost) and the form's own title becomes "title"."""
    out = []
    for i, raw in enumerate(raws):
        if raw.kind == "heading":
            nxt = raws[i + 1] if i + 1 < len(raws) else None
            if is_false_heading(raw.text) or continues_sentence(nxt):
                raw = Raw("text", raw.text, raw.item)
            elif is_title_heading(raw.text, row):
                raw = Raw("title", raw.text, raw.item)
        out.append(raw)
    return out


def split_number(text: str) -> tuple[str, str] | None:
    """ "6.2 What We Will Cover" -> ("6.2", "What We Will Cover"); None if unnumbered."""
    m = NUMBERED.match(text)
    return (m.group(1), m.group(2)) if m else None


def marker_number(marker: str) -> str | None:
    """List marker -> number: "3." -> "3", "2.1." -> "2.1", "(a)" / "A." -> None."""
    m = re.fullmatch(r"(\d+(?:\.\d+)*)\.?", marker)
    return m.group(1) if m else None


def top(number: str) -> int:
    return int(number.split(".")[0])


def list_title(text: str) -> str:
    """R4: a list-item section's title. "Purpose of This Change - This change is ..."

    -> "Purpose of This Change"; a short heading-like item is its own title."""
    before = text.split(" - ", 1)[0].strip()
    # The dash must not sit inside a quoted name: 'For "Direct Compensation - ...'.
    if " - " in text and before.count('"') % 2 == 0:
        return before
    if len(text) <= 60 and not text.endswith((".", ":", ",", ";")) and text[:1].isupper():
        return text
    return ""


TEXT_SECTION = re.compile(r"^(\d+)\.\s+[A-Z]")


def section_starts(raws: list[Raw]) -> dict[int, str]:
    """R4: which items start a numbered section, by one sequential "+1 gate".



    A top-level number N counts only if N == previous + 1, from a numbered heading

    ("2. What We Will Pay"), a list item whose marker is exactly "N.", or a plain

    paragraph that starts "N. " + a capital (OPCF 6B's section 3, which Docling read

    as text; it is the only such paragraph in the corpus). A dotted heading

    ("3.1. What We Will Cover") counts when its first part is the current section.

    Restarted nested lists ("1. 2. 3." inside condition 12) fail the gate.

    Returns {index in raws: section number}.

    """
    starts: dict[int, str] = {}
    current = 0
    for i, raw in enumerate(raws):
        if raw.kind == "heading":
            parts = split_number(raw.text)
            number = parts[0] if parts else None
        elif raw.kind == "list" and re.fullmatch(r"\d+\.", raw.marker):
            number = marker_number(raw.marker)
        elif raw.kind == "text" and (m := TEXT_SECTION.match(raw.text)):
            number = m.group(1)
        else:
            continue
        if number is None:
            continue
        if "." not in number and int(number) == current + 1:
            current = int(number)
            starts[i] = number
        elif "." in number and raw.kind == "heading" and current and top(number) == current:
            starts[i] = number
    return starts


def adopted_headings(raws: list[Raw], starts: dict[int, str]) -> set[int]:
    """Unnumbered headings that sit directly before a top-level section start.



    "Incorrect Classification" right before statutory condition "2." (OAP 1), or

    "INSURING AGREEMENT" right before "3." (OPCF 44R): the heading introduces that

    section, so it becomes a group heading above it, not text of the previous one.

    """
    adopted: set[int] = set()
    run: list[int] = []
    for i, raw in enumerate(raws):
        if raw.kind == "heading" and i not in starts:
            run.append(i)
            continue
        if i in starts and "." not in starts[i]:
            adopted.update(run)
        run = []
    return adopted


def structure_list_sections(

    raws: list[Raw], b: Builder, *, base: int, prefix: str, label: str, section: str | None

) -> None:
    """Sections numbered by R4 (OPCFs, and OAP 1's statutory conditions).



    Path below `base`: group heading (adopted, kept until the next one) > section

    ("Section 3: Title") > dotted sub-section ("3.1. What We Will Cover") >

    unnumbered sub-headings. `prefix` turns a number into a section id ("8." for

    OAP 1 conditions: condition 2 -> "8.2"). `section` is the id of whatever comes

    before the first numbered section.



    Title block (R2): headings before the first section are not path elements (the

    path root is the manifest's form_id + title), so they become body text, except a

    heading that introduces the first section ("DEFINITIONS" before "1.").

    """
    starts = section_starts(raws)
    adopted = adopted_headings(raws, starts)
    first = min(starts, default=len(raws))
    section_level = base + 2  # level of the current (sub-)section heading
    group_level = base + 1
    pending_group: list[str] = []
    for i, raw in enumerate(raws):
        if i < first and i not in adopted:
            b.body(raw, section)  # the title block
            continue
        if raw.kind == "title":  # the form's title again, mid-form: it is the path root
            continue
        if i in adopted:
            pending_group.append(raw.text)
            continue
        if i in starts:
            number = starts[i]
            if "." not in number:  # a new top-level section
                if pending_group:
                    b.heading(" - ".join(pending_group), group_level, prefix + number)
                    pending_group = []
                if raw.kind == "heading":
                    title = split_number(raw.text)[1]
                elif raw.kind == "text":  # "3. The limitation under ..." (number in text)
                    title = list_title(split_number(raw.text)[1])
                else:
                    title = list_title(raw.text)
                name = f"{label} {number}" + (f": {title}" if title else "")
                section, section_level = prefix + number, base + 2
                b.heading(name, section_level, section)
                if raw.kind != "heading":
                    b.body(raw, section)
            else:  # dotted heading: a sub-section, one level per extra number part
                section = prefix + number
                section_level = base + 1 + number.count(".") + 1
                b.heading(raw.text, section_level, section)
            continue
        if raw.kind == "heading":
            b.heading(raw.text, section_level + 1, section)  # a sub-heading
        else:
            b.body(raw, section)


def structure_opcf(raws: list[Raw]) -> list[Piece]:
    """An OPCF change form: title block, then sections numbered by R4.



    Forms with no numbering (OPCF 21A, 23B, 25A, 29, 49, 5C) are cited as a whole:

    their leading headings are the title block and later ones are sub-headings.

    """
    b = Builder()
    if section_starts(raws):
        structure_list_sections(raws, b, base=0, prefix="", label="Section", section=None)
        return b.done()
    leading = True
    for raw in raws:
        if raw.kind == "heading" and not leading:
            b.heading(raw.text, 1, None)
        else:
            leading = leading and raw.kind in ("heading", "title")
            b.body(raw, None)
    return b.done()


BANNER = re.compile(r"^Section (\d+)$")


def structure_oap1(raws: list[Raw]) -> list[Piece]:
    """OAP 1: R1 (structure from numbering), R2, R3; Section 8 by R4.



    - A dotted heading "1.6.1 ..." belongs to Section 1 wherever the "Section 1"

      banner sits, and its level is the depth of its number.

    - Each banner "Section N" + the heading after it ("Introduction") give the

      Section's path element "Section N: Introduction". The banner only supplies

      the title: Section 1's banner comes after 1.1-1.3 in reading order.

    - R3: in Sections 1-7, unnumbered headings ("Spouse", "Example") are body text.

    - Front matter before 1.1 has no section number; its headings stay headings

      (the document's title is text: the path root already says it).

    - Section 8 (Statutory Conditions) has no dotted numbers: its conditions are

      numbered list items, handled like an OPCF ("8.1" ... "8.13").

    """
    # Pass 1: banner titles, and the items they use up.
    titles: dict[int, str] = {}
    used: set[int] = set()
    for i, raw in enumerate(raws):
        m = BANNER.match(raw.text) if raw.kind == "heading" else None
        if not m:
            continue
        used.add(i)
        for j in range(i + 1, len(raws)):
            if raws[j].kind == "heading":
                titles[int(m.group(1))] = raws[j].text
                used.add(j)
                break

    b = Builder()
    current: int | None = None  # the Section we are in
    section: str | None = None

    def enter(n: int) -> None:
        nonlocal current, section
        current, section = n, str(n)
        b.heading(f"Section {n}: {titles.get(n, '')}".rstrip(": "), 1, section)

    for i, raw in enumerate(raws):
        if i in used:
            m = BANNER.match(raw.text)
            if m and int(m.group(1)) != current:
                enter(int(m.group(1)))
                if current == 8:
                    rest = [r for j, r in enumerate(raws[i + 1 :], i + 1) if j not in used]
                    structure_list_sections(
                        rest, b, base=1, prefix="8.", label="Statutory Condition",
                        section="8",
                    )  # fmt: skip
                    break
            continue
        if raw.kind != "heading":
            b.body(raw, section)
            continue
        parts = split_number(raw.text)
        if parts and "." in parts[0]:  # R1
            n = top(parts[0])
            if n != current:
                enter(n)
            section = parts[0]
            b.heading(raw.text, parts[0].count(".") + 1, section)
        elif current is None:
            b.heading(raw.text, 1, None)  # front matter: "About This Policy"
        else:  # R3: text, glued to what follows it (see Builder)
            b.body(raw, section)
    return b.done()


LAW_SECTION = re.compile(r"^Section (\d+(?:\.\d+)*(?:-\d+(?:\.\d+)*)?)(?::|$)")


def structure_law(raws: list[Raw], doc: DoclingDocument) -> list[Piece]:
    """Laws are already structured by parse.py: Part (1) > group (2) > "Section N: ..." (3).

    Keep the levels; the section number is the N in "Section N".



    Text between a group heading and the next section is moved to the start of that

    section: in the Insurance Act, "Policy coverage" (a second headnote, kept as a

    caption by parse.py) sits between "Motor Vehicle Liability Policies" and s. 239.

    The same goes for a caption directly before a section: it titles what follows.

    """
    levels = {
        item.self_ref: item.level for item, _ in doc.iterate_items()
        if isinstance(item, SectionHeaderItem)
    }  # fmt: skip
    b = Builder()
    section: str | None = None
    started = False  # seen a first section: text before it is the law's preamble
    waiting: list[Raw] = []  # text after a group heading, before its first section
    for i, raw in enumerate(raws):
        nxt = raws[i + 1] if i + 1 < len(raws) else None
        opens_next = nxt is not None and nxt.kind == "heading" and LAW_SECTION.match(nxt.text)
        if raw.kind != "heading":
            # waits for the next section: text after a group heading, or a headnote right
            # before a section ("Policy, formal requirements" titles s. 232, not s. 231)
            if started and (section is None or (opens_next and is_label(raw))):
                waiting.append(raw)
            else:
                b.body(raw, section)
            continue
        m = LAW_SECTION.match(raw.text)
        level = levels.get(raw.item.self_ref, 1)
        if m:
            section, started = m.group(1), True
        elif level <= 2:  # a new Part or group ends the previous section
            section = None
        b.heading(raw.text, level, section)
        if section is not None:
            for w in waiting:
                b.body(w, section)
            waiting = []
    for w in waiting:  # text after the last group, with no section after it
        b.body(w, None)
    return b.done()


def is_law(row: dict[str, str]) -> bool:
    return Path(row["filename"]).suffix.lower() == ".docx"


def structure(doc: DoclingDocument, row: dict[str, str]) -> list[Piece]:
    """Apply the right structure rules for this document."""
    raws = read_items(doc)
    if is_law(row):
        return structure_law(raws, doc)
    raws = classify_headings(raws, row)
    if row["form_id"] == "OAP 1":
        return structure_oap1(raws)
    return structure_opcf(raws)


# --- 3. rebuild + chunk -----------------------------------------------------------------


def root_title(row: dict[str, str]) -> str:
    """Path root: "OPCF 44R: Family Protection Coverage"."""
    return f"{row['form_id']}: {row['title']}"


def rebuild(pieces: list[Piece], row: dict[str, str]) -> tuple[DoclingDocument, dict[str, str]]:
    """A clean DoclingDocument from the Pieces. Body items keep their page provenance.



    Returns the document and {self_ref of each body item: section number} so every

    chunk can be traced back to its section without parsing heading strings.

    """
    doc = DoclingDocument(name=row["doc_id"])
    doc.add_title(root_title(row))
    sections: dict[str, str] = {}
    for p in pieces:
        if p.kind == "heading":
            doc.add_heading(p.text, level=p.level)
            continue
        new = doc.add_text(label=DocItemLabel.TEXT, text=p.text)
        new.prov = [prov for item in p.items for prov in item.prov]
        sections[new.self_ref] = p.section or ""
    return doc, sections


@cache
def tokenizer() -> HuggingFaceTokenizer:
    """The embedding model's own tokenizer, so "<= 400 tokens" means what it says."""
    return HuggingFaceTokenizer.from_pretrained(
        model_name=config.EMBED_MODEL, max_tokens=config.MAX_CHUNK_TOKENS
    )


@cache
def chunker() -> HybridChunker:
    # merge_peers: small neighbouring chunks under the same headings are merged.
    return HybridChunker(tokenizer=tokenizer(), merge_peers=True)


def source_id(doc_id: str, section: str | None) -> str:
    return f"{doc_id}#{section}" if section else doc_id


def pages(items: list[DocItem]) -> tuple[int | None, int | None]:
    numbers = [p.page_no for item in items for p in item.prov]
    return (min(numbers), max(numbers)) if numbers else (None, None)


def none_if_blank(value: str) -> str | None:
    return value or None


def doc_fields(row: dict[str, str]) -> dict[str, str | None]:
    """Columns every chunk/section row of one document shares."""
    return {
        "doc_id": row["doc_id"],
        "form_id": row["form_id"],
        "title": row["title"],
        "version": row["version"],
        "effective_from": none_if_blank(row["effective_from"]),
        "effective_to": none_if_blank(row["effective_to"]),
        # the doc_id this one replaces (OPCF 47R -> OPCF 47): Step 3c's version filter
        "supersedes": none_if_blank(row["supersedes"]),
        "url": row["url"],
    }


def unmark(serialized: str) -> str:
    """Undo the one change Docling's serializer makes to our text: it writes a line

    break as a markdown hard break ("  \n"). clean_text() never leaves spaces before

    a line break, so this restores the stored text exactly."""
    return serialized.replace("  \n", "\n")


def chunk_document(pieces: list[Piece], row: dict[str, str]) -> list[dict]:
    """Chunk one structured document with HybridChunker; one dict per chunk."""
    doc, sections = rebuild(pieces, row)
    counter: dict[str, int] = {}
    records = []
    for chunk in chunker().chunk(doc):
        found = {sections[item.self_ref] for item in chunk.meta.doc_items}
        if len(found) != 1:  # can't happen: every section starts with its own heading
            raise AssertionError(f"{row['doc_id']}: chunk spans sections {sorted(found)}")
        section = found.pop() or None
        sid = source_id(row["doc_id"], section)
        k = counter[sid] = counter.get(sid, -1) + 1
        start, end = pages(chunk.meta.doc_items)
        embed_text = unmark(chunker().contextualize(chunk))
        records.append(
            {
                "chunk_id": f"{sid}:{k}",  # readable and stable: same input, same ids
                **doc_fields(row),
                "source_id": sid,
                "section_number": section,
                "heading_path": " > ".join(chunk.meta.headings or []),
                "text": unmark(chunk.text),
                "embed_text": embed_text,
                "n_tokens": tokenizer().count_tokens(embed_text),
                "page_start": start,
                "page_end": end,
                "xrefs": [],  # filled by xref.py (Step 2d)
            }
        )
    return records


# --- sections table ---------------------------------------------------------------------


def covers(parent: str | None, child: str | None, dotted: bool) -> bool:
    """Does citing `parent` cover `child`? None (the whole document) covers everything.



    In the FSRA forms numbers nest by dots ("6.4" covers "6.4.2"; "8.1" does not

    cover "8.10"). In laws they don't: s. 3.1 is its own section, not part of s. 3.

    """
    if parent is None:
        return True
    if child is None:
        return False
    return child == parent or (dotted and child.startswith(parent + "."))


def parent_section(number: str | None, numbers: set[str | None], dotted: bool) -> str | None:
    """The nearest enclosing section that exists: "6.4.2" -> "6.4"; OAP 1 "8.10" -> "8";

    a top-level section or any law section -> None (the whole document). Stored so later

    steps (parent expansion, citation fallback) never guess from string prefixes."""
    if number is None or not dotted:
        return None
    parts = number.split(".")
    while len(parts) > 1:
        parts.pop()
        if ".".join(parts) in numbers:
            return ".".join(parts)
    return None


def section_records(pieces: list[Piece], row: dict[str, str]) -> list[dict]:
    """One row per citable source_id: the full text of that section, headings included,

    with every nested sub-section. The bare doc_id row is the whole document."""
    dotted = not is_law(row)
    path: dict[int, str] = {}
    first_path: dict[str | None, str] = {}
    for p in pieces:  # the heading path where each section starts
        if p.kind == "heading":
            path = {lvl: t for lvl, t in path.items() if lvl < p.level} | {p.level: p.text}
            first_path.setdefault(p.section, " > ".join([root_title(row), *path.values()]))
    numbers = [None, *dict.fromkeys(p.section for p in pieces if p.section)]
    records = []
    for number in numbers:
        members = [p for p in pieces if covers(number, p.section, dotted)]
        start, end = pages([item for p in members for item in p.items])
        parent = parent_section(number, set(numbers), dotted)
        records.append(
            {
                "source_id": source_id(row["doc_id"], number),
                # None for the whole document; "OAP1-2026#6.4" for 6.4.2; the doc_id for
                # a law section (s. 268.3 is not part of s. 268)
                "parent_source_id": None if number is None else source_id(row["doc_id"], parent),
                **doc_fields(row),
                "section_number": number,
                "heading_path": first_path.get(number, root_title(row)),
                "text": "\n".join(p.text for p in members),
                "page_start": start,
                "page_end": end,
            }
        )
    return records


# --- naive chunks (System A) ------------------------------------------------------------


def naive_text(doc: DoclingDocument) -> tuple[str, list[tuple[int, int, DocItem]]]:
    """What a developer gets from Docling by default, untouched: the body items in

    reading order with their text exactly as extracted (no text.py cleaning, table of

    contents and form-field text included, page headers/footers excluded as in

    Docling's default export). Tables are their grid rows, cells joined by " | ".



    Returns the text (items joined by line breaks) and each item's character span,

    so a window can be mapped back to pages and sections.

    """
    parts: list[str] = []
    spans: list[tuple[int, int, DocItem]] = []
    pos = 0
    for item, _ in doc.iterate_items():
        if isinstance(item, TableItem):
            text = "\n".join(" | ".join(c.text for c in row) for row in item.data.grid)
        elif isinstance(item, ListItem):
            text = f"{item.marker} {item.text}" if item.marker else item.text
        elif isinstance(item, TextItem):
            text = item.text
        else:  # pictures carry no text
            continue
        if not text.strip():
            continue
        spans.append((pos, pos + len(text), item))
        parts.append(text)
        pos += len(text) + 1  # the "\n" that joins items
    return "\n".join(parts), spans


def windows(text: str, size: int, overlap: int) -> list[tuple[int, int]]:
    """Fixed-size character windows [start, end): each at most `size` characters,

    neighbours share at most `overlap`. Cuts move back to whitespace (never further

    than half a window) and starts move forward to a word start, so words aren't cut

    unless one is longer than half a window."""
    spans: list[tuple[int, int]] = []
    start, n = 0, len(text)
    while start < n:
        end = min(start + size, n)
        if end < n:
            cut = next((j for j in range(end, start + size // 2, -1) if text[j].isspace()), end)
            end = cut
        if text[start:end].strip():
            spans.append((start, end))
        if end >= n:
            break
        nxt = max(end - overlap, start + 1)
        while nxt < end and not (text[nxt - 1].isspace()):
            nxt += 1  # don't start in the middle of a word
        start = nxt
    return spans


def naive_chunks(doc: DoclingDocument, pieces: list[Piece], row: dict[str, str]) -> list[dict]:
    """System A's chunks: fixed 800-character windows (100 overlap) over naive_text().



    The model sees only `text` and cites the whole document (source_id = doc_id).

    `covers_sources` lists the structured sections whose text the window contains; it

    is for evaluation only (recall@k against gold sources), never shown to the model.

    A window covers a section only if it holds at least NAIVE_COVER_MIN_CHARS of that

    section's text (or all of it, if the section is shorter): touching a section's

    first line at a window's edge doesn't count as retrieving it.

    """
    text, spans = naive_text(doc)
    section_of = {item.self_ref: p.section for p in pieces for item in p.items}
    size: dict[str | None, int] = {}  # characters of each section in the naive text
    for s, e, item in spans:
        if item.self_ref in section_of:
            sec = section_of[item.self_ref]
            size[sec] = size.get(sec, 0) + e - s
    records = []
    for k, (start, end) in enumerate(
        windows(text, config.NAIVE_CHUNK_CHARS, config.NAIVE_CHUNK_OVERLAP)
    ):
        overlapping = [(s, e, item) for s, e, item in spans if s < end and e > start]
        page_start, page_end = pages([item for _, _, item in overlapping])
        held: dict[str | None, int] = {}  # characters of each section in this window
        for s, e, item in overlapping:
            if item.self_ref in section_of:
                sec = section_of[item.self_ref]
                held[sec] = held.get(sec, 0) + min(e, end) - max(s, start)
        covered = [
            sec for sec, n in held.items() if n >= min(config.NAIVE_COVER_MIN_CHARS, size[sec])
        ]
        records.append(
            {
                "chunk_id": f"{row['doc_id']}~{k}",
                **doc_fields(row),
                "source_id": row["doc_id"],
                "text": text[start:end],
                "char_start": start,
                "char_end": end,
                "page_start": page_start,
                "page_end": page_end,
                "covers_sources": list(dict.fromkeys(source_id(row["doc_id"], s) for s in covered)),
            }
        )
    return records


# --- command ----------------------------------------------------------------------------


def load_parsed(doc_id: str, parsed_dir: Path) -> DoclingDocument:
    return DoclingDocument.load_from_json(parsed_dir / f"{doc_id}.json")


def iter_documents(

    manifest: Path, parsed_dir: Path

) -> Iterator[tuple[dict[str, str], DoclingDocument]]:
    for row in read_manifest(manifest):
        yield row, load_parsed(row["doc_id"], parsed_dir)


def write_table(records: list[dict], path: Path) -> None:
    """Parquet with page numbers as nullable integers (laws have no pages)."""
    df = pd.DataFrame(records).astype({"page_start": "Int64", "page_end": "Int64"})
    df.to_parquet(path, index=False)


def run(manifest: Path, parsed_dir: Path, index_dir: Path) -> int:
    """Chunk every parsed document and link cross-references. Writes chunks.parquet,

    sections.parquet, xrefs.parquet (every reference found) and naive_chunks.parquet."""
    index_dir.mkdir(parents=True, exist_ok=True)
    chunks: list[dict] = []
    sections: list[dict] = []
    naive: list[dict] = []
    laws: set[str] = set()
    print(f"{'doc_id':<18} {'pieces':>6} {'sections':>8} {'chunks':>6} {'max tok':>7} {'naive':>6}")
    for row, doc in iter_documents(manifest, parsed_dir):
        pieces = structure(doc, row)
        records = chunk_document(pieces, row)
        section_rows = section_records(pieces, row)
        naive_rows = naive_chunks(doc, pieces, row)
        chunks += records
        sections += section_rows
        naive += naive_rows
        if is_law(row):
            laws.add(row["doc_id"])
        max_tok = max((r["n_tokens"] for r in records), default=0)
        print(
            f"{row['doc_id']:<18} {len(pieces):>6} {len(section_rows):>8} "
            f"{len(records):>6} {max_tok:>7} {len(naive_rows):>6}"
        )
    edges = xref.link_chunks(chunks, xref.CorpusIndex.from_sections(sections, laws))
    write_table(chunks, index_dir / "chunks.parquet")
    write_table(sections, index_dir / "sections.parquet")
    write_table(naive, index_dir / "naive_chunks.parquet")
    pd.DataFrame(edges).to_parquet(index_dir / "xrefs.parquet", index=False)
    status = pd.Series([e["status"] for e in edges]).value_counts().to_dict()
    print(f"\n{len(chunks)} chunks, {len(sections)} sections, {len(naive)} naive chunks")
    print(f"{len(edges)} cross-reference targets: {status} -> {index_dir}")
    return 0


def main() -> None:
    sys.exit(run(config.MANIFEST_PATH, config.PARSED_DIR, config.INDEX_DIR))


if __name__ == "__main__":
    main()