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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
#!/usr/bin/env python3
"""Causally scoped v5.2-rc3 evaluator (offline acceptance candidate).

RC3 deliberately exposes two different verifier scopes:

``components`` / ``verified_reward_full_gt``
    Offline, executed-DXF versus full-GT verification.  Full-GT physical
    geometry is retained here because an RLVR verifier is allowed to access
    the reference answer.

``online_reward_prompt_masked``
    The FMFS-masked view of physical/annotation supervision.  Prompt physical
    features are scored only when the sidecar supplies a certified mapping to
    actual geometry.  Missing or ambiguous mappings are ineligible; there is
    no fallback to predicted DIMENSION text or to the full-GT physical score.

One positive uniform sheet scale remains an explicit legal invariance.  The
metric verifies geometry and physical proportions after fitting that scale;
it does not require a particular DXF plotting scale.

This module is add-only and is not connected to GRPO.  It uses the RC3 matcher
so every predicted cluster, including clusters outside the bounded role
assignment search, contributes to extra-geometry precision.
"""

from __future__ import annotations

import copy
import math
from itertools import combinations
from pathlib import Path
from typing import Any, Mapping, Sequence

import numpy as np
from scipy.optimize import linear_sum_assignment

try:
    from . import eval_geometric052 as BASE
    from . import eval_geometric052_rc2 as RC2
    from . import view_entity_matching_v52_rc3 as MATCH
except ImportError:  # direct evaluator import
    import eval_geometric052 as BASE
    import eval_geometric052_rc2 as RC2
    import view_entity_matching_v52_rc3 as MATCH


METRIC_VERSION = "v5.2-rc3"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc3"
ENGINEERING_THRESHOLDS = dict(BASE.ENGINEERING_THRESHOLDS)

PHYSICAL_SUPPORTED_SEMANTICS = BASE.PHYSICAL_SUPPORTED_SEMANTICS | {
    "bounding_box_width",
    "bounding_box_height",
    "cut_profile_diameter",
}

MAX_DIMENSION_BINDING_FRACTION = 0.08
MAX_DIMENSION_VALUE_LOG_ERROR = math.log(1.5)
MAX_GEOMETRY_BINDING_REL_ERROR = 0.03
SEVERE_ANNOTATION_SPAM_MULTIPLIER = 3
SEVERE_ANNOTATION_SPAM_ALLOWANCE = 6


def _consume_appended_omitted_marker(context: dict[str, Any]) -> dict[str, Any]:
    """Make clear that RC3 appended, and therefore did not omit, the clusters."""

    alignment = context.get("alignment")
    if not isinstance(alignment, dict):
        return context
    original = list(alignment.get("omitted_original_indices", []))
    alignment["role_assignment_omitted_original_indices"] = original
    alignment["omitted_original_indices"] = []
    alignment["omitted_clusters_are_appended_as_extras"] = True
    return context


def _layout_component(
    context: Mapping[str, Any], rows: Mapping[str, Any]
) -> dict[str, Any]:
    """Measure layout with radius/arc-parameter-invariant view anchors."""

    roles = [role for role, row in rows.items() if row["present"]]
    if len(roles) < 2:
        return BASE._component(
            None, False, "fewer_than_two_semantic_roles", matched_roles=roles
        )
    alignment = context["alignment"]
    scale = float(alignment.get("global_scale", 1.0))
    role_to_pred = alignment["role_to_pred"]
    pred_views = context["pred_views"]
    gt_by_role = context["gt_by_role"]
    sheet_diagonal = max(float(alignment.get("sheet_diagonal", 1.0)), 1.0)
    errors: list[float] = []
    pair_rows: list[dict[str, Any]] = []
    for first, second in combinations(roles, 2):
        pred_first = pred_views[role_to_pred[first]].get("layout_anchor")
        pred_second = pred_views[role_to_pred[second]].get("layout_anchor")
        gt_first = gt_by_role[first].get("layout_anchor")
        gt_second = gt_by_role[second].get("layout_anchor")
        if any(value is None for value in (pred_first, pred_second, gt_first, gt_second)):
            return BASE._component(
                None,
                False,
                "layout_anchor_unavailable",
                matched_roles=roles,
                anchor_definition=MATCH.LAYOUT_ANCHOR_DEFINITION,
            )
        pred_vector = scale * (
            np.asarray(pred_second, dtype=float) - np.asarray(pred_first, dtype=float)
        )
        gt_vector = np.asarray(gt_second, dtype=float) - np.asarray(gt_first, dtype=float)
        error = float(np.linalg.norm(pred_vector - gt_vector) / sheet_diagonal)
        errors.append(error)
        pair_rows.append(
            {"roles": [first, second], "vector_error_fraction": BASE._round(error)}
        )
    mean_error = float(np.mean(errors))
    score = math.exp(-mean_error / 0.10)
    return BASE._component(
        score,
        True,
        "ok" if mean_error <= 0.02 else "relative_view_layout_mismatch",
        matched_roles=roles,
        mean_pair_vector_error_fraction=BASE._round(mean_error),
        pairs=pair_rows,
        anchor_definition=MATCH.LAYOUT_ANCHOR_DEFINITION,
        uniform_sheet_scale_invariant=True,
    )


def _scope_contract(
    sidecar: Mapping[str, Any] | None, scope: str
) -> tuple[dict[str, Any], dict[str, Any]]:
    contract = BASE.EV51._scope_contracts(sidecar)
    selected = contract.get(scope, {})
    return contract, selected if isinstance(selected, Mapping) else {}


def _dimension_targets(
    context: Mapping[str, Any],
    sidecar: Mapping[str, Any] | None,
    contract: Mapping[str, Any],
) -> list[dict[str, Any]]:
    gt_dims = list((context.get("raw_gt") or {}).get("dims", []))
    targets: list[dict[str, Any]] = []
    for spec_index, raw_spec in enumerate(contract.get("specs", [])):
        spec = dict(raw_spec)
        try:
            gt_index = int(spec["gt_dimension_index"])
        except (KeyError, TypeError, ValueError):
            continue
        if not 0 <= gt_index < len(gt_dims):
            continue
        targets.append(
            {
                "spec_index": spec_index,
                "spec": spec,
                "gt_index": gt_index,
                "dimension": gt_dims[gt_index],
                "role": BASE._dimension_role(sidecar, gt_index),
            }
        )
    return targets


def _dimension_pair_detail(
    context: Mapping[str, Any],
    pred_dim: Mapping[str, Any],
    target: Mapping[str, Any],
) -> dict[str, Any]:
    role = target.get("role")
    transform = MATCH.role_local_transform(context, str(role)) if role else None
    if transform is None:
        scale = float(context["alignment"].get("global_scale", 1.0))
        translation = np.asarray(
            context["alignment"].get("translation", (0.0, 0.0)), dtype=float
        )
    else:
        scale, translation = transform
    sheet_diagonal = max(float(context["alignment"].get("sheet_diagonal", 1.0)), 1.0)
    pred_binding = np.asarray(pred_dim.get("binding_point", (0.0, 0.0)), dtype=float)
    gt_binding = np.asarray(
        target["dimension"].get("binding_point", (0.0, 0.0)), dtype=float
    )
    distance = float(
        np.linalg.norm(pred_binding * scale + translation - gt_binding) / sheet_diagonal
    )
    pred_family = BASE._semantic_family(pred_dim.get("family"))
    target_family = BASE._semantic_family(target["spec"].get("family"))
    target_value = abs(float(target["spec"]["value"]))
    predicted_value, value_source = BASE._dimension_display_value(
        pred_dim,
        target_value=target_value,
        target_dimension=target["dimension"],
        global_scale=float(scale),
    )
    if predicted_value is None or target_value <= 1e-12:
        value_log_error = math.inf
        value_relative_error = None
    else:
        value_log_error = abs(
            math.log(max(float(predicted_value), 1e-12) / target_value)
        )
        value_relative_error = abs(float(predicted_value) / target_value - 1.0)
    family_ok = pred_family == target_family
    accepted = bool(
        family_ok
        and distance <= MAX_DIMENSION_BINDING_FRACTION
        and value_log_error <= MAX_DIMENSION_VALUE_LOG_ERROR
    )
    cost = (
        distance
        + (2.0 if not family_ok else 0.0)
        + 0.20 * min(value_log_error, 2.0)
    )
    return {
        "cost": cost,
        "accepted": accepted,
        "binding_distance_fraction": distance,
        "predicted_family": pred_family,
        "target_family": target_family,
        "family_ok": family_ok,
        "target_value": target_value,
        "predicted_value": predicted_value,
        "value_source": value_source,
        "value_log_error": value_log_error,
        "value_relative_error": value_relative_error,
        "scale": float(scale),
        "role": role,
    }


def _annotation_component(
    context: Mapping[str, Any],
    sidecar: Mapping[str, Any] | None,
    *,
    scope: str,
) -> dict[str, Any]:
    """Score masked target quality plus precision against the total GT inventory."""

    contract, selected_contract = _scope_contract(sidecar, scope)
    mask = selected_contract.get("annotation_mask", [])
    if not selected_contract.get("annotation_eligible"):
        return BASE._component(
            None,
            False,
            f"{scope}_annotation_mask_ineligible",
            scope=scope,
            contract_errors=contract.get("errors", []),
            reason_codes=selected_contract.get("reason_codes", []),
        )
    targets = _dimension_targets(context, sidecar, contract)
    selected_spec_indices = {
        index for index, selected in enumerate(mask) if selected
    }
    selected_targets = [
        target for target in targets if target["spec_index"] in selected_spec_indices
    ]
    if not selected_targets:
        return BASE._component(
            None, False, "no_valid_masked_target_dimensions", scope=scope
        )

    pred_dims = list((context.get("raw_pred") or {}).get("dims", []))
    details: dict[tuple[int, int], dict[str, Any]] = {}
    pairs_by_target: dict[int, int] = {}
    if pred_dims and targets:
        costs = np.zeros((len(pred_dims), len(targets)), dtype=float)
        for pred_index, pred_dim in enumerate(pred_dims):
            for target_index, target in enumerate(targets):
                detail = _dimension_pair_detail(context, pred_dim, target)
                details[(pred_index, target_index)] = detail
                costs[pred_index, target_index] = float(detail["cost"])
        pred_rows, target_columns = linear_sum_assignment(costs)
        for pred_index, target_index in zip(pred_rows, target_columns):
            detail = details[(int(pred_index), int(target_index))]
            if detail["accepted"]:
                pairs_by_target[int(target_index)] = int(pred_index)

    target_position = {target["spec_index"]: index for index, target in enumerate(targets)}
    item_rows: list[dict[str, Any]] = []
    item_scores: list[float] = []
    presence_values: list[float] = []
    type_values: list[float] = []
    value_values: list[float] = []
    binding_values: list[float] = []
    for target in selected_targets:
        position = target_position[target["spec_index"]]
        pred_index = pairs_by_target.get(position)
        spec = target["spec"]
        if pred_index is None:
            item_scores.append(0.0)
            presence_values.append(0.0)
            type_values.append(0.0)
            value_values.append(0.0)
            binding_values.append(0.0)
            item_rows.append(
                {
                    "id": spec["id"],
                    "gt_dimension_index": target["gt_index"],
                    "pred_dimension_index": None,
                    "role": target.get("role"),
                    "presence": 0.0,
                    "type": 0.0,
                    "display_value": 0.0,
                    "binding": 0.0,
                    "score": 0.0,
                    "reason": "missing_or_semantically_incompatible_dimension",
                }
            )
            continue
        detail = details[(pred_index, position)]
        value_quality = math.exp(-float(detail["value_log_error"]) / 0.10)
        binding_quality = math.exp(
            -float(detail["binding_distance_fraction"]) / 0.03
        )
        item_score = 0.35 + 0.20 + 0.30 * value_quality + 0.15 * binding_quality
        item_scores.append(item_score)
        presence_values.append(1.0)
        type_values.append(1.0)
        value_values.append(value_quality)
        binding_values.append(binding_quality)
        item_rows.append(
            {
                "id": spec["id"],
                "gt_dimension_index": target["gt_index"],
                "pred_dimension_index": pred_index,
                "role": target.get("role"),
                "presence": 1.0,
                "type": 1.0,
                "display_value": BASE._round(value_quality),
                "binding": BASE._round(binding_quality),
                "target_display_value": BASE._round(detail["target_value"]),
                "predicted_display_value": BASE._round(detail["predicted_value"]),
                "display_value_source": detail["value_source"],
                "display_value_relative_error": BASE._round(
                    detail["value_relative_error"]
                ),
                "binding_distance_fraction": BASE._round(
                    detail["binding_distance_fraction"]
                ),
                "score": BASE._round(item_score),
                "reason": "ok" if item_score >= 0.90 else "annotation_field_mismatch",
            }
        )

    target_macro = float(np.mean(item_scores))
    target_worst = min(item_scores)
    target_quality = 0.50 * target_macro + 0.50 * target_worst
    matched_predicted = set(pairs_by_target.values())
    pred_meta = context.get("pred_meta", {})
    gt_meta = context.get("gt_meta", {})
    pred_text = int(pred_meta.get("dimension_like_text", 0) or 0)
    gt_text = int(gt_meta.get("dimension_like_text", 0) or 0)
    predicted_inventory = len(pred_dims) + pred_text
    matched_inventory = len(matched_predicted) + min(pred_text, gt_text)
    predicted_precision = (
        matched_inventory / predicted_inventory if predicted_inventory else 0.0
    )
    score = BASE._harmonic(target_quality, predicted_precision)
    return BASE._component(
        score,
        True,
        "ok" if score >= ENGINEERING_THRESHOLDS["annotation"] else "annotation_recall_precision_or_field_mismatch",
        scope=scope,
        n_selected_target=len(selected_targets),
        n_total_gt_dimension_targets=len(targets),
        n_predicted_native=len(pred_dims),
        n_predicted_dimension_like_text=pred_text,
        n_matched_predicted_native=len(matched_predicted),
        n_unmatched_predicted_native=len(pred_dims) - len(matched_predicted),
        predicted_precision=BASE._round(predicted_precision),
        presence_recall=BASE._round(float(np.mean(presence_values))),
        type_macro=BASE._round(float(np.mean(type_values))),
        display_value_macro=BASE._round(float(np.mean(value_values))),
        binding_macro=BASE._round(float(np.mean(binding_values))),
        target_quality=BASE._round(target_quality),
        item_macro=BASE._round(target_macro),
        item_worst=BASE._round(target_worst),
        items=item_rows,
        matching_policy="one_to_one_all_gt_inventory_family_binding_value_gated",
        unselected_gt_dimensions_are_precision_neutral=True,
        reads_actual_geometry=False,
    )


def _sidecar_dimension_item(
    sidecar: Mapping[str, Any] | None, gt_index: int
) -> Mapping[str, Any] | None:
    dimensions = sidecar.get("dimensions") if isinstance(sidecar, Mapping) else None
    items = dimensions.get("items") if isinstance(dimensions, Mapping) else None
    if isinstance(items, Sequence) and 0 <= gt_index < len(items):
        item = items[gt_index]
        return item if isinstance(item, Mapping) else None
    return None


def _fmfs_prompt_items(
    sidecar: Mapping[str, Any] | None,
) -> dict[int, Mapping[str, Any]]:
    fmfs = sidecar.get("fmfs") if isinstance(sidecar, Mapping) else None
    prompt = fmfs.get("prompt") if isinstance(fmfs, Mapping) else None
    items = prompt.get("items") if isinstance(prompt, Mapping) else None
    result: dict[int, Mapping[str, Any]] = {}
    if not isinstance(items, Sequence) or isinstance(items, (str, bytes)):
        return result
    for item in items:
        if not isinstance(item, Mapping):
            continue
        try:
            gt_index = int(item["gt_dimension_index"])
        except (KeyError, TypeError, ValueError):
            continue
        result[gt_index] = item
    return result


def _linear_axis(item: Mapping[str, Any], target_dim: Mapping[str, Any]) -> int | None:
    binding = item.get("v51_binding")
    orientation = binding.get("orientation") if isinstance(binding, Mapping) else None
    if orientation == "horizontal":
        return 0
    if orientation == "vertical":
        return 1
    refs = target_dim.get("ref_points", {})
    if isinstance(refs, Mapping) and "defpoint2" in refs and "defpoint3" in refs:
        first = np.asarray(refs["defpoint2"], dtype=float)
        second = np.asarray(refs["defpoint3"], dtype=float)
        delta = np.abs(second - first)
        if float(np.max(delta)) > 1e-12:
            return int(delta[1] > delta[0])
    return None


def _map_prompt_physical_item(
    context: Mapping[str, Any],
    rows: Mapping[str, Any],
    sidecar: Mapping[str, Any] | None,
    target: Mapping[str, Any],
    fmfs_item: Mapping[str, Any],
) -> tuple[dict[str, Any] | None, str | None]:
    semantic = str(fmfs_item.get("semantic_type") or "")
    if semantic not in PHYSICAL_SUPPORTED_SEMANTICS:
        return None, f"unsupported_semantic:{semantic or 'missing'}"
    if not fmfs_item.get("physical_eligible"):
        return None, "fmfs_item_not_physical_eligible"
    binding = fmfs_item.get("binding")
    geometry_binding = binding.get("geometry") if isinstance(binding, Mapping) else None
    if not isinstance(geometry_binding, Mapping) or geometry_binding.get("state") != "certified":
        return None, "geometry_binding_not_certified"
    role = target.get("role")
    if role not in context.get("gt_by_role", {}):
        return None, "semantic_view_role_unavailable"
    target_view = context["gt_by_role"][role]
    row = rows[role]
    spec_family = BASE._semantic_family(target["spec"].get("family"))
    target_dim = target["dimension"]
    measurement = target_dim.get("measurement")
    if not isinstance(measurement, (int, float)) or float(measurement) <= 1e-12:
        return None, "target_geometry_measurement_unavailable"

    if spec_family == "linear":
        sidecar_item = _sidecar_dimension_item(sidecar, target["gt_index"])
        axis = _linear_axis(sidecar_item or {}, target_dim)
        if axis is None:
            return None, "linear_axis_unavailable"
        gt_size = np.asarray(target_view["size"], dtype=float)
        gt_value = float(gt_size[axis])
        relative = abs(float(measurement) / max(gt_value, 1e-12) - 1.0)
        if relative > MAX_GEOMETRY_BINDING_REL_ERROR:
            return None, "linear_dimension_not_equal_to_view_extent"
        pred_index = context["alignment"].get("role_to_pred", {}).get(role)
        if not isinstance(pred_index, int) or not 0 <= pred_index < len(context.get("pred_views", [])):
            score = 0.0
            pred_value = None
            log_error = None
        else:
            scale = float(context["alignment"].get("global_scale", 1.0))
            pred_value = float(context["pred_views"][pred_index]["size"][axis]) * scale
            log_error = abs(math.log(max(pred_value, 1e-12) / gt_value))
            score = math.exp(-log_error / 0.10)
        return {
            "id": target["spec"]["id"],
            "gt_dimension_index": target["gt_index"],
            "semantic": semantic,
            "role": role,
            "measurement": "bbox_width" if axis == 0 else "bbox_height",
            "target_actual_geometry": BASE._round(gt_value),
            "predicted_actual_geometry_aligned": BASE._round(pred_value),
            "log_error": BASE._round(log_error),
            "score": BASE._round(score),
        }, None

    if spec_family not in {"diameter", "radius"}:
        return None, f"unsupported_dimension_family:{spec_family}"
    multiplier = 2.0 if spec_family == "diameter" else 1.0
    candidates: list[tuple[str, int, float]] = []
    for family in ("circle", "arc"):
        plural = "circles" if family == "circle" else "arcs"
        for index, primitive in enumerate(target_view["entities"].get(plural, [])):
            geometry_value = multiplier * abs(float(primitive[2]))
            relative = abs(float(measurement) / max(geometry_value, 1e-12) - 1.0)
            if relative <= MAX_GEOMETRY_BINDING_REL_ERROR:
                candidates.append((family, index, geometry_value))
    if len(candidates) != 1:
        return None, "circular_geometry_binding_not_unique"
    family, target_index, geometry_value = candidates[0]
    primitive_row = row["primitive"][family]
    matched_pair = next(
        (
            pair
            for pair in primitive_row.get("pairs", [])
            if int(pair.get("target_index", -1)) == target_index
        ),
        None,
    )
    if matched_pair is None:
        score = 0.0
        log_error = None
    else:
        log_error = float(matched_pair.get("radius_log_error", 0.0))
        score = math.exp(-log_error / 0.10)
    return {
        "id": target["spec"]["id"],
        "gt_dimension_index": target["gt_index"],
        "semantic": semantic,
        "role": role,
        "measurement": f"{family}_{spec_family}",
        "target_actual_geometry": BASE._round(geometry_value),
        "matched": matched_pair is not None,
        "radius_log_error": BASE._round(log_error),
        "score": BASE._round(score),
    }, None


def _prompt_physical_component(
    context: Mapping[str, Any],
    rows: Mapping[str, Any],
    sidecar: Mapping[str, Any] | None,
) -> dict[str, Any]:
    contract, prompt = _scope_contract(sidecar, "prompt")
    if not prompt.get("physical_eligible"):
        return BASE._component(
            None,
            False,
            "prompt_physical_mask_ineligible",
            scope="prompt_masked_actual_geometry",
            contract_errors=contract.get("errors", []),
            reason_codes=prompt.get("reason_codes", []),
            reads_prediction_dimension_text=False,
        )
    mask = prompt.get("physical_mask", [])
    selected_indices = {index for index, selected in enumerate(mask) if selected}
    targets = [
        target
        for target in _dimension_targets(context, sidecar, contract)
        if target["spec_index"] in selected_indices
    ]
    fmfs_items = _fmfs_prompt_items(sidecar)
    mapped: list[dict[str, Any]] = []
    errors: list[dict[str, Any]] = []
    for target in targets:
        item = fmfs_items.get(target["gt_index"])
        if item is None:
            errors.append(
                {"gt_dimension_index": target["gt_index"], "reason": "missing_fmfs_prompt_item"}
            )
            continue
        row, error = _map_prompt_physical_item(context, rows, sidecar, target, item)
        if error:
            errors.append(
                {"gt_dimension_index": target["gt_index"], "reason": error}
            )
        elif row is not None:
            mapped.append(row)
    if not targets or errors or len(mapped) != len(targets):
        return BASE._component(
            None,
            False,
            "prompt_physical_actual_geometry_mapping_incomplete",
            scope="prompt_masked_actual_geometry",
            n_selected=len(targets),
            n_mapped=len(mapped),
            mapping_errors=errors,
            mapped_items=mapped,
            reads_prediction_dimension_text=False,
            fallback_to_full_gt_physical=False,
        )
    qualities = [float(item["score"]) for item in mapped]
    macro = float(np.mean(qualities))
    worst = min(qualities)
    score = 0.55 * macro + 0.45 * worst
    return BASE._component(
        score,
        True,
        "ok" if score >= ENGINEERING_THRESHOLDS["physical"] else "prompt_mapped_actual_geometry_mismatch",
        scope="prompt_masked_actual_geometry",
        macro=BASE._round(macro),
        worst=BASE._round(worst),
        items=mapped,
        reads_prediction_dimension_text=False,
        fallback_to_full_gt_physical=False,
        uniform_sheet_scale_invariant=True,
    )


def _full_gt_physical_component(
    context: Mapping[str, Any],
    rows: Mapping[str, Any],
    sidecar: Mapping[str, Any] | None,
) -> dict[str, Any]:
    component = RC2._physical_component(context, rows, sidecar)
    details = component.setdefault("details", {})
    details["scope"] = "offline_full_gt_actual_geometry"
    details["prompt_mask_applied"] = False
    details["reads_prediction_dimension_text"] = False
    details["uniform_sheet_scale_invariant"] = True
    details["fail_closed_for_unsupported_semantics"] = False
    return component


def _structure_component(
    context: Mapping[str, Any], frozen: Mapping[str, Any]
) -> dict[str, Any]:
    """Independent validity gate; ordinary geometry/layout errors do not enter."""

    pred_meta = context.get("pred_meta", {})
    gt_meta = context.get("gt_meta", {})
    pred_counts = pred_meta.get("entity_type_counts", {})
    gt_counts = gt_meta.get("entity_type_counts", {})
    pred_native = int(pred_meta.get("native_dimensions", 0) or 0)
    gt_native = int(gt_meta.get("native_dimensions", 0) or 0)
    pred_text_total = sum(int(pred_counts.get(name, 0) or 0) for name in ("TEXT", "MTEXT"))
    gt_text_total = sum(int(gt_counts.get(name, 0) or 0) for name in ("TEXT", "MTEXT"))
    pred_annotation_total = pred_native + pred_text_total
    gt_annotation_total = gt_native + gt_text_total
    annotation_limit = max(
        SEVERE_ANNOTATION_SPAM_ALLOWANCE,
        gt_annotation_total + SEVERE_ANNOTATION_SPAM_ALLOWANCE,
        SEVERE_ANNOTATION_SPAM_MULTIPLIER * gt_annotation_total,
    )
    severe_annotation_spam = pred_annotation_total > annotation_limit
    unsupported = int(pred_meta.get("unsupported_geometry_like", 0) or 0)
    anti_hack = frozen.get("anti_hack", {}) if isinstance(frozen, Mapping) else {}
    try:
        duplicate_ratio = float(
            anti_hack.get("true_duplicate_dimension_ratio", 0.0) or 0.0
        )
    except (TypeError, ValueError):
        duplicate_ratio = 0.0
    alignment = context.get("alignment", {})
    accounting_ok = bool(alignment.get("all_extra_clusters_accounted_for", False))
    readable = bool(pred_meta.get("readable"))
    nondegenerate = bool(context.get("prediction_valid"))
    valid = bool(
        readable
        and nondegenerate
        and accounting_ok
        and unsupported == 0
        and duplicate_ratio < 0.50
        and not severe_annotation_spam
    )
    flags = [
        name
        for name, active in (
            ("unreadable_or_degenerate", not (readable and nondegenerate)),
            ("extra_cluster_accounting_incomplete", not accounting_ok),
            ("unsupported_geometry_like", unsupported > 0),
            ("true_duplicate_dimension_spam", duplicate_ratio >= 0.50),
            ("severe_dimension_or_text_spam", severe_annotation_spam),
        )
        if active
    ]
    return BASE._component(
        1.0 if valid else 0.0,
        True,
        "ok" if valid else "independent_validity_or_anti_hack_gate_failed",
        gate_only=True,
        flags=flags,
        readable=readable,
        nondegenerate=nondegenerate,
        all_extra_clusters_accounted_for=accounting_ok,
        unsupported_geometry_like=unsupported,
        true_duplicate_dimension_ratio=BASE._round(duplicate_ratio),
        predicted_native_dimensions=pred_native,
        predicted_text_mtext=pred_text_total,
        predicted_dimension_like_text=int(pred_meta.get("dimension_like_text", 0) or 0),
        target_annotation_inventory=gt_annotation_total,
        predicted_annotation_inventory=pred_annotation_total,
        severe_annotation_spam_limit=annotation_limit,
        positive_continuous_reward=False,
        reads_geometry_or_layout_quality=False,
    )


def _scoped_hierarchical_reward(
    components: Mapping[str, Mapping[str, Any]],
    atomic: Mapping[str, Any],
    *,
    scope: str,
) -> dict[str, Any]:
    """Renormalise absent optional stages instead of silently substituting them."""

    def eligible_score(name: str) -> float | None:
        row = components[name]
        value = row.get("score")
        if row.get("eligible") and isinstance(value, (int, float)):
            return float(value)
        return None

    structure = eligible_score("structure")
    view = eligible_score("view")
    geometry = eligible_score("geometry")
    if structure is None or view is None or geometry is None:
        return {
            "score": None,
            "eligible": False,
            "scope": scope,
            "reason": "required_reward_stage_ineligible",
        }
    topology = float(atomic.get("topology_score", 0.0))
    layout = eligible_score("layout")
    physical = eligible_score("physical")
    annotation = eligible_score("annotation")
    view_topology_gate = BASE._harmonic(view, topology)
    geometry_gate = BASE._harmonic(view_topology_gate, geometry)
    stages: dict[str, float] = {
        "view_topology": view_topology_gate
        * (0.70 + 0.30 * layout if layout is not None else 1.0),
        "geometry": view_topology_gate * geometry,
    }
    weights = {"view_topology": 0.35, "geometry": 0.30}
    upstream = geometry_gate
    if physical is not None:
        stages["physical"] = geometry_gate * physical
        weights["physical"] = 0.20
        upstream = BASE._harmonic(geometry_gate, physical)
    if annotation is not None:
        stages["annotation"] = upstream * annotation
        weights["annotation"] = 0.15
    active_weight = sum(weights.values())
    reward = structure * sum(weights[name] * stages[name] for name in weights) / active_weight
    excluded = [
        name
        for name in ("layout", "physical", "annotation")
        if eligible_score(name) is None
    ]
    return {
        "score": BASE._round(reward),
        "eligible": True,
        "scope": scope,
        "reason": "ok",
        "structure_gate": BASE._round(structure),
        "view_topology_gate": BASE._round(view_topology_gate),
        "geometry_gate": BASE._round(geometry_gate),
        "stages": {name: BASE._round(value) for name, value in stages.items()},
        "active_weights": {name: BASE._round(value / active_weight) for name, value in weights.items()},
        "excluded_ineligible_components": excluded,
        "ineligible_components_are_not_substituted": True,
    }


def _benchmark(components: Mapping[str, Mapping[str, Any]]) -> dict[str, Any]:
    states: dict[str, bool | None] = {}
    for name, threshold in ENGINEERING_THRESHOLDS.items():
        row = components[name]
        value = row.get("score")
        states[f"{name}_pass"] = (
            bool(float(value) >= threshold)
            if row.get("eligible") and isinstance(value, (int, float))
            else None
        )
    evaluable = all(value is not None for value in states.values())
    success = all(bool(value) for value in states.values()) if evaluable else None
    return {
        **states,
        "fully_evaluable": evaluable,
        "engineering_success": success,
        "cad_pass": success,
        "thresholds": dict(ENGINEERING_THRESHOLDS),
        "scope": "offline_full_gt_executed_dxf",
        "uniform_sheet_scale_invariant": True,
    }


def _matching_diagnostics(context: Mapping[str, Any]) -> dict[str, Any]:
    excluded = {
        "raw_pred",
        "raw_gt",
        "canonical_pred",
        "canonical_gt",
        "pred_views",
        "pred_views_all",
        "gt_by_role",
    }
    return {
        key: copy.deepcopy(value)
        for key, value in context.items()
        if key not in excluded
    }


def score_dxf_pair(
    pred: str | Path,
    gt: str | Path,
    sidecar: Mapping[str, Any] | None = None,
    category: str | None = None,
    **_kwargs: Any,
) -> dict[str, Any]:
    """Score one executed prediction under explicit full-GT and prompt scopes."""

    frozen = BASE.EV51.score_dxf_pair(pred, gt, sidecar=sidecar, category=category)
    context = _consume_appended_omitted_marker(
        MATCH.build_pair_context(pred, gt, sidecar=sidecar)
    )
    result: dict[str, Any] = {
        "schema_version": SCHEMA_VERSION,
        "metric_version": METRIC_VERSION,
        "category": category,
        "metric_definition": {
            "uniform_sheet_scale_invariant": True,
            "absolute_dxf_plotting_scale_required": False,
            "grpo_connected": False,
        },
        "anti_hack": copy.deepcopy(frozen.get("anti_hack", {})),
        "diagnostics": {
            "v51_frozen": {
                "metric_version": frozen.get("metric_version"),
                "components": copy.deepcopy(frozen.get("components", {})),
                "benchmark": copy.deepcopy(frozen.get("benchmark", {})),
                "anti_hack": copy.deepcopy(frozen.get("anti_hack", {})),
            },
            "matching": _matching_diagnostics(context),
        },
    }
    names = ("view", "geometry", "physical", "annotation", "layout", "structure")
    if not context.get("eligible"):
        components = {
            name: BASE._component(None, False, str(context.get("reason")))
            for name in names
        }
        result["components"] = components
        result["verified_reward_full_gt"] = {
            "score": None,
            "eligible": False,
            "scope": "offline_full_gt_executed_dxf",
            "reason": "target_ineligible",
        }
        result["online_reward_prompt_masked"] = {
            "score": None,
            "eligible": False,
            "scope": "prompt_masked_actual_geometry",
            "reason": "target_ineligible",
            "components": components,
        }
        result["benchmark"] = _benchmark(components)
        result["engineering_success"] = None
        return result
    if not context.get("prediction_valid"):
        components = BASE._zero_components("prediction_dxf_unreadable_or_degenerate")
        full_reward = _scoped_hierarchical_reward(
            components, {"topology_score": 0.0}, scope="offline_full_gt_executed_dxf"
        )
        prompt_reward = _scoped_hierarchical_reward(
            components, {"topology_score": 0.0}, scope="prompt_masked_actual_geometry"
        )
        result["components"] = components
        result["verified_reward_full_gt"] = full_reward
        result["online_reward_prompt_masked"] = {
            **prompt_reward,
            "components": components,
        }
        result["benchmark"] = _benchmark(components)
        result["engineering_success"] = result["benchmark"]["engineering_success"]
        return result

    rows, curve = BASE._semantic_rows(context)
    view = BASE._view_component(context, rows)
    layout = _layout_component(context, rows)
    geometry, atomic = BASE._geometry_component(context, rows, curve)
    full_physical = _full_gt_physical_component(context, rows, sidecar)
    full_annotation = _annotation_component(context, sidecar, scope="full_gt")
    prompt_physical = _prompt_physical_component(context, rows, sidecar)
    prompt_annotation = _annotation_component(context, sidecar, scope="prompt")
    structure = _structure_component(context, frozen)
    components = {
        "view": view,
        "geometry": geometry,
        "physical": full_physical,
        "annotation": full_annotation,
        "layout": layout,
        "structure": structure,
    }
    prompt_components = {
        "view": copy.deepcopy(view),
        "geometry": copy.deepcopy(geometry),
        "physical": prompt_physical,
        "annotation": prompt_annotation,
        "layout": copy.deepcopy(layout),
        "structure": copy.deepcopy(structure),
    }
    full_reward = _scoped_hierarchical_reward(
        components, atomic, scope="offline_full_gt_executed_dxf"
    )
    prompt_reward = _scoped_hierarchical_reward(
        prompt_components, atomic, scope="prompt_masked_actual_geometry"
    )
    benchmark = _benchmark(components)
    result.update(
        {
            "components": components,
            "verified_reward_full_gt": full_reward,
            "online_reward_prompt_masked": {
                **prompt_reward,
                "components": prompt_components,
            },
            "benchmark": benchmark,
            "engineering_success": benchmark["engineering_success"],
        }
    )
    result["diagnostics"].update(
        {
            "semantic_views": rows,
            "curve_geometry": curve,
            "atomic_geometry": {
                key: copy.deepcopy(value)
                for key, value in atomic.items()
                if key != "curve"
            },
            "curve_summary": atomic.get("curve"),
            "release_status": {
                "grpo_connected": False,
                "candidate": METRIC_VERSION,
                "reason": "counterfactual_and_real_generation_acceptance_required",
            },
        }
    )
    return result


__all__ = [
    "ENGINEERING_THRESHOLDS",
    "METRIC_VERSION",
    "PHYSICAL_SUPPORTED_SEMANTICS",
    "SCHEMA_VERSION",
    "score_dxf_pair",
]