File size: 45,137 Bytes
62787e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import html
import json
import os
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

import fitz
import numpy as np
from PIL import Image, ImageDraw


MIN_NATIVE_SPAN_COUNT = 24


@dataclass
class StyledFragment:
    text: str
    bbox: Tuple[float, float, float, float]
    font: str
    flags: int
    size: float
    bold: bool
    italic: bool
    underline: bool

    def to_payload(self) -> Dict[str, Any]:
        return {
            "text": self.text,
            "bbox": [round(value, 2) for value in self.bbox],
            "font": self.font,
            "flags": int(self.flags),
            "size": round(float(self.size), 2),
            "bold": bool(self.bold),
            "italic": bool(self.italic),
            "underline": bool(self.underline),
        }


@dataclass
class RowGroup:
    cy: float
    items: List[StyledFragment]

    @property
    def bbox(self) -> Tuple[float, float, float, float]:
        return union_bbox(item.bbox for item in self.items)

    def to_payload(self) -> Dict[str, Any]:
        return {
            "bbox": [round(value, 2) for value in self.bbox],
            "text": " | ".join(item.text for item in self.items),
            "fragments": [item.to_payload() for item in self.items],
        }


@dataclass
class TableCandidate:
    rect: Tuple[float, float, float, float]
    source: str
    score: float
    rows: List[RowGroup]

    def to_payload(self) -> Dict[str, Any]:
        return {
            "bbox": [round(value, 2) for value in self.rect],
            "source": self.source,
            "score": round(float(self.score), 2),
            "row_count": len(self.rows),
            "fragment_count": sum(len(row.items) for row in self.rows),
            "rows": [row.to_payload() for row in self.rows],
        }


@dataclass
class TableCellCandidate:
    row: int
    col: int
    rowspan: int
    colspan: int
    bbox: Tuple[float, float, float, float]
    text: str
    html: str
    header: bool
    bold: bool
    italic: bool
    underline: bool

    def to_payload(self) -> Dict[str, Any]:
        return {
            "row": int(self.row),
            "col": int(self.col),
            "rowspan": int(self.rowspan),
            "colspan": int(self.colspan),
            "bbox": [round(value, 2) for value in self.bbox],
            "text": self.text,
            "html": self.html,
            "header": bool(self.header),
            "bold": bool(self.bold),
            "italic": bool(self.italic),
            "underline": bool(self.underline),
        }


@dataclass
class RasterCandidate:
    rect: Tuple[float, float, float, float]
    score: float
    row_count: int
    avg_components_per_row: float
    text_density: float
    line_density: float

    def to_payload(self) -> Dict[str, Any]:
        return {
            "bbox": [round(value, 2) for value in self.rect],
            "score": round(float(self.score), 2),
            "row_count": int(self.row_count),
            "avg_components_per_row": round(float(self.avg_components_per_row), 2),
            "text_density": round(float(self.text_density), 4),
            "line_density": round(float(self.line_density), 4),
        }


def union_bbox(boxes: Iterable[Sequence[float]]) -> Tuple[float, float, float, float]:
    points = [tuple(float(value) for value in box) for box in boxes]
    if not points:
        return (0.0, 0.0, 0.0, 0.0)
    return (
        min(box[0] for box in points),
        min(box[1] for box in points),
        max(box[2] for box in points),
        max(box[3] for box in points),
    )


def bbox_iou(box_a: Sequence[float], box_b: Sequence[float]) -> float:
    left = max(float(box_a[0]), float(box_b[0]))
    top = max(float(box_a[1]), float(box_b[1]))
    right = min(float(box_a[2]), float(box_b[2]))
    bottom = min(float(box_a[3]), float(box_b[3]))
    inter_w = max(0.0, right - left)
    inter_h = max(0.0, bottom - top)
    inter_area = inter_w * inter_h
    area_a = max(0.0, float(box_a[2]) - float(box_a[0])) * max(0.0, float(box_a[3]) - float(box_a[1]))
    area_b = max(0.0, float(box_b[2]) - float(box_b[0])) * max(0.0, float(box_b[3]) - float(box_b[1]))
    union = max(1e-6, area_a + area_b - inter_area)
    return inter_area / union


def width(box: Sequence[float]) -> float:
    return max(0.0, float(box[2]) - float(box[0]))


def height(box: Sequence[float]) -> float:
    return max(0.0, float(box[3]) - float(box[1]))


def center_y(box: Sequence[float]) -> float:
    return (float(box[1]) + float(box[3])) / 2.0


def center_x(box: Sequence[float]) -> float:
    return (float(box[0]) + float(box[2])) / 2.0


def is_numeric_like(text: str) -> bool:
    normalized = str(text or "").strip()
    if not normalized:
        return False
    return any(char.isdigit() for char in normalized)


def is_bold(font_name: str, flags: int) -> bool:
    font_name = str(font_name or "").lower()
    return "bold" in font_name or bool(int(flags or 0) & 16)


def is_italic(font_name: str, flags: int) -> bool:
    font_name = str(font_name or "").lower()
    return "italic" in font_name or "oblique" in font_name or bool(int(flags or 0) & 2)


def extract_horizontal_line_boxes(page: fitz.Page) -> List[Tuple[float, float, float, float]]:
    line_boxes: List[Tuple[float, float, float, float]] = []
    for drawing in page.get_drawings():
        rect = drawing.get("rect")
        if rect is None:
            continue
        if rect.width <= 0 or rect.height > 2.5:
            continue
        line_boxes.append((rect.x0, rect.y0, rect.x1, rect.y1))
    return line_boxes


def span_has_underline(
    bbox: Sequence[float],
    *,
    line_boxes: Sequence[Sequence[float]],
) -> bool:
    span_left, _span_top, span_right, span_bottom = (float(value) for value in bbox)
    span_width = max(1.0, span_right - span_left)
    for line_box in line_boxes:
        line_left, line_top, line_right, line_bottom = (float(value) for value in line_box)
        overlap = max(0.0, min(span_right, line_right) - max(span_left, line_left))
        if overlap < (0.60 * span_width):
            continue
        if abs(line_top - span_bottom) <= 2.5 or abs(line_bottom - span_bottom) <= 2.5:
            return True
    return False


def extract_styled_fragments(page: fitz.Page) -> List[StyledFragment]:
    rawdict = page.get_text("rawdict")
    line_boxes = extract_horizontal_line_boxes(page)
    fragments: List[StyledFragment] = []
    for block in rawdict.get("blocks", []):
        for line in block.get("lines", []):
            for span in line.get("spans", []):
                text = "".join(char.get("c", "") for char in span.get("chars", [])).strip()
                if not text:
                    continue
                bbox = tuple(float(value) for value in span.get("bbox", (0, 0, 0, 0)))
                font = str(span.get("font") or "")
                flags = int(span.get("flags") or 0)
                fragments.append(
                    StyledFragment(
                        text=text,
                        bbox=bbox,
                        font=font,
                        flags=flags,
                        size=float(span.get("size") or 0.0),
                        bold=is_bold(font, flags),
                        italic=is_italic(font, flags),
                        underline=span_has_underline(bbox, line_boxes=line_boxes),
                    )
                )
    return fragments


def extract_layout_fragments(page: fitz.Page) -> List[StyledFragment]:
    words = page.get_text("words", sort=True)
    grouped_words: Dict[Tuple[int, int], List[Tuple[float, float, float, float, str]]] = {}
    for word in words:
        if len(word) < 8:
            continue
        x0, y0, x1, y1, text, block_no, line_no, _word_no = word[:8]
        normalized_text = str(text or "").strip()
        if not normalized_text:
            continue
        grouped_words.setdefault((int(block_no), int(line_no)), []).append(
            (float(x0), float(y0), float(x1), float(y1), normalized_text)
        )

    fragments: List[StyledFragment] = []
    for _line_key, line_words in sorted(grouped_words.items(), key=lambda item: (item[0][0], item[0][1])):
        current_texts: List[str] = []
        current_boxes: List[Tuple[float, float, float, float]] = []
        previous_right: Optional[float] = None
        current_height = 0.0
        for x0, y0, x1, y1, text in sorted(line_words, key=lambda item: item[0]):
            box = (x0, y0, x1, y1)
            box_height = height(box)
            gap = float("inf") if previous_right is None else max(0.0, x0 - previous_right)
            merge_gap = max(8.0, current_height * 0.45, box_height * 0.45)
            if current_texts and gap > merge_gap:
                merged_box = union_bbox(current_boxes)
                fragments.append(
                    StyledFragment(
                        text=" ".join(current_texts),
                        bbox=merged_box,
                        font="",
                        flags=0,
                        size=max(current_height, 0.0),
                        bold=False,
                        italic=False,
                        underline=False,
                    )
                )
                current_texts = []
                current_boxes = []
                current_height = 0.0
            current_texts.append(text)
            current_boxes.append(box)
            current_height = max(current_height, box_height)
            previous_right = x1
        if current_texts:
            merged_box = union_bbox(current_boxes)
            fragments.append(
                StyledFragment(
                    text=" ".join(current_texts),
                    bbox=merged_box,
                    font="",
                    flags=0,
                    size=max(current_height, 0.0),
                    bold=False,
                    italic=False,
                    underline=False,
                )
            )
    return fragments


def group_rows(items: Sequence[StyledFragment], *, y_tolerance: float = 3.5) -> List[RowGroup]:
    rows: List[RowGroup] = []
    for item in sorted(items, key=lambda fragment: (center_y(fragment.bbox), fragment.bbox[0])):
        item_cy = center_y(item.bbox)
        if rows and abs(rows[-1].cy - item_cy) <= y_tolerance:
            rows[-1].items.append(item)
            rows[-1].cy = float(np.mean([center_y(existing.bbox) for existing in rows[-1].items]))
            continue
        rows.append(RowGroup(cy=item_cy, items=[item]))
    return rows


def is_headerish_row(row: RowGroup, *, page_width: float) -> bool:
    bbox = row.bbox
    text = " ".join(item.text for item in row.items)
    centered = bbox[0] > (page_width * 0.25) and bbox[2] < (page_width * 0.85)
    short_text = len(text) <= 80
    return centered or short_text or row.items[0].italic


def _fragment_style_weight(fragment: StyledFragment) -> float:
    normalized_text = "".join(char for char in str(fragment.text or "") if not char.isspace())
    if normalized_text:
        return float(len(normalized_text))
    return max(1.0, width(fragment.bbox))


def _fragment_style_fraction(
    fragments: Sequence[StyledFragment],
    *,
    attr_name: str,
) -> float:
    total_weight = 0.0
    styled_weight = 0.0
    for fragment in fragments:
        weight = _fragment_style_weight(fragment)
        total_weight += weight
        if bool(getattr(fragment, attr_name, False)):
            styled_weight += weight
    if total_weight <= 0:
        return 0.0
    return styled_weight / total_weight


def _native_cell_bold_min_fraction() -> float:
    raw_value = str(os.getenv("PDF_NATIVE_CELL_BOLD_MIN_FRACTION", "0.60")).strip()
    try:
        return min(1.0, max(0.0, float(raw_value)))
    except ValueError:
        return 0.60


def drawing_based_candidates(page: fitz.Page) -> List[Tuple[float, float, float, float]]:
    candidate_boxes: List[Tuple[float, float, float, float]] = []
    page_width = float(page.rect.width)
    for drawing in page.get_drawings():
        rect = drawing.get("rect")
        if rect is None:
            continue
        candidate = (float(rect.x0), float(rect.y0), float(rect.x1), float(rect.y1))
        if width(candidate) < (page_width * 0.35):
            continue
        draw_type = str(drawing.get("type") or "")
        if draw_type in {"f", "fs"} and height(candidate) <= 30.0:
            candidate_boxes.append(candidate)
            continue
        if draw_type in {"s", "fs"} and height(candidate) <= 2.0:
            candidate_boxes.append(candidate)
    candidate_boxes.sort(key=lambda box: (box[1], box[0]))

    merged: List[Tuple[float, float, float, float]] = []
    for candidate in candidate_boxes:
        if (
            merged
            and candidate[1] - merged[-1][3] <= 18.0
            and min(candidate[2], merged[-1][2]) - max(candidate[0], merged[-1][0]) > (page_width * 0.20)
        ):
            merged[-1] = (
                min(merged[-1][0], candidate[0]),
                min(merged[-1][1], candidate[1]),
                max(merged[-1][2], candidate[2]),
                max(merged[-1][3], candidate[3]),
            )
            continue
        merged.append(candidate)
    return merged


def row_is_tabular_core(row: RowGroup) -> bool:
    numeric_count = sum(is_numeric_like(item.text) for item in row.items)
    if len(row.items) >= 4:
        return True
    if len(row.items) >= 3 and numeric_count >= 1:
        return True
    if len(row.items) >= 2 and numeric_count >= 2:
        return True
    return False


def row_is_tabular_support(row: RowGroup) -> bool:
    numeric_count = sum(is_numeric_like(item.text) for item in row.items)
    if row_is_tabular_core(row):
        return True
    if len(row.items) >= 2 and numeric_count >= 1:
        return True
    return False


def alignment_based_candidates(
    rows: Sequence[RowGroup],
    *,
    page_width: float,
) -> List[Tuple[float, float, float, float]]:
    candidates: List[Tuple[float, float, float, float]] = []
    index = 0
    while index < len(rows):
        row = rows[index]
        if not row_is_tabular_core(row):
            index += 1
            continue
        start = index
        end = index + 1
        while end < len(rows):
            row_gap = rows[end].bbox[1] - rows[end - 1].bbox[3]
            if row_gap > 22.0 or not row_is_tabular_support(rows[end]):
                break
            end += 1
        run = list(rows[start:end])
        core_count = sum(row_is_tabular_core(candidate_row) for candidate_row in run)
        avg_items = float(np.mean([len(candidate_row.items) for candidate_row in run])) if run else 0.0
        if core_count >= 3 and avg_items >= 2.8:
            expanded_start = start
            for _ in range(3):
                if expanded_start <= 0:
                    break
                previous_row = rows[expanded_start - 1]
                gap = rows[expanded_start].bbox[1] - previous_row.bbox[3]
                if gap > 18.0 or not is_headerish_row(previous_row, page_width=page_width):
                    break
                expanded_start -= 1
            expanded_end = end
            while expanded_end < len(rows):
                next_row = rows[expanded_end]
                if rows[expanded_end].bbox[1] - rows[expanded_end - 1].bbox[3] > 18.0:
                    break
                if len(next_row.items) > 2:
                    break
                next_text = " ".join(item.text for item in next_row.items).strip()
                if not next_text.startswith("("):
                    break
                expanded_end += 1
            run_rows = rows[expanded_start:expanded_end]
            candidate_box = union_bbox(row_group.bbox for row_group in run_rows)
            if width(candidate_box) >= (page_width * 0.35):
                candidates.append(candidate_box)
        index = max(end, index + 1)
    return candidates


def filter_fragments_in_rect(
    rect: Sequence[float],
    *,
    fragments: Sequence[StyledFragment],
) -> List[StyledFragment]:
    left, top, right, bottom = (float(value) for value in rect)
    kept: List[StyledFragment] = []
    for fragment in fragments:
        x0, y0, x1, y1 = fragment.bbox
        cx = (x0 + x1) / 2.0
        cy = (y0 + y1) / 2.0
        if left <= cx <= right and top <= cy <= bottom:
            kept.append(fragment)
    return kept


def score_candidate(
    rect: Sequence[float],
    *,
    fragments: Sequence[StyledFragment],
) -> Optional[TableCandidate]:
    inside_fragments = filter_fragments_in_rect(rect, fragments=fragments)
    if len(inside_fragments) < 6:
        return None
    rows = group_rows(inside_fragments)
    dense_rows = [row for row in rows if len(row.items) >= 2]
    if len(dense_rows) < 3:
        return None
    numeric_fragments = sum(is_numeric_like(fragment.text) for fragment in inside_fragments)
    bold_fragments = sum(bool(fragment.bold) for fragment in inside_fragments)
    score = (len(dense_rows) * 5.0) + min(20.0, float(numeric_fragments)) + min(10.0, float(bold_fragments))
    return TableCandidate(
        rect=tuple(float(value) for value in rect),
        source="scored",
        score=score,
        rows=rows,
    )


def dedupe_candidates(candidates: Sequence[TableCandidate]) -> List[TableCandidate]:
    kept: List[TableCandidate] = []
    for candidate in sorted(candidates, key=lambda item: (item.score, width(item.rect) * height(item.rect)), reverse=True):
        if any(bbox_iou(candidate.rect, existing.rect) >= 0.85 for existing in kept):
            continue
        kept.append(candidate)
    return kept


def render_fragment_html(fragment: StyledFragment) -> str:
    rendered = html.escape(fragment.text, quote=False)
    if fragment.bold:
        rendered = f"<strong>{rendered}</strong>"
    if fragment.italic:
        rendered = f"<em>{rendered}</em>"
    if fragment.underline:
        rendered = f"<u>{rendered}</u>"
    return rendered


def column_anchor_x(fragment: StyledFragment) -> float:
    if is_numeric_like(fragment.text):
        return float(fragment.bbox[2])
    return float(fragment.bbox[0])


def infer_column_centers(
    rows: Sequence[RowGroup],
    *,
    table_rect: Sequence[float],
) -> List[float]:
    table_width = width(table_rect)
    tolerance = max(14.0, table_width * 0.03)
    centers: List[float] = []
    counts: List[int] = []
    dense_rows = [row for row in rows if len(row.items) >= 2]
    for row in dense_rows:
        for item in sorted(row.items, key=lambda fragment: fragment.bbox[0]):
            item_center = column_anchor_x(item)
            matched_index: Optional[int] = None
            for index, existing_center in enumerate(centers):
                if abs(existing_center - item_center) <= tolerance:
                    matched_index = index
                    break
            if matched_index is None:
                centers.append(item_center)
                counts.append(1)
                continue
            counts[matched_index] += 1
            centers[matched_index] = (
                (centers[matched_index] * float(counts[matched_index] - 1)) + item_center
            ) / float(counts[matched_index])
    ranked_pairs = sorted(
        zip(centers, counts),
        key=lambda pair: pair[0],
    )
    filtered = [center for center, count in ranked_pairs if count >= 2]
    if filtered:
        return filtered
    if dense_rows:
        widest_row = max(dense_rows, key=lambda row: len(row.items))
        return [column_anchor_x(item) for item in sorted(widest_row.items, key=lambda fragment: fragment.bbox[0])]
    return []


def build_column_boundaries(
    column_centers: Sequence[float],
    *,
    table_rect: Sequence[float],
) -> List[float]:
    if not column_centers:
        return [float(table_rect[0]), float(table_rect[2])]
    boundaries = [float(table_rect[0])]
    sorted_centers = sorted(float(value) for value in column_centers)
    for index in range(len(sorted_centers) - 1):
        boundaries.append((sorted_centers[index] + sorted_centers[index + 1]) / 2.0)
    boundaries.append(float(table_rect[2]))
    return boundaries


def build_row_boundaries(
    rows: Sequence[RowGroup],
    *,
    table_rect: Sequence[float],
) -> List[float]:
    if not rows:
        return [float(table_rect[1]), float(table_rect[3])]
    boundaries = [float(table_rect[1])]
    for index in range(len(rows) - 1):
        boundaries.append((float(rows[index].bbox[3]) + float(rows[index + 1].bbox[1])) / 2.0)
    boundaries.append(float(table_rect[3]))
    return boundaries


def infer_header_row_count(rows: Sequence[RowGroup]) -> int:
    header_row_count = 0
    for row in rows[:3]:
        numeric_count = sum(is_numeric_like(item.text) for item in row.items)
        bold_count = sum(bool(item.bold) for item in row.items)
        if header_row_count == 0 and (numeric_count == 0 or len(row.items) <= 2):
            header_row_count += 1
            continue
        if numeric_count == 0 and len(row.items) >= 2:
            header_row_count += 1
            continue
        if bold_count >= max(1, len(row.items) - 1) and numeric_count <= 2:
            header_row_count += 1
            continue
        break
    return header_row_count


def assign_fragment_to_columns(
    fragment: StyledFragment,
    *,
    column_centers: Sequence[float],
    boundaries: Sequence[float],
    allow_spans: bool,
) -> Tuple[int, int]:
    if len(boundaries) < 2:
        return 0, 0
    item_left, _item_top, item_right, _item_bottom = fragment.bbox
    item_width = max(1.0, item_right - item_left)
    overlapping_columns: List[int] = []
    for index in range(len(boundaries) - 1):
        boundary_left = float(boundaries[index])
        boundary_right = float(boundaries[index + 1])
        overlap = max(0.0, min(item_right, boundary_right) - max(item_left, boundary_left))
        if overlap >= max(4.0, item_width * 0.12):
            overlapping_columns.append(index)
    if overlapping_columns:
        if not allow_spans:
            nearest_index = min(
                overlapping_columns,
                key=lambda index: abs(column_anchor_x(fragment) - float(column_centers[index])),
            )
            return nearest_index, nearest_index
        return overlapping_columns[0], overlapping_columns[-1]
    if not column_centers:
        return 0, 0
    nearest_index = min(
        range(len(column_centers)),
        key=lambda index: abs(column_anchor_x(fragment) - float(column_centers[index])),
    )
    return nearest_index, nearest_index


def infer_table_candidate_cells(candidate: TableCandidate) -> List[TableCellCandidate]:
    rows = [RowGroup(cy=row.cy, items=sorted(row.items, key=lambda fragment: fragment.bbox[0])) for row in candidate.rows]
    if not rows:
        return []
    column_centers = infer_column_centers(rows, table_rect=candidate.rect)
    if not column_centers:
        return []
    boundaries = build_column_boundaries(column_centers, table_rect=candidate.rect)
    row_boundaries = build_row_boundaries(rows, table_rect=candidate.rect)
    header_row_count = infer_header_row_count(rows)

    cells: List[TableCellCandidate] = []
    for row_index, row in enumerate(rows):
        assigned_cells: List[Dict[str, Any]] = []
        for fragment in row.items:
            start_column, end_column = assign_fragment_to_columns(
                fragment,
                column_centers=column_centers,
                boundaries=boundaries,
                allow_spans=(len(row.items) == 1),
            )
            fragment_html = render_fragment_html(fragment)
            if assigned_cells and start_column <= int(assigned_cells[-1]["end_column"]):
                assigned_cells[-1]["end_column"] = max(int(assigned_cells[-1]["end_column"]), end_column)
                assigned_cells[-1]["html"] += "<br>" + fragment_html
                assigned_cells[-1]["texts"].append(fragment.text)
                assigned_cells[-1]["fragments"].append(fragment)
                continue
            assigned_cells.append(
                {
                    "start_column": start_column,
                    "end_column": end_column,
                    "html": fragment_html,
                    "texts": [fragment.text],
                    "fragments": [fragment],
                }
            )

        cursor = 0
        for cell in assigned_cells:
            start_column = max(cursor, int(cell["start_column"]))
            end_column = max(start_column, int(cell["end_column"]))
            cursor = end_column + 1
            left = float(boundaries[start_column])
            right = float(boundaries[end_column + 1])
            top = float(row_boundaries[row_index])
            bottom = float(row_boundaries[row_index + 1])
            fragments = list(cell["fragments"])
            cells.append(
                TableCellCandidate(
                    row=row_index,
                    col=start_column,
                    rowspan=1,
                    colspan=max(1, end_column - start_column + 1),
                    bbox=(left, top, right, bottom),
                    text="\n".join(str(piece) for piece in cell["texts"] if str(piece).strip()),
                    html=str(cell["html"]),
                    header=(row_index < header_row_count),
                    bold=(
                        _fragment_style_fraction(fragments, attr_name="bold")
                        >= _native_cell_bold_min_fraction()
                    ),
                    italic=any(bool(fragment.italic) for fragment in fragments),
                    underline=any(bool(fragment.underline) for fragment in fragments),
                )
            )
    return cells


def render_table_candidate_html(candidate: TableCandidate) -> str:
    cells = infer_table_candidate_cells(candidate)
    if not cells:
        return ""
    row_count = max(int(cell.row + cell.rowspan) for cell in cells)
    column_count = max(int(cell.col + cell.colspan) for cell in cells)
    cells_by_row: Dict[int, List[TableCellCandidate]] = {}
    for cell in cells:
        cells_by_row.setdefault(int(cell.row), []).append(cell)

    parts: List[str] = ["<table>"]
    for row_index in range(row_count):
        row_cells = sorted(cells_by_row.get(row_index, []), key=lambda cell: (cell.col, cell.colspan))
        default_tag_name = "th" if any(bool(cell.header) for cell in row_cells) else "td"
        parts.append("<tr>")
        cursor = 0
        for cell in row_cells:
            start_column = max(cursor, int(cell.col))
            end_column = max(start_column, int(cell.col + cell.colspan - 1))
            while cursor < start_column:
                parts.append(f"<{default_tag_name}></{default_tag_name}>")
                cursor += 1
            colspan = max(1, end_column - start_column + 1)
            colspan_attr = f' colspan="{colspan}"' if colspan > 1 else ""
            tag_name = "th" if cell.header else "td"
            parts.append(f"<{tag_name}{colspan_attr}>{cell.html}</{tag_name}>")
            cursor = end_column + 1
        while cursor < column_count:
            parts.append(f"<{default_tag_name}></{default_tag_name}>")
            cursor += 1
        parts.append("</tr>")
    parts.append("</table>")
    return "".join(parts)


def detect_native_tables(page: fitz.Page) -> Dict[str, Any]:
    timings: Dict[str, float] = {}
    started_at = time.perf_counter()

    layout_started_at = time.perf_counter()
    layout_fragments = extract_layout_fragments(page)
    timings["layout_extraction_ms"] = (time.perf_counter() - layout_started_at) * 1000.0

    page_width = float(page.rect.width)
    grouped_rows = group_rows(layout_fragments)

    alignment_started_at = time.perf_counter()
    alignment_rects = alignment_based_candidates(grouped_rows, page_width=page_width)
    timings["alignment_candidate_ms"] = (time.perf_counter() - alignment_started_at) * 1000.0
    if not alignment_rects:
        timings["total_detection_ms"] = (time.perf_counter() - started_at) * 1000.0
        return {
            "mode": "pdf_native",
            "fragments": layout_fragments,
            "tables": [],
            "timings_ms": timings,
            "row_count": len(grouped_rows),
        }

    spans_started_at = time.perf_counter()
    fragments = extract_styled_fragments(page)
    timings["span_extraction_ms"] = (time.perf_counter() - spans_started_at) * 1000.0

    drawing_started_at = time.perf_counter()
    drawing_rects = drawing_based_candidates(page)
    timings["drawing_candidate_ms"] = (time.perf_counter() - drawing_started_at) * 1000.0

    scored_candidates: List[TableCandidate] = []
    for rect in [*drawing_rects, *alignment_rects]:
        candidate = score_candidate(rect, fragments=fragments)
        if candidate is None:
            continue
        candidate.source = "drawing" if rect in drawing_rects else "alignment"
        scored_candidates.append(candidate)

    deduped_candidates = dedupe_candidates(scored_candidates)
    timings["total_detection_ms"] = (time.perf_counter() - started_at) * 1000.0
    return {
        "mode": "pdf_native",
        "fragments": fragments,
        "tables": deduped_candidates,
        "timings_ms": timings,
        "row_count": len(grouped_rows),
    }


def render_page_image(page: fitz.Page, *, zoom: float = 2.0) -> Image.Image:
    pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False)
    return Image.frombytes("RGB", [pix.width, pix.height], pix.samples)


def group_component_boxes_into_rows(
    component_boxes: Sequence[Sequence[int]],
    *,
    y_tolerance: float,
) -> List[List[Tuple[int, int, int, int]]]:
    rows: List[List[Tuple[int, int, int, int]]] = []
    row_centers: List[float] = []
    for box in sorted(
        ((int(box[0]), int(box[1]), int(box[2]), int(box[3])) for box in component_boxes),
        key=lambda item: (((item[1] + item[3]) / 2.0), item[0]),
    ):
        cy = (box[1] + box[3]) / 2.0
        if rows and abs(row_centers[-1] - cy) <= y_tolerance:
            rows[-1].append(box)
            row_centers[-1] = float(np.mean([(item[1] + item[3]) / 2.0 for item in rows[-1]]))
            continue
        rows.append([box])
        row_centers.append(cy)
    return rows


def analyze_raster_candidate(
    *,
    text_mask: np.ndarray,
    line_mask: np.ndarray,
    x: int,
    y: int,
    width_px_box: int,
    height_px_box: int,
    scale_x: float,
    scale_y: float,
    page_height: float,
) -> Optional[RasterCandidate]:
    try:
        import cv2  # type: ignore
    except ImportError as exc:  # pragma: no cover - depends on environment
        raise RuntimeError("Raster fallback requires cv2 (opencv-python-headless).") from exc

    crop_text = text_mask[y : y + height_px_box, x : x + width_px_box]
    crop_lines = line_mask[y : y + height_px_box, x : x + width_px_box]
    if crop_text.size == 0:
        return None

    cc_kernel = cv2.getStructuringElement(
        cv2.MORPH_RECT,
        (max(4, width_px_box // 120), max(2, height_px_box // 160)),
    )
    grouped_components = cv2.dilate(crop_text, cc_kernel, iterations=1)
    component_count, _labels, stats, _centroids = cv2.connectedComponentsWithStats(grouped_components, connectivity=8)

    component_boxes: List[Tuple[int, int, int, int]] = []
    for component_index in range(1, component_count):
        comp_x, comp_y, comp_w, comp_h, comp_area = stats[component_index]
        if comp_area < 20 or comp_w < 4 or comp_h < 4:
            continue
        component_boxes.append((comp_x, comp_y, comp_x + comp_w, comp_y + comp_h))

    row_groups = group_component_boxes_into_rows(
        component_boxes,
        y_tolerance=max(8.0, height_px_box * 0.01),
    )
    populated_rows = [row for row in row_groups if row]
    row_count = len(populated_rows)
    avg_components_per_row = (
        float(np.mean([len(row) for row in populated_rows])) if populated_rows else 0.0
    )
    line_density = float((crop_lines > 0).mean())
    text_density = float((crop_text > 0).mean())

    # Narrative paragraphs tend to have dense full-width text and fewer disconnected
    # column clusters per row than real tables.
    if line_density < 0.003 and avg_components_per_row < 2.4:
        return None
    if text_density > 0.09 and line_density < 0.003:
        return None
    if line_density > 0.12:
        return None
    if row_count < 4:
        return None

    left = x * scale_x
    top = y * scale_y
    right = (x + width_px_box) * scale_x
    bottom = (y + height_px_box) * scale_y
    candidate_box = (left, top, right, bottom)
    score = (
        (avg_components_per_row * 8.0)
        + (line_density * 220.0)
        + (text_density * 35.0)
        + (height(candidate_box) / max(1.0, page_height) * 8.0)
    )
    return RasterCandidate(
        rect=candidate_box,
        score=score,
        row_count=row_count,
        avg_components_per_row=avg_components_per_row,
        text_density=text_density,
        line_density=line_density,
    )


def detect_raster_table_regions(page: fitz.Page) -> Dict[str, Any]:
    try:
        import cv2  # type: ignore
    except ImportError as exc:  # pragma: no cover - depends on environment
        raise RuntimeError("Raster fallback requires cv2 (opencv-python-headless).") from exc

    timings: Dict[str, float] = {}
    started_at = time.perf_counter()

    render_started_at = time.perf_counter()
    image = render_page_image(page, zoom=2.0)
    timings["render_ms"] = (time.perf_counter() - render_started_at) * 1000.0

    grayscale_started_at = time.perf_counter()
    rgb = np.asarray(image, dtype=np.uint8)
    gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
    _threshold, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    timings["binarize_ms"] = (time.perf_counter() - grayscale_started_at) * 1000.0

    morphology_started_at = time.perf_counter()
    height_px, width_px = gray.shape[:2]
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (max(40, width_px // 25), 1))
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, max(40, height_px // 25)))
    horizontal = cv2.morphologyEx(binary, cv2.MORPH_OPEN, horizontal_kernel)
    vertical = cv2.morphologyEx(binary, cv2.MORPH_OPEN, vertical_kernel)
    line_mask = cv2.bitwise_or(horizontal, vertical)
    text_mask = cv2.subtract(binary, line_mask)
    text_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (max(8, width_px // 180), max(6, height_px // 180)))
    grouped_text = cv2.dilate(text_mask, text_kernel, iterations=1)
    candidate_mask = cv2.dilate(
        cv2.bitwise_or(grouped_text, line_mask),
        cv2.getStructuringElement(cv2.MORPH_RECT, (max(20, width_px // 80), max(20, height_px // 80))),
        iterations=1,
    )
    contours, _hierarchy = cv2.findContours(candidate_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    timings["morphology_ms"] = (time.perf_counter() - morphology_started_at) * 1000.0

    scale_x = float(page.rect.width) / float(width_px)
    scale_y = float(page.rect.height) / float(height_px)
    candidates: List[RasterCandidate] = []
    for contour in contours:
        x, y, width_px_box, height_px_box = cv2.boundingRect(contour)
        if width_px_box < (width_px * 0.20) or height_px_box < (height_px * 0.05):
            continue
        candidate = analyze_raster_candidate(
            text_mask=text_mask,
            line_mask=line_mask,
            x=x,
            y=y,
            width_px_box=width_px_box,
            height_px_box=height_px_box,
            scale_x=scale_x,
            scale_y=scale_y,
            page_height=float(page.rect.height),
        )
        if candidate is not None:
            candidates.append(candidate)

    kept: List[RasterCandidate] = []
    for candidate in sorted(candidates, key=lambda item: item.score, reverse=True):
        if any(bbox_iou(candidate.rect, existing.rect) >= 0.85 for existing in kept):
            continue
        kept.append(candidate)

    timings["total_detection_ms"] = (time.perf_counter() - started_at) * 1000.0
    return {
        "mode": "image_morphology",
        "tables": kept[:6],
        "timings_ms": timings,
    }


def detect_tables_on_page(page: fitz.Page) -> Dict[str, Any]:
    native_result = detect_native_tables(page)
    native_fragment_count = len(native_result["fragments"])
    if native_fragment_count >= MIN_NATIVE_SPAN_COUNT:
        return native_result

    raster_result = detect_raster_table_regions(page)
    if native_result["tables"]:
        return native_result
    return raster_result


def build_table_payload(candidate: TableCandidate) -> Dict[str, Any]:
    payload = candidate.to_payload()
    payload["cells"] = [cell.to_payload() for cell in infer_table_candidate_cells(candidate)]
    html_fragment = render_table_candidate_html(candidate)
    if html_fragment:
        payload["html"] = html_fragment
    return payload


def save_overlay(
    page: fitz.Page,
    *,
    detection_payload: Dict[str, Any],
    output_path: Path,
) -> None:
    image = render_page_image(page, zoom=2.0)
    draw = ImageDraw.Draw(image)
    scale_x = float(image.width) / float(page.rect.width)
    scale_y = float(image.height) / float(page.rect.height)

    def scale_box(box: Sequence[float]) -> Tuple[float, float, float, float]:
        return (
            float(box[0]) * scale_x,
            float(box[1]) * scale_y,
            float(box[2]) * scale_x,
            float(box[3]) * scale_y,
        )

    if detection_payload.get("mode") == "pdf_native":
        for table in detection_payload.get("tables", []):
            draw.rectangle(scale_box(table.rect), outline=(220, 40, 40), width=5)
            for row in table.rows:
                draw.rectangle(scale_box(row.bbox), outline=(255, 140, 0), width=2)
                for fragment in row.items:
                    outline_color = (40, 170, 40) if fragment.bold else (40, 120, 220)
                    draw.rectangle(scale_box(fragment.bbox), outline=outline_color, width=1)
    else:
        for table in detection_payload.get("tables", []):
            box = table.rect if isinstance(table, RasterCandidate) else table["bbox"]
            draw.rectangle(scale_box(box), outline=(220, 40, 40), width=5)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    image.save(output_path)


def build_payload(
    pdf_path: Path,
    *,
    page_number: int,
    detection_payload: Dict[str, Any],
) -> Dict[str, Any]:
    payload: Dict[str, Any] = {
        "pdf_path": str(pdf_path),
        "page_number": int(page_number),
        "mode": detection_payload.get("mode"),
        "timings_ms": {
            key: round(float(value), 2)
            for key, value in dict(detection_payload.get("timings_ms") or {}).items()
        },
    }
    if detection_payload.get("mode") == "pdf_native":
        payload["native_fragment_count"] = len(detection_payload.get("fragments") or [])
        payload["tables"] = [build_table_payload(table) for table in detection_payload.get("tables") or []]
        payload["html_fragments"] = [
            str(table_payload["html"])
            for table_payload in payload["tables"]
            if isinstance(table_payload, dict) and isinstance(table_payload.get("html"), str) and table_payload.get("html")
        ]
    else:
        payload["tables"] = [table.to_payload() for table in detection_payload.get("tables") or []]
        payload["html_fragments"] = []
    return payload


def detect_tables_for_page_number(document: fitz.Document, *, page_number: int) -> Dict[str, Any]:
    opened_at = time.perf_counter()
    page = document.load_page(page_number - 1)
    detection_payload = detect_tables_on_page(page)
    detection_payload.setdefault("timings_ms", {})
    detection_payload["timings_ms"]["open_and_dispatch_ms"] = (time.perf_counter() - opened_at) * 1000.0
    return detection_payload


def extract_tables_from_pdf_page(
    pdf_path: Path | str,
    *,
    page_number: int,
    overlay_path: Optional[Path | str] = None,
) -> Dict[str, Any]:
    resolved_pdf_path = Path(pdf_path).resolve()
    with fitz.open(str(resolved_pdf_path)) as document:
        detection_payload = detect_tables_for_page_number(document, page_number=page_number)
        if overlay_path:
            overlay_started_at = time.perf_counter()
            page = document.load_page(page_number - 1)
            save_overlay(page, detection_payload=detection_payload, output_path=Path(overlay_path).resolve())
            detection_payload["timings_ms"]["overlay_ms"] = (time.perf_counter() - overlay_started_at) * 1000.0
    return build_payload(resolved_pdf_path, page_number=page_number, detection_payload=detection_payload)


def summarize_document_payloads(page_payloads: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
    latencies_ms = [
        float(page_payload.get("timings_ms", {}).get("open_and_dispatch_ms"))
        for page_payload in page_payloads
        if isinstance(page_payload.get("timings_ms", {}).get("open_and_dispatch_ms"), (int, float))
    ]
    if latencies_ms:
        latency_array = np.asarray(latencies_ms, dtype=float)
        latency_summary = {
            "median_ms": round(float(np.median(latency_array)), 2),
            "p95_ms": round(float(np.percentile(latency_array, 95)), 2),
            "max_ms": round(float(np.max(latency_array)), 2),
        }
    else:
        latency_summary = {}
    return {
        "pages": len(page_payloads),
        "pages_with_tables": sum(bool(page_payload.get("tables")) for page_payload in page_payloads),
        "native_pages": sum(page_payload.get("mode") == "pdf_native" for page_payload in page_payloads),
        "raster_pages": sum(page_payload.get("mode") == "image_morphology" for page_payload in page_payloads),
        "latency_ms": latency_summary,
    }


def extract_tables_from_pdf_document(
    pdf_path: Path | str,
    *,
    page_numbers: Optional[Sequence[int]] = None,
) -> Dict[str, Any]:
    resolved_pdf_path = Path(pdf_path).resolve()
    with fitz.open(str(resolved_pdf_path)) as document:
        total_pages = int(document.page_count)
        selected_pages = (
            [page_number for page_number in page_numbers if 1 <= int(page_number) <= total_pages]
            if page_numbers is not None
            else list(range(1, total_pages + 1))
        )
        page_payloads = [
            build_payload(
                resolved_pdf_path,
                page_number=page_number,
                detection_payload=detect_tables_for_page_number(document, page_number=page_number),
            )
            for page_number in selected_pages
        ]
    return {
        "pdf_path": str(resolved_pdf_path),
        "page_count": len(page_payloads),
        "pages": page_payloads,
        "summary": summarize_document_payloads(page_payloads),
    }


def extract_table_html_fragments_from_pdf_page(
    pdf_path: Path | str,
    *,
    page_number: int,
) -> List[str]:
    payload = extract_tables_from_pdf_page(pdf_path, page_number=page_number)
    return [str(fragment) for fragment in payload.get("html_fragments") or [] if str(fragment).strip()]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Fast table bbox/style extraction for PDF pages using native PDF spans and a lightweight raster fallback."
    )
    parser.add_argument("--pdf", required=True, help="Path to the input PDF.")
    parser.add_argument("--page", type=int, help="1-based page number.")
    parser.add_argument("--all-pages", action="store_true", help="Process the full PDF instead of a single page.")
    parser.add_argument("--output-json", help="Optional JSON output path.")
    parser.add_argument("--overlay-png", help="Optional debug overlay PNG path.")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    pdf_path = Path(args.pdf).resolve()
    if not args.all_pages and args.page is None:
        raise SystemExit("Pass --page N for a single page or --all-pages for a full-document run.")

    if args.all_pages:
        if args.overlay_png:
            raise SystemExit("--overlay-png is only supported with single-page mode.")
        payload = extract_tables_from_pdf_document(pdf_path)
    else:
        payload = extract_tables_from_pdf_page(
            pdf_path,
            page_number=max(1, int(args.page)),
            overlay_path=(Path(args.overlay_png).resolve() if args.overlay_png else None),
        )
    rendered = json.dumps(payload, indent=2, sort_keys=True)
    print(rendered)
    if args.output_json:
        output_path = Path(args.output_json).resolve()
        output_path.parent.mkdir(parents=True, exist_ok=True)
        output_path.write_text(rendered + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()