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
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
#!/usr/bin/env python3
"""Audit evaluator-private SAM2 masks without modifying dataset artifacts.

The audit joins ``metadata/manifest.json`` with ``metadata/sam2_masks.jsonl``,
decodes every referenced mask, recomputes geometry and prompt-point metrics,
and emits a machine-readable JSON report plus a compact Markdown review table.
Suspicious mask geometry is a visual-review flag and does not make the command
fail. Missing, malformed, duplicated, or internally inconsistent artifacts are
structural errors and produce exit 2.

Connected components use OpenCV when available, then SciPy, and finally a
memory-conscious run-length/union-find implementation with 8-connectivity.
"""

from __future__ import annotations

import argparse
import json
import math
import sys
from collections import Counter
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Iterable

import numpy as np
from PIL import Image, ImageOps


DEFAULT_DATASET_ROOT = Path(__file__).resolve().parents[1]


@dataclass(frozen=True)
class StructuralIssue:
    code: str
    location: str
    message: str


class StructuralRecorder:
    def __init__(self) -> None:
        self.errors: list[StructuralIssue] = []

    def add(self, code: str, location: str, message: str) -> None:
        self.errors.append(StructuralIssue(code, location, message))


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT)
    parser.add_argument("--manifest", type=Path, default=None)
    parser.add_argument("--sam2-audit", type=Path, default=None)
    parser.add_argument("--output-json", type=Path, default=None)
    parser.add_argument("--output-markdown", type=Path, default=None)
    parser.add_argument("--case-id", action="append", default=[], help="Audit only these case IDs.")
    parser.add_argument("--pair", action="append", choices=("A", "B"), default=[])
    parser.add_argument(
        "--component-backend",
        choices=("auto", "opencv", "scipy", "rle"),
        default="auto",
        help="8-connected-component implementation; auto prefers OpenCV, then SciPy.",
    )
    parser.add_argument("--min-mask-area-ratio", type=float, default=0.001)
    parser.add_argument("--max-mask-area-ratio", type=float, default=0.40)
    parser.add_argument("--min-primary-component-fraction", type=float, default=0.85)
    parser.add_argument("--max-meaningful-components", type=int, default=3)
    parser.add_argument("--max-raw-components", type=int, default=100)
    parser.add_argument("--component-min-pixels", type=int, default=64)
    parser.add_argument("--component-min-fraction", type=float, default=0.001)
    parser.add_argument("--max-bbox-leak-ratio", type=float, default=0.03)
    parser.add_argument("--min-prompt-box-fill-ratio", type=float, default=0.02)
    parser.add_argument("--min-mask-bbox-prompt-iou", type=float, default=0.15)
    parser.add_argument("--min-sam-score", type=float, default=0.70)
    return parser.parse_args()


def validate_thresholds(args: argparse.Namespace) -> None:
    fraction_names = (
        "min_mask_area_ratio",
        "max_mask_area_ratio",
        "min_primary_component_fraction",
        "component_min_fraction",
        "max_bbox_leak_ratio",
        "min_prompt_box_fill_ratio",
        "min_mask_bbox_prompt_iou",
        "min_sam_score",
    )
    for name in fraction_names:
        value = float(getattr(args, name))
        if not math.isfinite(value) or not 0.0 <= value <= 1.0:
            raise ValueError(f"--{name.replace('_', '-')} must be in [0, 1]")
    if args.min_mask_area_ratio > args.max_mask_area_ratio:
        raise ValueError("--min-mask-area-ratio cannot exceed --max-mask-area-ratio")
    for name in ("max_meaningful_components", "max_raw_components", "component_min_pixels"):
        if int(getattr(args, name)) < 1:
            raise ValueError(f"--{name.replace('_', '-')} must be positive")


def read_json_object(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError(f"Expected a JSON object: {path}")
    return value


def read_jsonl(path: Path, recorder: StructuralRecorder) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    try:
        lines = path.read_text(encoding="utf-8").splitlines()
    except (OSError, UnicodeError) as exc:
        recorder.add("audit.unreadable", str(path), str(exc))
        return rows
    for line_number, line in enumerate(lines, start=1):
        location = f"{path}:{line_number}"
        if not line.strip():
            recorder.add("audit.blank_line", location, "Blank lines are not valid audit rows")
            continue
        try:
            value = json.loads(line)
        except json.JSONDecodeError as exc:
            recorder.add("audit.invalid_json", location, str(exc))
            continue
        if not isinstance(value, dict):
            recorder.add("audit.not_object", location, "Each JSONL row must be an object")
            continue
        rows.append(value)
    return rows


def nonempty_string(value: Any) -> bool:
    return isinstance(value, str) and bool(value.strip())


def safe_relative_path(
    root: Path, value: Any, recorder: StructuralRecorder, location: str
) -> Path | None:
    if not nonempty_string(value):
        recorder.add("path.invalid", location, "Expected a non-empty relative dataset path")
        return None
    relative = Path(value)
    if relative.is_absolute():
        recorder.add("path.absolute", location, f"Expected a relative path, got {value}")
        return None
    root = root.resolve()
    candidate = (root / relative).resolve(strict=False)
    try:
        candidate.relative_to(root)
    except ValueError:
        recorder.add("path.escape", location, f"Path escapes the dataset root: {value}")
        return None
    return candidate


def finite_float(value: Any) -> float | None:
    try:
        result = float(value)
    except (TypeError, ValueError):
        return None
    return result if math.isfinite(result) else None


def normalized_box(value: Any) -> tuple[float, float, float, float] | None:
    if not isinstance(value, (list, tuple)) or len(value) != 4:
        return None
    numbers = [finite_float(item) for item in value]
    if any(item is None for item in numbers):
        return None
    x1, y1, x2, y2 = (float(item) for item in numbers)
    if not (0.0 <= x1 < x2 <= 1.0 and 0.0 <= y1 < y2 <= 1.0):
        return None
    return x1, y1, x2, y2


def pixel_box(value: Any, width: int, height: int) -> tuple[int, int, int, int] | None:
    if not isinstance(value, (list, tuple)) or len(value) != 4:
        return None
    try:
        numbers = [int(item) for item in value]
    except (TypeError, ValueError, OverflowError):
        return None
    x1, y1, x2, y2 = numbers
    if not (0 <= x1 < x2 < width and 0 <= y1 < y2 < height):
        return None
    return x1, y1, x2, y2


def normalized_box_to_pixels(
    box: Iterable[float], width: int, height: int
) -> tuple[int, int, int, int]:
    box_values = tuple(float(item) for item in box)
    x1n, y1n, x2n, y2n = box_values
    values = (
        max(0, min(width - 1, round(x1n * width))),
        max(0, min(height - 1, round(y1n * height))),
        max(0, min(width - 1, round(x2n * width))),
        max(0, min(height - 1, round(y2n * height))),
    )
    x1, y1, x2, y2 = values
    if x1 >= x2 or y1 >= y2:
        raise ValueError(f"Normalized box becomes degenerate at {width}x{height}: {box_values}")
    return values


def normalized_points_to_pixels(value: Any, width: int, height: int) -> list[list[int]] | None:
    if value is None:
        return []
    if not isinstance(value, list):
        return None
    result: list[list[int]] = []
    for point in value:
        if not isinstance(point, (list, tuple)) or len(point) != 2:
            return None
        x = finite_float(point[0])
        y = finite_float(point[1])
        if x is None or y is None or not (0.0 <= x <= 1.0 and 0.0 <= y <= 1.0):
            return None
        result.append(
            [
                max(0, min(width - 1, round(x * width))),
                max(0, min(height - 1, round(y * height))),
            ]
        )
    return result


def valid_pixel_points(value: Any, width: int, height: int) -> list[list[int]] | None:
    if value is None:
        return []
    if not isinstance(value, list):
        return None
    result: list[list[int]] = []
    for point in value:
        if not isinstance(point, (list, tuple)) or len(point) != 2:
            return None
        try:
            x, y = int(point[0]), int(point[1])
        except (TypeError, ValueError, OverflowError):
            return None
        if not (0 <= x < width and 0 <= y < height):
            return None
        result.append([x, y])
    return result


def _component_areas_opencv(mask: np.ndarray) -> list[int]:
    import cv2

    count, _labels, stats, _centroids = cv2.connectedComponentsWithStats(
        mask.astype(np.uint8, copy=False), connectivity=8
    )
    if count <= 1:
        return []
    return sorted((int(value) for value in stats[1:, cv2.CC_STAT_AREA]), reverse=True)


def _component_areas_scipy(mask: np.ndarray) -> list[int]:
    from scipy import ndimage

    labels, count = ndimage.label(mask, structure=np.ones((3, 3), dtype=np.uint8))
    if count == 0:
        return []
    areas = np.bincount(labels.reshape(-1), minlength=count + 1)[1:]
    return sorted((int(value) for value in areas), reverse=True)


def _component_areas_rle(mask: np.ndarray) -> list[int]:
    """Return 8-connected areas using row runs and a union-find forest."""

    if mask.ndim != 2:
        raise ValueError(f"Expected a 2-D mask, got shape {mask.shape}")
    parents: list[int] = []
    ranks: list[int] = []
    run_lengths: list[int] = []

    def add_node(length: int) -> int:
        node = len(parents)
        parents.append(node)
        ranks.append(0)
        run_lengths.append(length)
        return node

    def find(node: int) -> int:
        root = node
        while parents[root] != root:
            root = parents[root]
        while parents[node] != node:
            following = parents[node]
            parents[node] = root
            node = following
        return root

    def union(left: int, right: int) -> None:
        left_root = find(left)
        right_root = find(right)
        if left_root == right_root:
            return
        if ranks[left_root] < ranks[right_root]:
            left_root, right_root = right_root, left_root
        parents[right_root] = left_root
        if ranks[left_root] == ranks[right_root]:
            ranks[left_root] += 1

    # Tuples are (inclusive_start, inclusive_end, union_find_node).
    previous: list[tuple[int, int, int]] = []
    for row in np.asarray(mask, dtype=bool):
        padded = np.empty(row.size + 2, dtype=np.int8)
        padded[0] = 0
        padded[-1] = 0
        padded[1:-1] = row
        transitions = np.diff(padded)
        starts = np.flatnonzero(transitions == 1)
        ends = np.flatnonzero(transitions == -1) - 1
        current: list[tuple[int, int, int]] = []
        previous_cursor = 0
        for start_value, end_value in zip(starts.tolist(), ends.tolist()):
            start = int(start_value)
            end = int(end_value)
            node = add_node(end - start + 1)
            while previous_cursor < len(previous) and previous[previous_cursor][1] < start - 1:
                previous_cursor += 1
            overlap_cursor = previous_cursor
            while overlap_cursor < len(previous) and previous[overlap_cursor][0] <= end + 1:
                union(node, previous[overlap_cursor][2])
                overlap_cursor += 1
            current.append((start, end, node))
        previous = current

    totals: dict[int, int] = {}
    for node, length in enumerate(run_lengths):
        root = find(node)
        totals[root] = totals.get(root, 0) + length
    return sorted(totals.values(), reverse=True)


def choose_component_counter(name: str) -> tuple[str, Callable[[np.ndarray], list[int]]]:
    if name in ("auto", "opencv"):
        try:
            import cv2  # noqa: F401
        except ImportError:
            if name == "opencv":
                raise RuntimeError("OpenCV requested but cv2 is not installed")
        else:
            return "opencv", _component_areas_opencv
    if name in ("auto", "scipy"):
        try:
            from scipy import ndimage  # noqa: F401
        except ImportError:
            if name == "scipy":
                raise RuntimeError("SciPy requested but scipy.ndimage is not installed")
        else:
            return "scipy.ndimage", _component_areas_scipy
    return "rle-union-find", _component_areas_rle


def inclusive_area(box: tuple[int, int, int, int]) -> int:
    return (box[2] - box[0] + 1) * (box[3] - box[1] + 1)


def mask_bbox(mask: np.ndarray) -> tuple[int, int, int, int] | None:
    occupied_rows = np.flatnonzero(mask.any(axis=1))
    occupied_columns = np.flatnonzero(mask.any(axis=0))
    if occupied_rows.size == 0 or occupied_columns.size == 0:
        return None
    return (
        int(occupied_columns[0]),
        int(occupied_rows[0]),
        int(occupied_columns[-1]),
        int(occupied_rows[-1]),
    )


def inclusive_iou(
    left: tuple[int, int, int, int] | None, right: tuple[int, int, int, int]
) -> float:
    if left is None:
        return 0.0
    ix1, iy1 = max(left[0], right[0]), max(left[1], right[1])
    ix2, iy2 = min(left[2], right[2]), min(left[3], right[3])
    intersection = max(0, ix2 - ix1 + 1) * max(0, iy2 - iy1 + 1)
    union = inclusive_area(left) + inclusive_area(right) - intersection
    return float(intersection / union) if union else 0.0


def near(left: Any, right: float, *, absolute: float = 1e-6, relative: float = 1e-5) -> bool:
    parsed = finite_float(left)
    return parsed is not None and math.isclose(parsed, right, abs_tol=absolute, rel_tol=relative)


def relative_or_absolute(path: Path, root: Path) -> str:
    try:
        return str(path.resolve().relative_to(root.resolve()))
    except ValueError:
        return str(path.resolve())


def thresholds_dict(args: argparse.Namespace) -> dict[str, Any]:
    return {
        "min_mask_area_ratio": args.min_mask_area_ratio,
        "max_mask_area_ratio": args.max_mask_area_ratio,
        "min_primary_component_fraction": args.min_primary_component_fraction,
        "max_meaningful_components": args.max_meaningful_components,
        "max_raw_components": args.max_raw_components,
        "component_min_pixels": args.component_min_pixels,
        "component_min_fraction": args.component_min_fraction,
        "max_bbox_leak_ratio": args.max_bbox_leak_ratio,
        "min_prompt_box_fill_ratio": args.min_prompt_box_fill_ratio,
        "min_mask_bbox_prompt_iou": args.min_mask_bbox_prompt_iou,
        "min_sam_score": args.min_sam_score,
    }


def expected_variants(
    manifest: dict[str, Any],
    selected_cases: set[str],
    selected_pairs: set[str],
    recorder: StructuralRecorder,
) -> dict[tuple[str, str], tuple[dict[str, Any], dict[str, Any]]]:
    cases = manifest.get("cases")
    if not isinstance(cases, list):
        recorder.add("manifest.cases", "manifest.cases", "Expected a list")
        return {}
    result: dict[tuple[str, str], tuple[dict[str, Any], dict[str, Any]]] = {}
    for case_index, case in enumerate(cases):
        location = f"manifest.cases[{case_index}]"
        if not isinstance(case, dict):
            recorder.add("manifest.case", location, "Expected an object")
            continue
        case_id = case.get("case_id")
        if not nonempty_string(case_id):
            recorder.add("manifest.case_id", f"{location}.case_id", "Expected a non-empty string")
            continue
        case_id = str(case_id)
        if selected_cases and case_id not in selected_cases:
            continue
        variants = case.get("variants")
        if not isinstance(variants, list):
            recorder.add("manifest.variants", f"{location}.variants", "Expected a list")
            continue
        for variant_index, variant in enumerate(variants):
            variant_location = f"{location}.variants[{variant_index}]"
            if not isinstance(variant, dict):
                recorder.add("manifest.variant", variant_location, "Expected an object")
                continue
            pair = variant.get("pair")
            if not nonempty_string(pair):
                recorder.add("manifest.pair", f"{variant_location}.pair", "Expected a non-empty string")
                continue
            pair = str(pair)
            if selected_pairs and pair not in selected_pairs:
                continue
            key = (case_id, pair)
            if key in result:
                recorder.add("manifest.duplicate_key", variant_location, f"Duplicate case/pair: {case_id}/{pair}")
                continue
            result[key] = (case, variant)
    if selected_cases:
        absent = sorted(selected_cases - {key[0] for key in result})
        for case_id in absent:
            recorder.add("filter.case_not_found", "--case-id", f"No selected variant found for {case_id}")
    return result


def audit_index(
    rows: list[dict[str, Any]], recorder: StructuralRecorder
) -> dict[tuple[str, str], dict[str, Any]]:
    result: dict[tuple[str, str], dict[str, Any]] = {}
    for index, row in enumerate(rows):
        location = f"sam2_masks[{index}]"
        case_id, pair = row.get("case_id"), row.get("pair")
        if not nonempty_string(case_id) or not nonempty_string(pair):
            recorder.add("audit.key", location, "case_id and pair must be non-empty strings")
            continue
        key = str(case_id), str(pair)
        if key in result:
            recorder.add("audit.duplicate_key", location, f"Duplicate case/pair: {key[0]}/{key[1]}")
            continue
        result[key] = row
    return result


def inspect_one(
    *,
    key: tuple[str, str],
    case: dict[str, Any],
    variant: dict[str, Any],
    audit: dict[str, Any],
    dataset_root: Path,
    source_dimensions_cache: dict[str, tuple[int, int]],
    component_backend: str,
    component_counter: Callable[[np.ndarray], list[int]],
    args: argparse.Namespace,
    recorder: StructuralRecorder,
) -> dict[str, Any] | None:
    case_id, pair = key
    location = f"{case_id}/{pair}"
    image_rel = case.get("image")
    image_path = safe_relative_path(dataset_root, image_rel, recorder, f"{location}.image")
    if image_path is None:
        return None
    if audit.get("image") != image_rel:
        recorder.add(
            "audit.image_mismatch",
            f"{location}.image",
            f"Manifest has {image_rel!r}; audit has {audit.get('image')!r}",
        )
    if not image_path.is_file():
        recorder.add("source.missing", f"{location}.image", f"Missing source image: {image_path}")
        return None
    try:
        if str(image_path) not in source_dimensions_cache:
            with Image.open(image_path) as raw_source:
                source_dimensions_cache[str(image_path)] = ImageOps.exif_transpose(raw_source).size
        width, height = source_dimensions_cache[str(image_path)]
    except (OSError, ValueError) as exc:
        recorder.add("source.invalid", f"{location}.image", str(exc))
        return None

    mask_path = safe_relative_path(dataset_root, audit.get("mask"), recorder, f"{location}.mask")
    if mask_path is None:
        return None
    if not mask_path.is_file():
        recorder.add("mask.missing", f"{location}.mask", f"Missing mask: {mask_path}")
        return None
    try:
        with Image.open(mask_path) as raw_mask:
            raw_mask.load()
            original_mode = raw_mask.mode
            mask_array = np.asarray(raw_mask.convert("L"))
    except (OSError, ValueError) as exc:
        recorder.add("mask.invalid", f"{location}.mask", str(exc))
        return None
    if mask_array.shape != (height, width):
        recorder.add(
            "mask.dimension_mismatch",
            f"{location}.mask",
            f"Source is {width}x{height}; mask is {mask_array.shape[1]}x{mask_array.shape[0]}",
        )
        return None
    histogram = np.bincount(mask_array.reshape(-1), minlength=256)
    unique_values = np.flatnonzero(histogram)
    if unique_values.size > 2:
        recorder.add(
            "mask.not_binary",
            f"{location}.mask",
            f"Expected at most two grayscale values, found {unique_values.size}",
        )
    mask = mask_array > 0

    if audit.get("image_dimensions") != [width, height]:
        recorder.add(
            "audit.dimension_mismatch",
            f"{location}.image_dimensions",
            f"Expected {[width, height]}, got {audit.get('image_dimensions')!r}",
        )

    manifest_prompt = variant.get("sam2_prompt")
    if not isinstance(manifest_prompt, dict):
        recorder.add("manifest.sam2_prompt", f"{location}.sam2_prompt", "Expected an object")
        return None
    manifest_norm_box = normalized_box(manifest_prompt.get("bbox_xyxy_norm"))
    if manifest_norm_box is None:
        recorder.add("manifest.bbox", f"{location}.sam2_prompt.bbox_xyxy_norm", "Invalid normalized box")
        return None
    expected_box = normalized_box_to_pixels(manifest_norm_box, width, height)

    audit_prompt = audit.get("sam2_prompt")
    if not isinstance(audit_prompt, dict):
        recorder.add("audit.sam2_prompt", f"{location}.sam2_prompt", "Expected an object")
        audit_prompt = {}
    box = pixel_box(audit_prompt.get("bbox_xyxy_px"), width, height)
    if box is None:
        recorder.add("audit.bbox", f"{location}.sam2_prompt.bbox_xyxy_px", "Invalid or missing pixel box")
        box = expected_box
    elif box != expected_box:
        recorder.add(
            "audit.bbox_mismatch",
            f"{location}.sam2_prompt.bbox_xyxy_px",
            f"Expected {list(expected_box)}, got {list(box)}",
        )
    audit_norm_box = normalized_box(audit_prompt.get("bbox_xyxy_norm"))
    if audit_norm_box is None or not np.allclose(
        audit_norm_box, manifest_norm_box, rtol=0.0, atol=1e-9
    ):
        recorder.add(
            "audit.normalized_bbox_mismatch",
            f"{location}.sam2_prompt.bbox_xyxy_norm",
            f"Expected {list(manifest_norm_box)}, got {audit_prompt.get('bbox_xyxy_norm')!r}",
        )

    point_report: dict[str, Any] = {}
    for kind, should_hit in (("positive", True), ("negative", False)):
        norm_key = f"{kind}_points_norm"
        px_key = f"{kind}_points_px"
        stored_hit_key = f"{kind}_point_hits"
        manifest_px = normalized_points_to_pixels(manifest_prompt.get(norm_key, []), width, height)
        if manifest_px is None:
            recorder.add("manifest.points", f"{location}.sam2_prompt.{norm_key}", "Invalid normalized point list")
            manifest_px = []
        audit_px = valid_pixel_points(audit_prompt.get(px_key, []), width, height)
        if audit_px is None:
            recorder.add("audit.points", f"{location}.sam2_prompt.{px_key}", "Invalid pixel point list")
            audit_px = manifest_px
        elif audit_px != manifest_px:
            recorder.add(
                "audit.points_mismatch",
                f"{location}.sam2_prompt.{px_key}",
                f"Expected {manifest_px}, got {audit_px}",
            )
        audit_norm_points = audit_prompt.get(norm_key)
        manifest_norm_points = manifest_prompt.get(norm_key, [])
        if audit_norm_points != manifest_norm_points:
            recorder.add(
                "audit.normalized_points_mismatch",
                f"{location}.sam2_prompt.{norm_key}",
                (
                    f"Expected {manifest_norm_points!r}, "
                    f"got {audit_norm_points!r}"
                ),
            )
        hits = [bool(mask[y, x]) for x, y in audit_px]
        stored_hits = audit.get(stored_hit_key)
        if not isinstance(stored_hits, list) or any(not isinstance(item, bool) for item in stored_hits):
            recorder.add(
                "audit.point_hits", f"{location}.{stored_hit_key}", "Expected a list of booleans"
            )
            stored_hits = []
        elif stored_hits != hits:
            recorder.add(
                "audit.point_hits_mismatch",
                f"{location}.{stored_hit_key}",
                f"Stored {stored_hits}; recomputed {hits}",
            )
        point_report[kind] = {
            "points_px": audit_px,
            "audit_hits": stored_hits,
            "recomputed_hits": hits,
            "all_expected": all(hit == should_hit for hit in hits),
        }

    mask_pixels = int(mask.sum())
    image_pixels = width * height
    area_ratio = float(mask_pixels / image_pixels)
    if audit.get("mask_area_pixels") != mask_pixels:
        recorder.add(
            "audit.mask_area_mismatch",
            f"{location}.mask_area_pixels",
            f"Expected {mask_pixels}, got {audit.get('mask_area_pixels')!r}",
        )
    if not near(audit.get("mask_area_ratio"), area_ratio):
        recorder.add(
            "audit.mask_ratio_mismatch",
            f"{location}.mask_area_ratio",
            f"Expected {area_ratio:.12g}, got {audit.get('mask_area_ratio')!r}",
        )

    areas = component_counter(mask)
    primary_fraction = float(areas[0] / mask_pixels) if areas and mask_pixels else 0.0
    meaningful_minimum = max(
        args.component_min_pixels, math.ceil(mask_pixels * args.component_min_fraction)
    )
    meaningful_areas = [area for area in areas if area >= meaningful_minimum]

    x1, y1, x2, y2 = box
    inside_pixels = int(mask[y1 : y2 + 1, x1 : x2 + 1].sum())
    outside_pixels = mask_pixels - inside_pixels
    fraction_inside = float(inside_pixels / mask_pixels) if mask_pixels else 0.0
    leak_ratio = float(outside_pixels / mask_pixels) if mask_pixels else 0.0
    prompt_box_area = inclusive_area(box)
    prompt_box_fill = float(inside_pixels / prompt_box_area)
    actual_mask_bbox = mask_bbox(mask)
    bbox_iou = inclusive_iou(actual_mask_bbox, box)
    if not near(audit.get("mask_fraction_inside_prompt_box"), fraction_inside):
        recorder.add(
            "audit.containment_mismatch",
            f"{location}.mask_fraction_inside_prompt_box",
            f"Expected {fraction_inside:.12g}, got {audit.get('mask_fraction_inside_prompt_box')!r}",
        )
    cached_bbox = audit.get("mask_bbox_xyxy_px")
    expected_cached_bbox = list(actual_mask_bbox) if actual_mask_bbox is not None else None
    if cached_bbox != expected_cached_bbox:
        recorder.add(
            "audit.mask_bbox_mismatch",
            f"{location}.mask_bbox_xyxy_px",
            f"Expected {expected_cached_bbox}, got {cached_bbox!r}",
        )

    chosen_score = finite_float(audit.get("chosen_score"))
    if chosen_score is None:
        recorder.add("audit.chosen_score", f"{location}.chosen_score", "Expected a finite number")

    flags: list[str] = []
    if mask_pixels == 0:
        flags.append("empty_mask")
    if area_ratio < args.min_mask_area_ratio:
        flags.append("mask_area_too_small")
    if area_ratio > args.max_mask_area_ratio:
        flags.append("mask_area_too_large")
    if areas and primary_fraction < args.min_primary_component_fraction:
        flags.append("fragmented_primary_component")
    if len(meaningful_areas) > args.max_meaningful_components:
        flags.append("too_many_meaningful_components")
    if len(areas) > args.max_raw_components:
        flags.append("too_many_raw_components")
    if leak_ratio > args.max_bbox_leak_ratio:
        flags.append("prompt_box_leak")
    if prompt_box_fill < args.min_prompt_box_fill_ratio:
        flags.append("prompt_box_fill_too_low")
    if bbox_iou < args.min_mask_bbox_prompt_iou:
        flags.append("mask_bbox_prompt_iou_too_low")
    if point_report["positive"]["recomputed_hits"] and not point_report["positive"]["all_expected"]:
        flags.append("positive_point_miss")
    if point_report["negative"]["recomputed_hits"] and not point_report["negative"]["all_expected"]:
        flags.append("negative_point_hit")
    if chosen_score is not None and chosen_score < args.min_sam_score:
        flags.append("low_sam_score")
    touches_border = bool(
        mask[0, :].any() or mask[-1, :].any() or mask[:, 0].any() or mask[:, -1].any()
    )
    if touches_border:
        flags.append("mask_touches_image_border")

    return {
        "case_id": case_id,
        "pair": pair,
        "target_expression": variant.get("target_expression"),
        "image": str(image_rel),
        "mask": str(audit.get("mask")),
        "image_dimensions": [width, height],
        "mask_original_mode": original_mode,
        "mask_unique_values": [int(value) for value in unique_values.tolist()],
        "mask_area_pixels": mask_pixels,
        "mask_area_ratio": area_ratio,
        "connected_components": {
            "backend": component_backend,
            "raw_count": len(areas),
            "meaningful_count": len(meaningful_areas),
            "meaningful_minimum_pixels": meaningful_minimum,
            "primary_component_pixels": areas[0] if areas else 0,
            "primary_component_fraction": primary_fraction,
            "largest_component_areas": areas[:10],
        },
        "prompt_box": {
            "bbox_xyxy_px": list(box),
            "area_pixels": prompt_box_area,
            "mask_pixels_inside": inside_pixels,
            "mask_pixels_outside": outside_pixels,
            "mask_fraction_inside": fraction_inside,
            "leak_ratio": leak_ratio,
            "fill_ratio": prompt_box_fill,
            "mask_bbox_xyxy_px": list(actual_mask_bbox) if actual_mask_bbox is not None else None,
            "mask_bbox_prompt_iou": bbox_iou,
        },
        "prompt_points": point_report,
        "chosen_sam_score": chosen_score,
        "touches_image_border": touches_border,
        "visual_review_flags": flags,
        "visual_review_required": bool(flags),
    }


def markdown_escape(value: Any) -> str:
    return str(value).replace("|", "\\|").replace("\n", " ")


def percent(value: float) -> str:
    return f"{100.0 * value:.2f}%"


def make_markdown(report: dict[str, Any]) -> str:
    summary = report["summary"]
    lines = [
        "# SAM2 mask quality audit",
        "",
        f"Generated: `{report['created_utc']}`",
        "",
        (
            f"Audited **{summary['masks_audited']}** masks across **{summary['cases_audited']}** "
            f"cases; **{summary['masks_flagged_for_visual_review']}** masks have heuristic flags "
            f"and **{summary['structural_error_count']}** structural errors were found."
        ),
        "",
        "Heuristic flags are review cues, not automatic mask failures. Structural errors alone control the command exit code.",
        "",
        "## Thresholds",
        "",
        "```json",
        json.dumps(report["thresholds"], indent=2, sort_keys=True),
        "```",
        "",
    ]
    errors = report["structural_errors"]
    if errors:
        lines.extend(["## Structural errors", ""])
        for issue in errors:
            lines.append(
                f"- `{markdown_escape(issue['code'])}` at `{markdown_escape(issue['location'])}`: "
                f"{markdown_escape(issue['message'])}"
            )
        lines.append("")
    flag_counts = summary["visual_flag_counts"]
    lines.extend(["## Visual flag counts", ""])
    if flag_counts:
        for code, count in flag_counts.items():
            lines.append(f"- `{markdown_escape(code)}`: {count}")
    else:
        lines.append("- None")
    lines.extend(
        [
            "",
            "## Per-mask metrics",
            "",
            "| Status | Case / pair | Area | Components meaningful/raw | Primary | Inside box | Leak | Box fill | BBox IoU | Points +/− | SAM score | Flags |",
            "|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---|",
        ]
    )
    for item in report["masks"]:
        components = item["connected_components"]
        prompt_box = item["prompt_box"]
        points = item["prompt_points"]
        positive_hits = points["positive"]["recomputed_hits"]
        negative_hits = points["negative"]["recomputed_hits"]
        positive_summary = f"{sum(positive_hits)}/{len(positive_hits)}" if positive_hits else "—"
        negative_misses = sum(not hit for hit in negative_hits)
        negative_summary = f"{negative_misses}/{len(negative_hits)}" if negative_hits else "—"
        score = item["chosen_sam_score"]
        lines.append(
            "| {status} | `{key}` | {area} | {meaningful}/{raw} | {primary} | {inside} | {leak} | {fill} | {iou} | {positive} / {negative} | {score} | {flags} |".format(
                status="REVIEW" if item["visual_review_required"] else "OK",
                key=markdown_escape(f"{item['case_id']}/{item['pair']}"),
                area=percent(item["mask_area_ratio"]),
                meaningful=components["meaningful_count"],
                raw=components["raw_count"],
                primary=percent(components["primary_component_fraction"]),
                inside=percent(prompt_box["mask_fraction_inside"]),
                leak=percent(prompt_box["leak_ratio"]),
                fill=percent(prompt_box["fill_ratio"]),
                iou=percent(prompt_box["mask_bbox_prompt_iou"]),
                positive=positive_summary,
                negative=negative_summary,
                score=f"{score:.3f}" if score is not None else "—",
                flags=", ".join(
                    f"`{markdown_escape(flag)}`" for flag in item["visual_review_flags"]
                ) or "—",
            )
        )
    lines.extend(
        [
            "",
            "Point columns show positive points landing inside the mask and negative points landing outside it, respectively.",
            "",
        ]
    )
    return "\n".join(lines)


def run(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
    validate_thresholds(args)
    dataset_root = args.dataset_root.resolve()
    manifest_path = (args.manifest or dataset_root / "metadata/manifest.json").resolve()
    audit_path = (args.sam2_audit or dataset_root / "metadata/sam2_masks.jsonl").resolve()
    output_json = (args.output_json or dataset_root / "metadata/sam2_quality_audit.json").resolve()
    output_markdown = (
        args.output_markdown or dataset_root / "metadata/sam2_quality_audit.md"
    ).resolve()
    if not manifest_path.is_file():
        raise FileNotFoundError(f"Manifest not found: {manifest_path}")
    if not audit_path.is_file():
        raise FileNotFoundError(f"SAM2 audit not found: {audit_path}")

    recorder = StructuralRecorder()
    manifest = read_json_object(manifest_path)
    expected = expected_variants(manifest, set(args.case_id), set(args.pair), recorder)
    audit_rows = read_jsonl(audit_path, recorder)
    if not expected:
        recorder.add(
            "manifest.no_selected_variants",
            "manifest.cases",
            "No manifest variants matched the requested filters",
        )
    audits = audit_index(audit_rows, recorder)
    filtered = bool(args.case_id or args.pair)
    if not filtered:
        for key in sorted(set(audits) - set(expected)):
            recorder.add(
                "audit.unexpected_row",
                f"{key[0]}/{key[1]}",
                "Audit row has no matching manifest variant",
            )

    component_backend, component_counter = choose_component_counter(args.component_backend)
    source_dimensions_cache: dict[str, tuple[int, int]] = {}
    mask_reports: list[dict[str, Any]] = []
    for key in sorted(expected):
        if key not in audits:
            recorder.add(
                "audit.missing_row",
                f"{key[0]}/{key[1]}",
                "Manifest variant has no SAM2 audit row",
            )
            continue
        case, variant = expected[key]
        result = inspect_one(
            key=key,
            case=case,
            variant=variant,
            audit=audits[key],
            dataset_root=dataset_root,
            source_dimensions_cache=source_dimensions_cache,
            component_backend=component_backend,
            component_counter=component_counter,
            args=args,
            recorder=recorder,
        )
        if result is not None:
            mask_reports.append(result)

    flag_counts: Counter[str] = Counter(
        flag for item in mask_reports for flag in item["visual_review_flags"]
    )
    report = {
        "schema_version": "1.0",
        "created_utc": datetime.now(timezone.utc).isoformat(),
        "privacy": "evaluator-private",
        "dataset_root": str(dataset_root),
        "inputs": {
            "manifest": relative_or_absolute(manifest_path, dataset_root),
            "sam2_audit": relative_or_absolute(audit_path, dataset_root),
        },
        "component_backend": component_backend,
        "thresholds": thresholds_dict(args),
        "summary": {
            "expected_masks": len(expected),
            "masks_audited": len(mask_reports),
            "cases_audited": len({item["case_id"] for item in mask_reports}),
            "masks_flagged_for_visual_review": sum(
                bool(item["visual_review_flags"]) for item in mask_reports
            ),
            "visual_flag_counts": dict(sorted(flag_counts.items())),
            "structural_error_count": len(recorder.errors),
        },
        "structural_errors": [asdict(issue) for issue in recorder.errors],
        "masks": mask_reports,
        "interpretation": (
            "Heuristic flags require human inspection and are not automatic failures. "
            "Only structural_errors affect the process exit code."
        ),
    }
    output_json.parent.mkdir(parents=True, exist_ok=True)
    output_markdown.parent.mkdir(parents=True, exist_ok=True)
    output_json.write_text(
        json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    output_markdown.write_text(make_markdown(report), encoding="utf-8")
    print(
        json.dumps(
            {
                "json": str(output_json),
                "markdown": str(output_markdown),
                **report["summary"],
                "exit_code": 2 if recorder.errors else 0,
            },
            ensure_ascii=False,
            indent=2,
        )
    )
    return report, 2 if recorder.errors else 0


def main() -> None:
    try:
        _report, exit_code = run(parse_args())
    except (OSError, UnicodeError, ValueError, RuntimeError, json.JSONDecodeError) as exc:
        print(f"STRUCTURAL ERROR: {exc}", file=sys.stderr)
        raise SystemExit(2) from exc
    raise SystemExit(exit_code)


if __name__ == "__main__":
    main()