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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Canonical joint name mappings for Truebones Zoo animal skeletons (73 species).

Rule-based + lookup mapper that converts diverse Truebones naming conventions
(Bip01_, BN_, jt_, Japanese romaji, Sabrecat_, NPC_, game-engine names) into
standardised lowercase English anatomical labels.

Generated: 2026-03-18
Dataset: truebones_zoo (73 species, 1193 unique raw joint names)
"""

from __future__ import annotations

import re
from typing import Callable

# ---------------------------------------------------------------------------
# Pattern 4: Japanese romaji -> English lookup
# ---------------------------------------------------------------------------

JAPANESE_MAP: dict[str, str] = {
    # Torso / core
    "koshi":      "pelvis",
    "kosi":       "pelvis",          # alternate romanisation
    "hara":       "abdomen",
    "mune":       "chest",
    "kubi":       "neck",
    "atama":      "head",
    "kao":        "face",
    "ago":        "jaw",
    # Limbs (bare form, without L_/R_ prefix)
    "kata":       "shoulder",
    "hiji":       "elbow",
    "te":         "hand",
    "momo":       "thigh",
    "hiza":       "knee",
    "ashi":       "foot",
    # Tail
    "sippo":      "tail",            # numbered variants handled by regex
    # Fish-specific (Pirrana / Tukan)
    "obire":      "tail fin",
    "obireA":     "tail fin upper",
    "obireB":     "tail fin lower",
    "sebire":     "dorsal fin",
    "harabireR":  "right pectoral fin",
    "harabireL":  "left pectoral fin",
    "munabireR":  "right pectoral fin upper",
    "munabireL":  "left pectoral fin upper",
    "eraR":       "right gill",
    "eraL":       "left gill",
    "shiribire":  "anal fin",
    "shiribireA": "anal fin upper",
    "shirihireB": "anal fin lower",  # note: typo in original data
    "shippoA":    "tail upper",
    "shippoB":    "tail lower",
    # Misc
    "o":          "tail base",
}

# ---------------------------------------------------------------------------
# Lookup tables for non-regex special cases
# ---------------------------------------------------------------------------

_STANDALONE_MAP: dict[str, str] = {
    # Root / global joints
    "Hips":          "hips",
    "locator":       "root",
    "locator2":      "root",
    "Trajectory":    "trajectory",
    "Head":          "head",
    "Spine":         "spine",
    "Handle":        "handle",
    "Saddle":        "saddle",
    "MESH":          "mesh",
    "N_ALL":         "root all",
    "MagicEffectsNode": "effects node",
    "EyesBlue":      "right eye",
    "EyesBlue_2":    "left eye",
    "ElkJaw":        "jaw",
    "C_ctrl":        "center control",
    "BN_P":          "pelvis",
    "BN_Shell":      "shell",
    "BN_Down":       "lower body",
    "BN_Downbody":   "lower body",
    # Standalone sided
    "LeftArm":       "left arm",
    "RightArm":      "right arm",
    "LeftForeArm":   "left forearm",
    "RightForeArm":  "right forearm",
    "LeftHand":      "left hand",
    "RightHand":     "right hand",
    "LeftFoot":      "left foot",
    "RightFoot":     "right foot",
    "LeftLeg":       "left leg",
    "RightLeg":      "right leg",
    "LeftUpLeg":     "left upper leg",
    "RightUpLeg":    "right upper leg",
}

# Body part name normalisation for Bip01_ / BN_ / jt_ suffixes
_BODY_PART_MAP: dict[str, str] = {
    # Core
    "pelvis":     "pelvis",
    "spine":      "spine",
    "neck":       "neck",
    "head":       "head",
    "jaw":        "jaw",
    "ribcage":    "ribcage",
    # Upper limb
    "clavicle":   "clavicle",
    "upperarm":   "upper arm",
    "forearm":    "forearm",
    "hand":       "hand",
    "finger":     "finger",
    "thumb":      "thumb",
    "wrist":      "wrist",
    "palm":       "palm",
    # Lower limb
    "thigh":      "thigh",
    "calf":       "calf",
    "horselink":  "pastern",        # extra joint in digitigrade legs
    "foot":       "foot",
    "toe":        "toe",
    "ankle":      "ankle",
    "knee":       "knee",
    "hip":        "hip",
    # Tail
    "tail":       "tail",
    "tai":        "tail",           # BN_Tai variants
    # Face / head
    "ear":        "ear",
    "eye":        "eye",
    "eyeball":    "eyeball",
    "eyebrow":    "eyebrow",
    "eyelid":     "eyelid",
    "nose":       "nose",
    "mouth":      "mouth",
    "lip":        "lip",
    "beard":      "beard",
    "chin":       "chin",
    "tongue":     "tongue",
    "thouge":     "tongue",         # typo in original data
    "tone":       "tongue",         # BN_Tone (Anaconda typo for tongue)
    "mascara":    "eyelash",
    # Appendages
    "wing":       "wing",
    "feeler":     "feeler",
    "feelers":    "feeler",
    "clip":       "claw",           # BN_Clip = pincers
    "claw":       "claw",
    "pincers":    "pincer",
    "tentacles":  "tentacle",
    "piers":      "pincer",         # BN_Piers = pincers (typo)
    "pliers":     "pincer",         # BN_Pliers (typo variant)
    # Fur / mane / hair
    "fur":        "fur",
    "mane":       "mane",
    "hair":       "hair",
    "ponytail":   "ponytail",
    "ponitail":   "ponytail",       # typo in original data
    # Armour / tack
    "halter":     "halter",
    "reins":      "reins",
    "shall":      "shell plate",    # BN_Shall (shell plates)
    # Anatomy
    "shoulder":   "shoulder",
    "elbow":      "elbow",
    # Dinosaur-specific
    "cog":        "center of gravity",
    "spline":     "spine",          # BN_Spline = spine segments
    # Body
    "body":       "body",
    "dorsal":     "dorsal",
    "leg":        "leg",
    "arm":        "arm",
    "collarbone": "collarbone",
    "fang":       "fang",
    # Index / middle / ring / pinky
    "index":      "index",
    "middle":     "middle",
    "ring":       "ring",
    "pinky":      "pinky",
}


# ---------------------------------------------------------------------------
# Helper: CamelCase splitter
# ---------------------------------------------------------------------------

_CAMEL_RE = re.compile(r"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")


def _camel_to_words(s: str) -> str:
    """Split CamelCase into lowercase space-separated words."""
    return _CAMEL_RE.sub(" ", s).lower()


# ---------------------------------------------------------------------------
# Helper: side detection
# ---------------------------------------------------------------------------

def _detect_side(name: str) -> tuple[str, str]:
    """Return (side_prefix, name_without_side).

    side_prefix is "left ", "right ", "center ", or "".
    """
    # _L, _R, _C suffixes (jt_ style)
    m = re.match(r"^(.+?)_(L|R|C)$", name)
    if m:
        sides = {"L": "left ", "R": "right ", "C": "center "}
        return sides[m.group(2)], m.group(1)

    # L_ or R_ prefix
    m = re.match(r"^(L|R)_(.+)$", name)
    if m:
        sides = {"L": "left ", "R": "right "}
        return sides[m.group(1)], m.group(2)

    # Embedded _L_ or _R_ or _C_
    m = re.match(r"^(.+?)_(L|R|C)_(.+)$", name)
    if m:
        sides = {"L": "left ", "R": "right ", "C": "center "}
        return sides[m.group(2)], m.group(1) + "_" + m.group(3)

    return "", name


# ---------------------------------------------------------------------------
# Helper: trailing number extractor
# ---------------------------------------------------------------------------

def _extract_trailing_number(s: str) -> tuple[str, str]:
    """Split 'Foo02' -> ('Foo', ' 2') or 'Foo' -> ('Foo', '')."""
    m = re.match(r"^(.*?)(\d+)$", s)
    if m:
        base = m.group(1).rstrip("_")
        num = str(int(m.group(2)))  # strip leading zeros
        return base, f" {num}"
    return s, ""


# ---------------------------------------------------------------------------
# PREFIX_RULES: list of (regex, handler) applied in priority order
# ---------------------------------------------------------------------------

def _handle_bip01(raw: str) -> str | None:
    """Pattern 1: Bip01_ prefix (most common, ~1900 occurrences)."""
    m = re.match(r"^_?Bip01_(.+)$", raw)
    if not m:
        return None
    rest = m.group(1).lstrip("_")  # strip stray leading underscores

    # Detect Nub suffix (leaf joint)
    is_nub = False
    if rest.endswith("Nub"):
        is_nub = True
        rest = rest[:-3]

    # Detect side
    side, rest = _detect_side(rest)

    # Handle trailing L/R side markers without underscore (SpineL, SpineR)
    if not side:
        side_suffix_m = re.match(r"^(.+?)(L|R)$", rest)
        if side_suffix_m:
            candidate = side_suffix_m.group(1).lower()
            if candidate in _BODY_PART_MAP or candidate.rstrip("_") in _BODY_PART_MAP:
                side = "left " if side_suffix_m.group(2) == "L" else "right "
                rest = side_suffix_m.group(1)

    # Special compound names (check BEFORE number extraction so
    # Spine0_Tail matches correctly)
    rest_lower_full = rest.lower().rstrip("_")
    compound_map = {
        "horselink":         "pastern",
        "head_jaw":          "jaw",
        "head1_jaw":         "jaw",
        "head_muzzle":       "muzzle",
        "head_brain":        "brain",
        "head2_eyeleds":     "eyelid",
        "head11_tungecontroler": "tongue controller",
        "ponytail3_tunge":   "tongue",
        "xtra_spine":        "extra spine",
        "xtra_neck":         "extra neck",
        "arm_nub":           "arm end",
        "leg_mid_nub":       "mid leg end",
        "leg_rear_nub":      "rear leg end",
    }
    if rest_lower_full in compound_map:
        base = compound_map[rest_lower_full]
        result = f"{side}{base}"
        if is_nub and "end" not in result:
            result += " end"
        return result.strip()

    # Compound: Spine0_Tail, Spine0_Tail1, etc.
    spine_tail_m = re.match(
        r"^Spine\d+_Tail(\d*)$", rest, re.IGNORECASE
    )
    if spine_tail_m:
        num = spine_tail_m.group(1)
        suffix = f" {int(num)}" if num else ""
        result = f"{side}tail base{suffix}"
        if is_nub:
            result += " end"
        return result.strip()

    # Compound: Spine1_LWing, Spine1_RWing
    spine_wing_m = re.match(
        r"^Spine\d+_(L|R)Wing$", rest, re.IGNORECASE
    )
    if spine_wing_m:
        wing_side = "left " if spine_wing_m.group(1) == "L" else "right "
        return f"{wing_side}wing root"

    # Compound: Calf_Mid, Calf_Rear, Thigh_Mid, Foot_Mid, etc.
    qual_m = re.match(r"^(\w+?)_(Mid|Rear)$", rest, re.IGNORECASE)
    if qual_m:
        part = qual_m.group(1).lower()
        qualifier = qual_m.group(2).lower()
        canonical_part = _BODY_PART_MAP.get(part, part)
        result = f"{side}{qualifier} {canonical_part}"
        if is_nub:
            result += " end"
        return result.strip()

    # Compound: Foot_1, Foot_2, FootNub_1, Thigh_1, Thigh1_1, etc.
    # Only match limb segment patterns (not Ear_01, Ponytail_L01, etc.)
    _SEGMENT_PARTS = {
        "foot", "calf", "thigh", "toe", "finger",
        "thigh1", "calf1", "foot1",
    }
    part_sub_m = re.match(r"^(\w+?)(\d*)_(\d+)$", rest)
    if part_sub_m:
        part_raw = part_sub_m.group(1).lower()
        if part_raw in _SEGMENT_PARTS:
            group_num = part_sub_m.group(2)
            sub_num = str(int(part_sub_m.group(3)))
            canonical_part = _BODY_PART_MAP.get(part_raw, part_raw)
            group_str = f" {int(group_num)}" if group_num else ""
            result = f"{side}{canonical_part}{group_str} segment {sub_num}"
            if is_nub:
                result += " end"
            return result.strip()

    # Handle Xtra (extra bone) -- BEFORE general number extraction
    rest_lower_pre = rest.lower().rstrip("_")
    if rest_lower_pre.startswith("xtra"):
        # Parse: Xtra[NN][Opp][Nub], Xtra_Spine, Xtra_Neck01, etc.
        # The index is typically 2 digits (01-08), use \d{0,2} to avoid
        # swallowing sub-numbers (e.g. Xtra0102 = Xtra01 + sub 02)
        xtra_m = re.match(
            r"^Xtra_?(\d{0,2})(?:_?([A-Za-z]+?))?(\d*)$", rest, re.IGNORECASE
        )
        if xtra_m:
            xtra_num = xtra_m.group(1)
            xtra_part = (xtra_m.group(2) or "").lower()
            xtra_num2 = xtra_m.group(3)
            n = f" {int(xtra_num)}" if xtra_num else ""
            n2 = f" {int(xtra_num2)}" if xtra_num2 else ""
            if xtra_part == "opp":
                result = f"extra opposite{n}"
            elif xtra_part == "oppnub":
                # Already handled by Nub stripping
                result = f"extra opposite{n}"
            elif xtra_part in _BODY_PART_MAP:
                result = f"extra {_BODY_PART_MAP[xtra_part]}{n2}{n}"
            elif xtra_part:
                result = f"extra {xtra_part}{n2}{n}"
            else:
                result = f"extra{n}"
        else:
            result = "extra"
        result = f"{side}{result}"
        if is_nub:
            result += " end"
        return result.strip()

    # Handle Ponytail with embedded antenna/mandible
    # Must be checked BEFORE general number extraction because
    # the side may already have been extracted from embedded _L_/_R_
    rest_lower_check = rest.lower().rstrip("_")
    if rest_lower_check.startswith("ponytail"):
        # Parse: Ponytail[NN][_]?[L|R][_]?PartName[NN]
        pony_m = re.match(
            r"^Ponytail(\d*)[_]?(?:(L|R)[_]?)?([A-Za-z_]*?)(\d*)$",
            rest, re.IGNORECASE
        )
        if pony_m:
            pony_idx = pony_m.group(1)       # ponytail index
            pony_side_char = pony_m.group(2)  # L or R
            pony_part = pony_m.group(3).lower().rstrip("_") if pony_m.group(3) else ""
            pony_num = pony_m.group(4)        # trailing number on part

            # Determine effective side
            if pony_side_char:
                eff_side = "left " if pony_side_char.upper() == "L" else "right "
            else:
                eff_side = side

            if pony_part and pony_part not in ("ponytail", ""):
                # Embedded body part: antenna, mandible, etc.
                part = _BODY_PART_MAP.get(pony_part, pony_part)
                p_num = f" {int(pony_num)}" if pony_num else ""
                result = f"{eff_side}{part}{p_num}"
            else:
                # Pure sided ponytail: Ponytail_L01, Ponytail_R03
                if pony_num:
                    p_num = f" {int(pony_num)}"
                elif pony_idx:
                    p_num = f" {int(pony_idx)}"
                else:
                    p_num = ""
                result = f"{eff_side}ponytail{p_num}"
        else:
            # Simple ponytail with number
            _, p_num_suffix = _extract_trailing_number(rest)
            result = f"{side}ponytail{p_num_suffix}"
        if is_nub:
            result += " end"
        return result.strip()

    # Now extract trailing number for simple names
    rest_stripped, num_suffix = _extract_trailing_number(rest)
    rest_lower = rest_stripped.lower().rstrip("_")

    # Handle Ear (Bip01_R_Ear_01, Bip01__L_Ear_01)
    if rest_lower.startswith("ear") or rest_lower_check.startswith("ear"):
        # rest may be 'Ear_01' or 'Ear01'
        ear_m = re.match(r"^Ear[_]?(\d+)$", rest, re.IGNORECASE)
        if ear_m:
            n = str(int(ear_m.group(1)))
            result = f"{side}ear {n}"
        else:
            result = f"{side}ear{num_suffix}"
        if is_nub:
            result += " end"
        return result.strip()

    # Standard body part lookup
    part_name = rest_stripped.rstrip("_")
    part_lower = part_name.lower()

    # Try direct lookup (rest is already number-stripped, e.g. "Spine")
    canonical_part = _BODY_PART_MAP.get(part_lower, None)
    if canonical_part is None:
        # Try with an inner trailing number: e.g. "Finger01" where
        # rest_stripped="Finger01" (Nub suffix was the only thing stripped)
        inner_base, inner_num = _extract_trailing_number(part_lower)
        canonical_inner = _BODY_PART_MAP.get(inner_base, None)
        if canonical_inner is not None:
            canonical_part = canonical_inner
            num_suffix = inner_num + num_suffix  # combine inner + outer
        else:
            # CamelCase split: e.g. "UpperArm" -> "upper arm"
            canonical_part = _camel_to_words(part_name).strip()
            # Re-extract number from the camel-split result
            words = canonical_part.split()
            if words and words[-1].isdigit():
                extra_num = f" {int(words[-1])}"
                canonical_part = " ".join(words[:-1])
                num_suffix = extra_num + num_suffix

    result = f"{side}{canonical_part}{num_suffix}"
    if is_nub:
        result += " end"
    return result.strip()


def _handle_bn(raw: str) -> str | None:
    """Pattern 2: BN_ / Bn_ prefix (~900 occurrences)."""
    m = re.match(r"^[Bb][Nn]_(.+)$", raw)
    if not m:
        return None
    rest = m.group(1)

    # Detect Nub suffix
    is_nub = False
    if rest.endswith("Nub"):
        is_nub = True
        rest = rest[:-3]

    # Handle BN_Bip01_Pelvis style (nested prefix)
    if rest.startswith("Bip01_"):
        inner = _handle_bip01("Bip01_" + rest[6:])
        return inner

    # Handle BN_LWing / BN_RWing (no underscore side marker)
    wing_m = re.match(r"^(L|R)(Wing)(\d+)$", rest)
    if wing_m:
        side = "left " if wing_m.group(1) == "L" else "right "
        num = str(int(wing_m.group(3)))
        return f"{side}wing {num}"

    # Handle BN_LBeard / BN_RBeard / BN_FBeard
    beard_m = re.match(r"^(L|R|F)(Beard|Eyeball)(\d*)$", rest)
    if beard_m:
        side_map = {"L": "left ", "R": "right ", "F": "front "}
        side = side_map[beard_m.group(1)]
        part = beard_m.group(2).lower()
        part = _BODY_PART_MAP.get(part, part)
        num = f" {int(beard_m.group(3))}" if beard_m.group(3) else ""
        return f"{side}{part}{num}"

    # Handle BN_Crab_pincers_L_01 style
    crab_m = re.match(r"^Crab_pincers_(L|R)_(\d+)$", rest)
    if crab_m:
        side = "left " if crab_m.group(1) == "L" else "right "
        num = str(int(crab_m.group(2)))
        return f"{side}pincer {num}"

    # Handle double-underscore: BN__Forearm_L_01, BN__Neck_01, BN__UpperArm_R_01
    if rest.startswith("_"):
        rest = rest.lstrip("_")

    # Detect side
    side, rest = _detect_side(rest)

    # Extract trailing number
    rest, num_suffix = _extract_trailing_number(rest)

    # Lookup body part
    rest_clean = rest.rstrip("_").lower()

    # Handle compound: Toe01, Toe0, Foot
    # Strip inner number: Toe01 -> Toe + 1
    inner_num_m = re.match(r"^(\w+?)(\d+)$", rest_clean)
    if inner_num_m:
        inner_base = inner_num_m.group(1)
        inner_num = str(int(inner_num_m.group(2)))
        canonical_part = _BODY_PART_MAP.get(inner_base, inner_base)
        result = f"{side}{canonical_part} {inner_num}{num_suffix}"
    else:
        canonical_part = _BODY_PART_MAP.get(rest_clean, None)
        if canonical_part is None:
            canonical_part = _camel_to_words(rest.rstrip("_")).strip()
        result = f"{side}{canonical_part}{num_suffix}"

    if is_nub:
        result += " end"
    return result.strip()


def _handle_jt(raw: str) -> str | None:
    """Pattern 3: jt_ prefix (Trex, Raptor2/3, ~286 occurrences)."""
    m = re.match(r"^jt_(.+)$", raw)
    if not m:
        return None
    rest = m.group(1)

    # Detect side (_L, _R, _C suffix)
    side, rest = _detect_side(rest)

    # Extract trailing number
    rest, num_suffix = _extract_trailing_number(rest)

    # Handle compound names with CamelCase: ToeMiddle, ClawInner, etc.
    words = _camel_to_words(rest.rstrip("_")).strip()

    # Remap known parts
    tokens = words.split()
    mapped_tokens = []
    for t in tokens:
        mapped_tokens.append(_BODY_PART_MAP.get(t, t))
    canonical = " ".join(mapped_tokens)

    # Special: "x" suffix on tail (jt_Tail01x_C -> tail 1 secondary)
    if canonical.endswith("x"):
        canonical = canonical[:-1].rstrip() + " secondary"

    result = f"{side}{canonical}{num_suffix}"
    return result.strip()


def _handle_japanese(raw: str) -> str | None:
    """Pattern 4: Japanese romaji (Alligator, Pirrana, Tukan)."""
    # Direct match
    if raw in JAPANESE_MAP:
        return JAPANESE_MAP[raw]

    # L_/R_ prefixed romaji: L_kata -> left shoulder
    m = re.match(r"^(L|R)_(.+)$", raw)
    if m:
        side = "left " if m.group(1) == "L" else "right "
        base = m.group(2)
        # Try with trailing number: sippo01 -> tail 1
        base_word, num = _extract_trailing_number(base)
        if base_word in JAPANESE_MAP:
            return f"{side}{JAPANESE_MAP[base_word]}{num}"
        if base in JAPANESE_MAP:
            return f"{side}{JAPANESE_MAP[base]}"
        return None

    # Numbered romaji: sippo01 -> tail 1
    base_word, num = _extract_trailing_number(raw)
    if base_word in JAPANESE_MAP:
        return f"{JAPANESE_MAP[base_word]}{num}"

    return None


def _handle_npc(raw: str) -> str | None:
    """Pattern 5a: NPC_ prefix (SabreToothTiger reskin, ~77 occurrences)."""
    m = re.match(r"^NPC_(.+)$", raw)
    if not m:
        return None
    rest = m.group(1)

    # Strip trailing short-code markers like __Head_, __LMag_ (max 6 chars)
    rest = re.sub(r"__\w{1,6}_$", "", rest)

    # Detect side via L/R prefix in subname
    side = ""
    side_m = re.match(r"^(L|R)_?(.+)$", rest)
    if side_m and len(side_m.group(2)) > 1:  # avoid matching single chars
        side = "left " if side_m.group(1) == "L" else "right "
        rest = side_m.group(2)

    # Special: magic node
    if "MagicNode" in rest or "MagicEffects" in rest:
        return f"{side}magic node".strip()

    # Extract trailing number
    rest, num_suffix = _extract_trailing_number(rest)

    # Handle specific NPC compound names
    rest_lower = rest.rstrip("_").lower()
    npc_special = {
        "head":        "head",
        "jaw":         "jaw",
        "nose":        "nose",
        "pelvis":      "pelvis",
        "ribcage":     "ribcage",
        "neckjiggle":  "neck jiggle",
        "armjiggle":   "arm jiggle",
        "armpalm":     "palm",
        "armball":     "arm ball",
        "armcollarbone": "collarbone",
        "thighjiggle": "thigh jiggle",
        "legankle":    "ankle",
        "legball":     "leg ball",
        "upperlip":    "upper lip",
        "upperleftlip":  "upper left lip",
        "upperrightlip": "upper right lip",
        "lowerfrontlip": "lower front lip",
        "lowerleftlip":  "lower left lip",
        "lowerrightlip": "lower right lip",
        "eyebrow":     "eyebrow",
        "spine1backjiggle": "spine 1 back jiggle",
        "spine1jiggle": "spine 1 jiggle",
        "spine4jiggle": "spine 4 jiggle",
    }
    if rest_lower in npc_special:
        result = f"{side}{npc_special[rest_lower]}{num_suffix}"
        return result.strip()

    # CamelCase split and map
    words = _camel_to_words(rest.rstrip("_")).strip()

    # Handle embedded side markers: LArm1, RLeg2, etc.
    inner_side_m = re.match(r"^(l|r)(\w+)$", words.replace(" ", ""))
    if inner_side_m and not side:
        inner_s = inner_side_m.group(1)
        side = "left " if inner_s == "l" else "right "
        words = _camel_to_words(rest.rstrip("_")[1:]).strip()

    tokens = words.split()
    mapped = []
    skip_next = False
    for i, t in enumerate(tokens):
        if skip_next:
            skip_next = False
            continue
        # Handle "upper arm twist 1" -> "upper arm twist 1"
        mapped.append(_BODY_PART_MAP.get(t, t))
    canonical = " ".join(mapped)

    result = f"{side}{canonical}{num_suffix}"
    return result.strip()


def _handle_sabrecat(raw: str) -> str | None:
    """Pattern 5b: Sabrecat_ prefix (SabreToothTiger, ~63 occurrences)."""
    m = re.match(r"^Sabrecat_(.+)$", raw)
    if not m:
        return None
    rest = m.group(1)

    # Special: _pelv_ (pelvis) -- check BEFORE stripping short codes
    if rest.lstrip("_").startswith("pelv"):
        return "pelvis"

    # Handle Head sub-parts BEFORE short-code stripping (the trailing
    # codes carry the actual sub-part info for Head joints)
    # Patterns: Head__LEye_, Head__REye_, Head__RChk_, Head__LChk_,
    #           Head_Head__LChk_, Head_jaw_, Head_LM01_, Head_RM01_,
    #           HeadLeftEar_LEar_, HeadRightEar_REar_,
    #           Head_EyeLid_HELT_, HeadEyeLid__HELB_
    rest_for_head = rest
    if rest_for_head.startswith("Head"):
        sub = rest_for_head[4:].strip("_")
        if not sub:
            return "head"
        sub_lower = sub.lower().strip("_")

        # Try to interpret the head sub-part
        head_sabrecat_map = {
            "jaw": "jaw",
            "leye": "left eye",
            "reye": "right eye",
            "lchk": "left cheek",
            "rchk": "right cheek",
            "lm01": "left muzzle 1",
            "rm01": "right muzzle 1",
            "helt": "upper eyelid",
            "helb": "lower eyelid",
        }
        # Extract the short code from the full sub-part
        # e.g. "Head__LChk_" -> sub = "Head__LChk", look at last code
        codes = [c for c in sub.split("_") if c]
        if codes:
            last_code = codes[-1].lower()
            if last_code in head_sabrecat_map:
                return head_sabrecat_map[last_code]
            # Check all codes for known head parts
            for code in codes:
                cl = code.lower()
                if cl in head_sabrecat_map:
                    return head_sabrecat_map[cl]

        # EyeLid patterns
        if "eyelid" in sub_lower:
            return "eyelid"
        # Jaw
        if "jaw" in sub_lower:
            return "jaw"
        # Head (identity)
        if sub_lower.startswith("head"):
            inner = sub_lower[4:].strip("_")
            if not inner:
                return "head"
        # Fallback for head sub-parts
        inner = _camel_to_words(sub.split("_")[0])
        return f"head {inner}".strip()

    # HeadLeftEar / HeadRightEar (without leading Sabrecat_)
    if rest_for_head.startswith("HeadLeft"):
        part = rest_for_head[8:].split("_")[0].lower()
        return f"left {part}"
    if rest_for_head.startswith("HeadRight"):
        part = rest_for_head[9:].split("_")[0].lower()
        return f"right {part}"
    if rest_for_head.startswith("HeadEyeLid"):
        return "eyelid"

    # Extract side and number from trailing short code before stripping
    code_side = ""
    code_num = ""
    code_m = re.search(r"_([LR]?)(\w*?)(\d+)_$", rest)
    if code_m:
        if code_m.group(1):
            code_side = "left " if code_m.group(1) == "L" else "right "
        code_num = f" {int(code_m.group(3))}"

    # Strip trailing short code: _LThi_, _RClf_, _Spn0_ etc.
    rest = re.sub(r"_\w{2,5}_$", "", rest)

    # Detect side via Left/Right in name, with fallback to short code side
    side = ""
    if rest.startswith("Left"):
        side = "left "
        rest = rest[4:]
    elif rest.startswith("Right"):
        side = "right "
        rest = rest[5:]
    elif code_side:
        side = code_side

    # Handle Neck, Spine, Ribcage, Tail, Finger, Toe
    rest, num_suffix = _extract_trailing_number(rest)
    # Use short-code number as fallback if no number in the main part
    if not num_suffix and code_num:
        num_suffix = code_num
    words = _camel_to_words(rest.rstrip("_")).strip()
    tokens = words.split()
    mapped = []
    for t in tokens:
        mapped.append(_BODY_PART_MAP.get(t, t))
    canonical = " ".join(mapped)

    result = f"{side}{canonical}{num_suffix}"
    return result.strip()


def _handle_game_engine(raw: str) -> str | None:
    """Pattern 5c: Game-engine names (Spider, etc.)."""
    # Arm[LR]Collarbone, Arm[LR]Claw, Arm[LR]_01_
    arm_m = re.match(r"^Arm(L|R)(\w+?)_?$", raw)
    if arm_m:
        side = "left " if arm_m.group(1) == "L" else "right "
        rest = arm_m.group(2)
        rest, num = _extract_trailing_number(rest)
        part = _BODY_PART_MAP.get(rest.lower(), _camel_to_words(rest))
        return f"{side}arm {part}{num}".strip()

    # Leg_[LR]_NN_
    leg_m = re.match(r"^Leg_(L|R)_(\d+)_$", raw)
    if leg_m:
        side = "left " if leg_m.group(1) == "L" else "right "
        idx = int(leg_m.group(2))
        leg_group = idx // 10
        seg = idx % 10
        return f"{side}leg {leg_group} segment {seg}"

    # Fang[LR]_NN_
    fang_m = re.match(r"^Fang(L|R)_(\d+)_$", raw)
    if fang_m:
        side = "left " if fang_m.group(1) == "L" else "right "
        num = str(int(fang_m.group(2)))
        return f"{side}fang {num}"

    # _[LR]Toe[N]_ or _[LR]Jaw_
    toe_m = re.match(r"^_(L|R)(Toe|Jaw)(\d*)_$", raw)
    if toe_m:
        side = "left " if toe_m.group(1) == "L" else "right "
        part = toe_m.group(2).lower()
        num = f" {int(toe_m.group(3))}" if toe_m.group(3) else ""
        return f"{side}{part}{num}"

    # _body_
    if raw == "_body_":
        return "body"

    # NPC_Head__Head_
    if raw == "NPC_Head__Head_":
        return "head"

    # Elk* prefix (Raindeer-like)
    elk_m = re.match(r"^Elk(L|R)?(.+)$", raw)
    if elk_m:
        side = ""
        if elk_m.group(1):
            side = "left " if elk_m.group(1) == "L" else "right "
        rest = elk_m.group(2)
        # Handle compound: UpperLip, FrontHoof, etc.
        rest_lower = rest.lower().rstrip("_")
        elk_parts = {
            "pelvis":       "pelvis",
            "ribcage":      "ribcage",
            "scull":        "skull",
            "scullbase":    "skull base",
            "jaw":          "jaw",
            "ear":          "ear",
            "femur":        "femur",
            "tibia":        "tibia",
            "humerus":      "humerus",
            "radius":       "radius",
            "scapula":      "scapula",
            "metacarpus":   "metacarpus",
            "phalanxprima": "phalanx prima",
            "phalangesmanus": "phalanges manus",
            "largecannon":  "cannon bone",
            "fronthoof":    "front hoof",
            "rearhoof":     "rear hoof",
            "upperlip":     "upper lip",
        }
        rest_clean, num = _extract_trailing_number(rest_lower)
        part = elk_parts.get(rest_clean, None)
        if part is None:
            part = elk_parts.get(rest_lower, None)
        if part is None:
            part = _camel_to_words(rest).strip()
            rest_clean2, num = _extract_trailing_number(part)
            part = rest_clean2
        return f"{side}{part}{num}".strip()

    # Bone[NN] (generic unnamed bones)
    bone_m = re.match(r"^Bone(\d+)$", raw)
    if bone_m:
        return f"bone {int(bone_m.group(1))}"

    # Tail[NN] standalone
    tail_m = re.match(r"^Tail(\d+)$", raw)
    if tail_m:
        return f"tail {int(tail_m.group(1))}"

    # body01
    body_m = re.match(r"^body(\d+)$", raw)
    if body_m:
        return f"body {int(body_m.group(1))}"

    # Pure numbered: _00, _01, ..., _23
    num_m = re.match(r"^_(\d+)$", raw)
    if num_m:
        return f"joint {int(num_m.group(1))}"

    return None


def _handle_misc(raw: str) -> str | None:
    """Catch-all for remaining patterns."""
    # IK_Chain01, Dummy01_*, ESI1_*, ProjectileNode_*
    if raw.startswith("IK_"):
        return "ik " + _camel_to_words(raw[3:]).strip()
    if raw.startswith("Dummy01_"):
        return "dummy " + _camel_to_words(raw[8:]).strip().rstrip("_")
    if raw.startswith("ESI1_"):
        return _camel_to_words(raw[5:]).strip()
    if raw.startswith("ProjectileNode_"):
        return "projectile " + raw[15:].lower().rstrip("_")
    # NPC_L_MagicNode__LMag_
    if "MagicNode" in raw or "MagicEffects" in raw:
        side = "left " if "_L_" in raw or "NPC_L" in raw else (
               "right " if "_R_" in raw else "")
        return f"{side}magic node".strip()
    # BN_center
    if raw == "BN_center":
        return "center"

    return None


# ---------------------------------------------------------------------------
# PREFIX_RULES: ordered list of (pattern_regex, handler_function)
# ---------------------------------------------------------------------------

PREFIX_RULES: list[tuple[str, Callable[[str], str | None]]] = [
    # Highest priority: exact matches (standalone + Japanese)
    (r"^(Hips|locator2?|Trajectory|Head|Spine|Handle|Saddle|MESH|N_ALL|"
     r"MagicEffectsNode|EyesBlue|EyesBlue_2|C_ctrl|BN_P|BN_Shell|BN_Down|"
     r"BN_Downbody|BN_center|Left\w+|Right\w+)$",
     lambda raw: _STANDALONE_MAP.get(raw)),

    # Japanese romaji (check before Bip01 since L_/R_ prefix overlaps)
    (r"^(?:[LR]_)?(?:koshi|kosi|hara|mune|kubi|atama|kao|ago|kata|hiji|te|"
     r"momo|hiza|ashi|sippo|obire|sebire|harabire|munabire|era|shiribire|"
     r"shirihire|shippo|o)\w*$",
     _handle_japanese),

    # Bip01_ prefix (most common)
    (r"^_?Bip01_", _handle_bip01),

    # BN_ / Bn_ prefix
    (r"^[Bb][Nn]_", _handle_bn),

    # jt_ prefix
    (r"^jt_", _handle_jt),

    # NPC_ prefix
    (r"^NPC_", _handle_npc),

    # Sabrecat_ prefix
    (r"^Sabrecat_", _handle_sabrecat),

    # Game-engine patterns (Spider, Elk, Bone, etc.)
    (r"^(?:Arm[LR]|Leg_[LR]|Fang[LR]|_[LR](?:Toe|Jaw)|_body_|_\d+$|"
     r"Elk[LR]?|Bone\d|Tail\d|body\d|NPC_Head__Head_)",
     _handle_game_engine),

    # Miscellaneous catch-all
    (r".", _handle_misc),
]

# Pre-compile regexes
_COMPILED_RULES: list[tuple[re.Pattern, Callable[[str], str | None]]] = [
    (re.compile(pattern), handler) for pattern, handler in PREFIX_RULES
]


# ---------------------------------------------------------------------------
# Main API
# ---------------------------------------------------------------------------

def canonicalize_zoo_joint(name: str) -> str:
    """Convert a single Truebones Zoo raw joint name to canonical form.

    Parameters
    ----------
    name : str
        Raw joint name as stored in the skeleton .npz file.

    Returns
    -------
    str
        Lowercase canonical English name. Falls back to lowercased + cleaned
        version of the input if no rule matches.
    """
    # Try each rule in priority order
    for pattern, handler in _COMPILED_RULES:
        if pattern.search(name):
            result = handler(name)
            if result is not None:
                # Final cleanup: collapse whitespace, strip
                result = re.sub(r"\s+", " ", result).strip()
                return result

    # Fallback: lowercase, strip underscores/trailing _
    fallback = name.strip("_").lower()
    fallback = re.sub(r"[_]+", " ", fallback).strip()
    return fallback


def get_zoo_canonical_names(joint_names: list[str]) -> list[str]:
    """Map a list of raw Truebones Zoo joint names to canonical form.

    Parameters
    ----------
    joint_names : list[str]
        Raw joint names from a skeleton .npz file.

    Returns
    -------
    list[str]
        Canonical names in the same order as *joint_names*.
    """
    return [canonicalize_zoo_joint(n) for n in joint_names]


# ---------------------------------------------------------------------------
# CLI: quick self-test
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    import numpy as np
    from pathlib import Path

    skel_dir = Path(__file__).resolve().parents[2] / "data" / "processed" / "truebones_zoo" / "skeletons"

    test_species = ["Dog", "Cat", "Horse", "Eagle", "Anaconda",
                    "Trex", "Spider", "Ant", "Dragon", "Crab"]

    for species in test_species:
        skel_path = skel_dir / f"{species}.npz"
        if not skel_path.exists():
            print(f"[SKIP] {species}: file not found")
            continue
        data = np.load(str(skel_path), allow_pickle=True)
        raw_names = [str(n) for n in data["joint_names"]]
        canonical = get_zoo_canonical_names(raw_names)
        print(f"\n{'='*60}")
        print(f"  {species}  ({len(raw_names)} joints)")
        print(f"{'='*60}")
        for r, c in zip(raw_names, canonical):
            print(f"  {r:45s} -> {c}")