File size: 59,612 Bytes
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
a44aaae
27c9320
a44aaae
27c9320
a44aaae
27c9320
a44aaae
27c9320
 
 
 
 
a44aaae
 
27c9320
a44aaae
27c9320
 
 
 
 
 
 
 
 
 
a44aaae
27c9320
a44aaae
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
 
 
 
27c9320
a44aaae
 
27c9320
a44aaae
 
 
 
 
27c9320
a44aaae
 
 
 
27c9320
 
 
a44aaae
 
27c9320
a44aaae
 
27c9320
a44aaae
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
27c9320
 
a44aaae
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
 
 
 
 
27c9320
 
 
a44aaae
27c9320
 
a44aaae
27c9320
 
a44aaae
27c9320
 
 
 
 
 
 
 
 
 
 
 
a44aaae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
 
 
27c9320
a44aaae
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
a44aaae
 
27c9320
 
 
 
a44aaae
27c9320
 
a44aaae
27c9320
 
 
 
a44aaae
27c9320
 
a44aaae
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
a44aaae
 
27c9320
 
a44aaae
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44aaae
27c9320
 
 
 
 
a44aaae
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdb26a6
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
"""
Per-field comparison rules per TIE Logics.docx.
Each rule returns: (transformed_value:str, bna_value_str:str, match:str, recommendation:str)
match values: "Match" | "Differ"
"""
from __future__ import annotations
import re
import unicodedata
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple


def _strip_accents(s):
    """Remove diacritics (accents) from a string. 'Águila' -> 'Aguila',
    'Peña' -> 'Pena'. Used by _norm_name so person/company name
    comparison is accent-insensitive."""
    if not s: return s
    nfkd = unicodedata.normalize("NFKD", str(s))
    return "".join(ch for ch in nfkd if not unicodedata.combining(ch))

LEGAL_SUFFIXES = {
    "corporation", "corp", "corp.", "limited", "ltd", "ltd.",
    "incorporated", "inc", "inc.", "company", "co", "co.",
    "group", "holdings", "holding", "international", "intl",
    "s.a.", "s.a", "sa", "ltda", "ltda.", "spa", "spa.",
    "ag", "gmbh", "plc", "llc", "l.l.c", "l.l.c.",
    "s.a.s", "sas", "n.v.", "nv", "lda", "lda.", "kk",
    "p.c", "pty", "pte", "pvt", "ehf",
    "the",
}
PUNCT_RE = re.compile(r"[.,!?;:'\"\(\)\[\]\{\}/\\]")
SPACES_RE = re.compile(r"\s+")
# Anchored: matches ONLY when the entire trimmed value is a placeholder.
# Previously this used .search() which falsely flagged long descriptive
# fields (milestones, descriptions) that happened to mention 'TBD' or
# 'not available' inside the body as blank.
NOT_DISCLOSED = re.compile(
    r"^(?:not\s+(?:yet\s+|publicly\s+)?disclosed|not\s+available|n[/\.]?a|tbd|to\s+be\s+(?:determined|disclosed)|no\s+disponible|no\s+divulgado|n[ãa]o\s+dispon[íi]vel|n[ãa]o\s+divulgado|sin\s+divulgar)$",
    re.IGNORECASE)


def _is_blank(v):
    if v is None: return True
    s = str(v).strip()
    if s == "" or s.lower() in ("null", "none", "nan"): return True
    if NOT_DISCLOSED.fullmatch(s): return True
    return False


def _split_csv(v):
    if _is_blank(v): return []
    parts = re.split(r"\s*[,;|]\s*|\s*\n\s*", str(v))
    return [p.strip() for p in parts if p.strip()]


def _norm_name(s):
    if not s: return ""
    # Accent-insensitive + case-insensitive: 'Aníbal Del Águila' and
    # 'Aníbal del Aguila' both normalize to 'anibal del aguila'.
    t = _strip_accents(s).lower().strip()
    t = PUNCT_RE.sub(" ", t)
    t = SPACES_RE.sub(" ", t)
    tokens = [tok for tok in t.split(" ") if tok and tok not in LEGAL_SUFFIXES]
    return " ".join(tokens).strip()


def _proper_case(s):
    if not s: return ""
    out = []
    for word in s.split():
        if word.isupper() and 2 <= len(word) <= 6:
            out.append(word)
        else:
            out.append(word[:1].upper() + word[1:].lower() if word else word)
    return " ".join(out)


# Date helpers
MONTHS_EN = ["January","February","March","April","May","June","July","August","September","October","November","December"]
MONTHS_ES = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]
MONTHS_PT = ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"]
ALL_MONTH_LOOKUP = {}
for arr in (MONTHS_EN, MONTHS_ES, MONTHS_PT):
    for i, m in enumerate(arr, 1):
        ALL_MONTH_LOOKUP[m.lower()] = i
# Short / abbreviated month names (English, Spanish, Portuguese)
for short, idx in {"jan":1,"feb":2,"mar":3,"apr":4,"may":5,"jun":6,"jul":7,
                   "aug":8,"sep":9,"sept":9,"oct":10,"nov":11,"dec":12,
                   "ene":1,"abr":4,"ago":8,"dic":12,
                   "fev":2,"abr":4,"ago":8,"set":9,"out":10,"dez":12}.items():
    ALL_MONTH_LOOKUP[short] = idx


def parse_date(raw):
    if raw is None or raw == "": return None
    if isinstance(raw, datetime): return raw
    s = str(raw).strip()
    if not s: return None
    s = re.sub(r"T\d{2}:\d{2}.*$", "", s)
    for fmt in ("%Y-%m-%d","%Y/%m/%d","%Y.%m.%d","%d-%m-%Y","%d/%m/%Y","%d.%m.%Y","%Y-%m","%m-%Y","%m/%Y","%Y/%m"):
        try: return datetime.strptime(s, fmt)
        except ValueError: pass
    tokens = re.findall(r"[A-Za-zÀ-ÿ]+|\d+", s)
    month, year, day = None, None, 1
    for t in tokens:
        tl = t.lower()
        if tl in ALL_MONTH_LOOKUP: month = ALL_MONTH_LOOKUP[tl]
        elif t.isdigit():
            n = int(t)
            if len(t) == 4: year = n
            elif day == 1 and 1 <= n <= 31: day = n
    if month and year:
        try: return datetime(year, month, day)
        except ValueError: return datetime(year, month, 1)
    return None


def fmt_month_year(dt, lang):
    if not dt: return ""
    if lang == "es": return f"{MONTHS_ES[dt.month-1]} {dt.year}"
    if lang == "pt": return f"{MONTHS_PT[dt.month-1]} {dt.year}"
    return f"{MONTHS_EN[dt.month-1]} {dt.year}"


# Number helpers
def parse_number(raw):
    if raw is None or raw == "": return None
    if isinstance(raw, (int, float)): return float(raw)
    s = re.sub(r"[^\d,.\-]", "", str(raw))
    if not s: return None
    if "," in s and "." in s:
        if s.rfind(",") > s.rfind("."):
            s = s.replace(".", "").replace(",", ".")
        else:
            s = s.replace(",", "")
    elif "," in s:
        parts = s.split(",")
        if len(parts) == 2 and len(parts[-1]) <= 2:
            s = s.replace(",", ".")
        else:
            s = s.replace(",", "")
    elif "." in s:
        # ES/PT thousand-separator: '3.600.000' (multiple dots) or
        # '1.234' followed by 3+ digits — treat dots as thousand sep.
        parts = s.split(".")
        if len(parts) >= 3 or (len(parts) == 2 and len(parts[-1]) == 3 and len(parts[0]) <= 3):
            s = s.replace(".", "")
    try: return float(s)
    except ValueError: return None


# Multiplier suffixes commonly seen in capacity values, both EN and ES/PT.
_MULTIPLIERS = {
    "thousand": 1_000, "thousands": 1_000,
    "mil": 1_000, "miles": 1_000,
    "million": 1_000_000, "millions": 1_000_000,
    "millón": 1_000_000, "millon": 1_000_000,
    "millones": 1_000_000, "milhão": 1_000_000,
    "milhao": 1_000_000, "milhões": 1_000_000, "milhoes": 1_000_000,
    "billion": 1_000_000_000, "billions": 1_000_000_000,
    "mil millones": 1_000_000_000, "bilhão": 1_000_000_000, "bilhao": 1_000_000_000,
}


def _extract_multiplier(text):
    """Return (multiplier, remaining_text). Default multiplier 1."""
    if not text: return 1, ""
    t = str(text).strip()
    low = t.lower()
    # Match longest first
    for word in sorted(_MULTIPLIERS, key=len, reverse=True):
        pat = re.compile(rf"\b{re.escape(word)}\b", re.IGNORECASE)
        m = pat.search(low)
        if m:
            stripped = (t[:m.start()] + " " + t[m.end():]).strip()
            stripped = re.sub(r"\s+", " ", stripped)
            return _MULTIPLIERS[word], stripped
    return 1, t


def fmt_capex(value, lang):
    if value is None: return ""
    decimals = 1 if value <= 99 else 0
    s = f"{value:,.{decimals}f}" if decimals else f"{value:,.0f}"
    if lang in ("es", "pt"):
        s = s.replace(",", "§").replace(".", ",").replace("§", ".")
    return s + " USD"


def normalize_capacity_number(raw):
    n = parse_number(raw)
    if n is None: return None
    if abs(n - round(n)) < 1e-9:
        return float(int(round(n)))
    return n


def extract_numbers(text):
    if not text: return []
    nums = re.findall(r"\d+(?:[.,]\d+)?", text)
    out = []
    for n in nums:
        v = parse_number(n)
        if v is not None: out.append(v)
    return out


def _meaningful_diff(ai_text, bna_text, min_overlap=0.6):
    if _is_blank(ai_text): return False
    if _is_blank(bna_text): return True
    a = set(re.findall(r"[A-Za-zÀ-ÿ0-9]+", ai_text.lower()))
    b = set(re.findall(r"[A-Za-zÀ-ÿ0-9]+", bna_text.lower()))
    if not a: return False
    return (len(a & b) / len(a)) < min_overlap


def parse_latlon(raw):
    if _is_blank(raw): return None
    m = re.findall(r"([+-]?\d+\.?\d*)\s*°?\s*([NSEW])?", str(raw), re.IGNORECASE)
    if not m: return None
    coords = []
    for num, dirc in m[:4]:
        try: v = float(num)
        except ValueError: continue
        if dirc and dirc.upper() in ("S","W"): v = -abs(v)
        elif dirc and dirc.upper() in ("N","E"): v = abs(v)
        coords.append(v)
    return (coords[0], coords[1]) if len(coords) >= 2 else None


def reco_text(label, ai_orig, transformed, bna_value, lang="en"):
    """Localised recommendation text. Each rule now passes the output
    language through (or defaults to 'en')."""
    try:
        import i18n as _i18n
        tpl = _i18n.RECO_TEMPLATE.get(lang, _i18n.RECO_TEMPLATE["en"])
        na = _i18n.NOT_AVAILABLE_LABEL.get(lang, "Not Available")
        # Translate the field-name label too (e.g. 'Capex' is shared,
        # but 'Project Name' becomes 'Nombre del Proyecto' in ES).
        try:
            label_tr = _i18n.FIELD_NAME_I18N.get(str(label).strip().lower(), {}).get(lang, label)
        except Exception:
            label_tr = label
    except Exception:
        tpl = "{label} differs. Agentic AI value: {ai}. BNA Platform value: {bna}."
        na = "Not Available"
        label_tr = label
    bna = bna_value if bna_value else na
    ai_orig = ai_orig if ai_orig else ""
    ai_disp = f"{ai_orig}/{transformed}" if transformed and transformed != ai_orig else ai_orig
    return tpl.format(label=label_tr, ai=ai_disp, bna=bna)


def reco_missing(extra, lang="en"):
    try:
        import i18n as _i18n
        tpl = _i18n.RECO_MISSING_TEMPLATE.get(lang, _i18n.RECO_MISSING_TEMPLATE["en"])
    except Exception:
        tpl = "Missing information identified from Agentic AI output: {extra}"
    return tpl.format(extra=extra).strip()


def _val(bd):
    if bd is None: return ""
    if isinstance(bd, dict): return str(bd.get("value", "") or "")
    if isinstance(bd, list): return ", ".join(str(x) for x in bd)
    return str(bd)


# ---- Rules ----
def rule_project_name(ai, x, b, tie, lang):
    if _is_blank(ai): return "", _val(b), "Match", ""
    a = str(ai).strip(); bn = _val(b)
    if not bn: return a, "", "Differ", reco_text("Project Name", a, a, "")
    if _norm_name(a) == _norm_name(bn): return a, bn, "Match", ""
    return a, bn, "Differ", reco_text("Project Name", a, a, bn)


def _company_match(ai_norm, bna_norms):
    """Check whether the normalised AI company name matches any of the
    normalised BNA company names. Order of fallbacks:
      1. Exact equality after legal-suffix stripping.
      2. Substring containment (one fully inside the other) for names
         with at least 4 characters of meat — handles 'Equinox Gold'
         vs 'Equinox Gold Mining'.
      3. Token-set overlap of >= 60% with at least 2 shared tokens —
         handles minor word reorderings or extra branding tokens.
    """
    if not ai_norm: return False
    ai_tokens = set(t for t in ai_norm.split() if len(t) >= 2)
    for bn in bna_norms:
        if not bn: continue
        if ai_norm == bn: return True
        if len(ai_norm) >= 4 and (ai_norm in bn or bn in ai_norm):
            return True
        bn_tokens = set(t for t in bn.split() if len(t) >= 2)
        if len(ai_tokens) >= 2 and len(bn_tokens) >= 2:
            shared = ai_tokens & bn_tokens
            denom = min(len(ai_tokens), len(bn_tokens))
            if denom and len(shared) / denom >= 0.6 and len(shared) >= 2:
                return True
    return False


def _company_role(label, ai, b):
    """Many-to-many comparison.
    - AI value is comma-split into individual company names.
    - BNA value is a list of company names harvested chip-by-chip.
    - For every AI company, check whether ANY BNA company matches
      (using _company_match: norm-equal, substring, or token overlap).
    - AI items that match a BNA item are 'already in BNA' — ignore.
    - AI items WITHOUT a match are flagged as missing.
    - Field-level result: Match if every AI item has a match; otherwise
      Differ, with the missing AI items shown in the recommendation.
    """
    bna_names = b if isinstance(b, list) else _split_csv(_val(b))
    if _is_blank(ai): return "", ", ".join(bna_names), "Match", ""
    ai_names = _split_csv(ai)
    transformed_list = [_proper_case(n) for n in ai_names]
    transformed = ", ".join(transformed_list)
    bna_str = ", ".join(bna_names)
    if not bna_names:
        return transformed, "", "Differ", reco_text(label, str(ai), transformed, "")
    bna_norms = [_norm_name(b2) for b2 in bna_names]
    unmatched = [t for t in transformed_list
                 if not _company_match(_norm_name(t), bna_norms)]
    if not unmatched:
        return transformed, bna_str, "Match", ""
    return transformed, bna_str, "Differ", reco_text(label, str(ai), ", ".join(unmatched), bna_str)


def rule_owner(ai, x, b, tie, lang):         return _company_role("Owner", ai, b)
def rule_concession(ai, x, b, tie, lang):     return _company_role("Concessionaire/Operator", ai, b)
def rule_contractor(ai, x, b, tie, lang):     return _company_role("Contractor", ai, b)
def rule_engineering_co(ai, x, b, tie, lang): return _company_role("Engineering Company", ai, b)
def rule_equipment_co(ai, x, b, tie, lang):   return _company_role("Equipment / Technology Provider", ai, b)
def rule_consultancy_co(ai, x, b, tie, lang): return _company_role("Consultancy Company", ai, b)


def _canonical_stage_en(token, tie):
    """Resolve a project stage token (in any language) to its canonical
    English form. Tries TIE Stage Mapping first, then walks the Current
    Stage sheet (which has substage_en / substage_es / substage_pt
    columns), then the Project Stage Translations table. Falls back to
    the input."""
    if not token or tie is None: return token
    t = _strip_accents(str(token)).strip().lower()
    if not t: return token
    # 1) Stage Mapping (External Term -> BNA Stage)
    try:
        mapped = tie.lookup_mapping(tie.stage_mapping, token)
        if mapped: return mapped
    except Exception:
        pass
    # 2) Current Stage sheet (substage code + en/es/pt)
    try:
        for row in getattr(tie, "current_stages", []) or []:
            for fld in ("substage", "en", "es", "pt"):
                v = (row.get(fld) or "").strip()
                if v and _strip_accents(v).lower() == t:
                    return row.get("en") or v
    except Exception:
        pass
    # 3) Project Stage Translations (en -> {es, pt})
    try:
        table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
        for en_key, langs in table.items():
            if _strip_accents(en_key).lower() == t: return en_key
            es = (langs.get("es") or "")
            pt = (langs.get("pt") or "")
            if _strip_accents(es).lower() == t or _strip_accents(pt).lower() == t:
                return en_key
    except Exception:
        pass
    return token


def _display_stage(canonical_en, tie, lang):
    """Translate a canonical English stage to display language. Looks up
    Current Stage sheet first (more authoritative), then Project Stage
    Translations. Falls back to the canonical EN."""
    if not canonical_en or lang not in ("es", "pt") or tie is None:
        return canonical_en
    key = _strip_accents(str(canonical_en)).strip().lower()
    try:
        for row in getattr(tie, "current_stages", []) or []:
            en = (row.get("en") or "")
            if en and _strip_accents(en).lower() == key:
                v = (row.get(lang) or "").strip()
                if v: return v
    except Exception:
        pass
    try:
        table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
        entry = table.get(canonical_en.strip().lower())
        if entry:
            v = entry.get(lang)
            if v: return v
    except Exception:
        pass
    return canonical_en


def _is_known_stage(token, tie):
    """Returns True if the token (in any language) resolves to a known
    Stage Mapping / Current Stage / Project Stage Translations entry —
    i.e. it's a stage name in its own right (so comma-split would be wrong)."""
    if not token or tie is None: return False
    t = _strip_accents(str(token)).strip().lower()
    if not t: return False
    try:
        if tie.lookup_mapping(tie.stage_mapping, token): return True
    except Exception: pass
    try:
        for row in getattr(tie, "current_stages", []) or []:
            for fld in ("substage", "en", "es", "pt"):
                v = (row.get(fld) or "").strip()
                if v and _strip_accents(v).lower() == t: return True
    except Exception: pass
    try:
        table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
        for en_key, langs in table.items():
            if _strip_accents(en_key).lower() == t: return True
            es = (langs.get("es") or ""); pt = (langs.get("pt") or "")
            if _strip_accents(es).lower() == t or _strip_accents(pt).lower() == t:
                return True
    except Exception: pass
    return False


def _known_stage_labels(tie):
    """Return a list of (display_label, canonical_en) for every known
    stage in any language. Sorted longest-first so 'Design, Feasibility
    and Basic Engineering' matches before 'Design'."""
    out = []
    try:
        for row in getattr(tie, "current_stages", []) or []:
            canon_en = (row.get("en") or "").strip()
            if not canon_en: continue
            for fld in ("en", "es", "pt", "substage"):
                v = (row.get(fld) or "").strip()
                if v: out.append((v, canon_en))
    except Exception: pass
    try:
        table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
        for en_key, langs in table.items():
            out.append((en_key, en_key))
            for fld in ("es", "pt"):
                v = (langs.get(fld) or "").strip()
                if v: out.append((v, en_key))
    except Exception: pass
    try:
        for ext, bna in (getattr(tie, "stage_mapping", {}) or {}).items():
            if ext and bna: out.append((ext, bna))
    except Exception: pass
    # Dedupe preserving first occurrence, longest-first
    seen = set(); deduped = []
    for label, en in sorted(out, key=lambda x: -len(x[0])):
        k = _strip_accents(label).strip().lower()
        if not k or k in seen: continue
        seen.add(k); deduped.append((label, en))
    return deduped


def _scan_stages_in_string(s, tie):
    """Scan input string for known stage names (in any language). Returns
    a list of canonical EN stages in order of first occurrence. Handles
    the case where a stage name contains commas internally, e.g.
    'Design, Feasibility and Basic Engineering'."""
    if not s or not tie: return []
    haystack = _strip_accents(str(s)).lower()
    labels = _known_stage_labels(tie)
    found = []
    seen_positions = set()
    for label, canonical_en in labels:
        needle = _strip_accents(label).lower()
        if not needle: continue
        start = 0
        while True:
            idx = haystack.find(needle, start)
            if idx == -1: break
            # Must be on a word boundary (or punctuation)
            left_ok = idx == 0 or not haystack[idx-1].isalnum()
            end = idx + len(needle)
            right_ok = end == len(haystack) or not haystack[end].isalnum()
            if left_ok and right_ok:
                # Avoid double-counting overlapping matches
                overlap = any(a <= idx < b for a, b in seen_positions)
                if not overlap:
                    seen_positions.add((idx, end))
                    found.append((idx, canonical_en))
            start = idx + 1
    found.sort(key=lambda x: x[0])
    # Dedup canonical names while preserving order
    seen_canon = set(); out = []
    for _, c in found:
        kc = _strip_accents(c).lower()
        if kc in seen_canon: continue
        seen_canon.add(kc); out.append(c)
    return out


def _split_stages(s, tie):
    """Split a stage string into individual stages. Some BNA stages
    legitimately contain commas (e.g. 'Design, Feasibility and Basic
    Engineering'). Strategy: split first on semicolon / pipe / newline
    (these are unambiguous). Only fall back to comma-split when the
    whole string does NOT resolve to a known stage."""
    if not s: return []
    raw = str(s).strip()
    if not raw: return []
    # Pass 1: semicolon / pipe / newline split — never ambiguous
    parts = re.split(r"\s*[;|]\s*|\n+", raw)
    parts = [p.strip() for p in parts if p.strip()]
    # Pass 2: comma split each part only if the part is NOT a known stage
    out = []
    for p in parts:
        if "," in p and not _is_known_stage(p, tie):
            sub = [s2.strip() for s2 in p.split(",") if s2.strip()]
            # Only accept comma split if every sub-part is a known stage
            if sub and all(_is_known_stage(s2, tie) for s2 in sub):
                out.extend(sub)
            else:
                out.append(p)
        else:
            out.append(p)
    return out


def rule_project_stage(ai, x, b, tie, lang):
    """Project Stage comparison — multi-value + language-agnostic.
    Both AI and BNA values are split via _split_stages (which respects
    commas inside known canonical stage names). Each token is mapped
    to canonical English form so PT/ES/EN compare correctly.
    Match if every AI stage appears in BNA stages (set containment)."""
    bn_raw = _val(b)

    # Helper: translate the BNA value through the same canonical pipeline
    # the AI side uses so the output column reads in the target language.
    def _bna_display(raw):
        if not raw:
            return ""
        toks = _scan_stages_in_string(raw, tie)
        if not toks:
            items = _split_stages(raw, tie)
            toks = [_canonical_stage_en(t, tie) for t in items]
        if not toks:
            return raw
        return ", ".join([_display_stage(t, tie, lang) for t in toks])

    if _is_blank(ai):
        return "", _bna_display(bn_raw), "Match", ""
    a = str(ai).strip()
    # Try the scan-known-stages path first — it handles stage names that
    # legitimately contain commas (e.g. 'Design, Feasibility and Basic
    # Engineering'). Fall back to delimiter splitting if nothing matches.
    ai_canonical_en = _scan_stages_in_string(a, tie)
    if not ai_canonical_en:
        ai_items = _split_stages(a, tie)
        ai_canonical_en = [_canonical_stage_en(t, tie) for t in ai_items]
    transformed_items = [_display_stage(t, tie, lang) for t in ai_canonical_en]
    transformed = ", ".join(transformed_items)
    if not bn_raw:
        return transformed, "", "Differ", reco_text("Project Stage", a, transformed, "")
    bna_canonical_en = _scan_stages_in_string(bn_raw, tie)
    if not bna_canonical_en:
        bna_items = _split_stages(bn_raw, tie)
        bna_canonical_en = [_canonical_stage_en(t, tie) for t in bna_items]
    bn_display = ", ".join([_display_stage(t, tie, lang) for t in bna_canonical_en]) if bna_canonical_en else bn_raw
    # Set-based comparison (accent + case insensitive)
    def _key(s): return _strip_accents(str(s or "")).strip().lower()
    ai_set = {_key(t) for t in ai_canonical_en}
    bna_set = {_key(t) for t in bna_canonical_en}
    if ai_set and ai_set.issubset(bna_set):
        return transformed, bn_display, "Match", ""
    # Substring containment fallback
    if ai_set:
        raw_b = _key(bn_raw)
        haystack_parts = list(bna_set) + [raw_b]
        all_in = True
        for ai_tok in ai_set:
            if not ai_tok:
                continue
            hit = any(ai_tok and (ai_tok in h or h in ai_tok) for h in haystack_parts if h)
            if not hit:
                all_in = False
                break
        if all_in:
            return transformed, bn_display, "Match", ""
    # Last-ditch whole-string equality (case + accent insensitive)
    if _key(a) == _key(bn_raw):
        return transformed, bn_display, "Match", ""
    return transformed, bn_display, "Differ", reco_text("Project Stage", a, transformed, bn_display)


def rule_project_description(ai, x, b, tie, lang):
    a = "" if _is_blank(ai) else str(ai).strip()
    bn = _val(b)
    if not a: return "", bn, "Match", ""
    if not bn: return a, "", "Differ", reco_missing(a)
    if _meaningful_diff(a, bn):
        ai_sents = re.split(r"(?<=[\.\!\?])\s+", a)
        bna_low = bn.lower()
        new_bits = [s.strip() for s in ai_sents
                    if s.strip() and not all(tok in bna_low for tok in re.findall(r"[a-z]+", s.lower())[:3])]
        extra = " ".join(new_bits) or a
        return a, bn, "Differ", reco_missing(extra)
    return a, bn, "Match", ""


def _strip_paren(s):
    """Drop trailing parenthetical qualifiers like 'Public (PPP/PFI)' -> 'Public'."""
    if s is None: return ""
    return re.sub(r"\s*\([^)]*\)\s*", " ", str(s)).strip()


def rule_property_type(ai, x, b, tie, lang):
    if _is_blank(ai):
        # Even when AI is blank we still translate the BNA value so the
        # output column doesn't show English on an ES/PT report.
        return "", _translate_with_paren(_val(b), tie, lang, "property_type"), "Match", ""
    a = str(ai).strip()
    canonical_en = (tie.lookup_mapping(tie.ownership_type_mapping, a) or a) if tie else a
    transformed = _translate_with_paren(canonical_en, tie, lang, "property_type")
    bn = _val(b)
    bn_display = _translate_with_paren(bn, tie, lang, "property_type") if bn else ""
    if not bn:
        return transformed, "", "Differ", reco_text("Property Type", a, transformed, "")
    if transformed.strip().lower() == bn_display.strip().lower():
        return transformed, bn_display, "Match", ""
    # Tolerate parenthetical qualifiers on either side:
    # 'Public' ↔ 'Public (PPP/PFI)' should be a Match. Compare canonical EN.
    if _strip_paren(canonical_en).lower() == _strip_paren(bn).lower():
        return transformed, bn_display, "Match", ""
    return transformed, bn_display, "Differ", reco_text("Property Type", a, transformed, bn_display)


def rule_development_type(ai, x, b, tie, lang):
    if _is_blank(ai):
        return "", _translate_with_paren(_val(b), tie, lang, "development_type"), "Match", ""
    a = str(ai).strip()
    canonical_en = (tie.lookup_mapping(tie.development_type_mapping, a) or a) if tie else a
    transformed = _translate_with_paren(canonical_en, tie, lang, "development_type")
    bn = _val(b)
    bn_display = _translate_with_paren(bn, tie, lang, "development_type") if bn else ""
    if not bn:
        return transformed, "", "Differ", reco_text("Development Type", a, transformed, "")
    if transformed.strip().lower() == bn_display.strip().lower():
        return transformed, bn_display, "Match", ""
    if _strip_paren(canonical_en).lower() == _strip_paren(bn).lower():
        return transformed, bn_display, "Match", ""
    return transformed, bn_display, "Differ", reco_text("Development Type", a, transformed, bn_display)


def rule_capex(ai, ai_date, b, tie, lang, bna_fields=None):
    """Capex comparison per TIE Logics:
       1. Convert AI value to USD millions using FX rate at the source
          publication date (or BNA Last Expert Review if missing).
       2. Round, format per language, then compare to BNA value.
       3. If both are blank -> Match (no recommendation).
       4. If BNA is blank but AI has a value -> Differ + add to recommendation.
       5. If values differ numerically -> Differ + recommendation showing the
          transformed USD value.
    """
    import currency as _cur

    bn = _val(b)

    # Both blank -> nothing to compare
    if _is_blank(ai) and _is_blank(bn):
        return "", "", "Match", ""

    # AI blank, BNA has a value -> match (no AI claim to validate)
    if _is_blank(ai):
        return "", bn, "Match", ""

    # Parse AI Capex value (currency + amount + unit)
    parsed = _cur.parse_capex_value(ai)
    if parsed is None:
        return str(ai), bn, "Differ", reco_text("Capex", str(ai), "", bn)

    # FX dates: AI uses its OWN source date; BNA uses Last Expert Review.
    # Each side is converted at the rate that was current on its date.
    ai_fx_date = ai_date if ai_date else None
    bna_fx_date = None
    if bna_fields:
        for k, v in bna_fields.items():
            if str(k).strip().lower() == "last expert review":
                bna_fx_date = v; break
    # Last-resort fallback if a side has no own date
    if not ai_fx_date: ai_fx_date = bna_fx_date
    if not bna_fx_date: bna_fx_date = ai_fx_date

    usd_mn, rate, src = _cur.to_usd_millions(parsed, ai_fx_date, tie)
    if usd_mn is None:
        # Conversion failed — fall back to raw amount as USD
        usd_mn = parsed["raw_units"] / 1_000_000.0

    transformed = _cur.fmt_usd_millions(usd_mn, lang)

    # BNA missing -> recommend adding the AI value
    if not bn:
        return transformed, "", "Differ", reco_text("Capex", str(ai), transformed, "Not Available")

    # Convert BNA value to USD millions using the BNA review date.
    bna_parsed = _cur.parse_capex_value(bn)
    bna_usd_mn = None
    if bna_parsed:
        bna_usd_mn, _, _ = _cur.to_usd_millions(bna_parsed, bna_fx_date, tie)
        if bna_usd_mn is None and bna_parsed["currency"] == "USD":
            bna_usd_mn = bna_parsed["raw_units"] / 1_000_000.0
    bn_display = _cur.fmt_usd_millions(bna_usd_mn, lang) if bna_usd_mn is not None else bn

    # Compare numerically.
    bn_n = bna_usd_mn if bna_usd_mn is not None else parse_number(bn)
    if bn_n is not None:
        # Tolerate small rounding noise: 1 mn absolute OR 1% relative.
        diff = abs(bn_n - usd_mn)
        denom = max(1.0, abs(usd_mn), abs(bn_n))
        if diff < 1.0 or (diff / denom) < 0.01:
            return transformed, bn_display, "Match", ""
    return transformed, bn_display, "Differ", reco_text("Capex", str(ai), transformed, bn_display)


def rule_lifespan(ai, x, b, tie, lang):
    """Lifespan compare: extract the numeric value from each side, round to a
    whole number, and compare. Symbols like '+', '~', 'approx', 'around', and
    the unit word (years / year / años / año / anos / ano) are ignored. The
    unit word is compared case-insensitively. If both AI and BNA round to the
    same whole-number, return Match."""
    if _is_blank(ai) and _is_blank(b):
        return "", "", "Match", ""
    bn = _val(b)
    if _is_blank(ai):
        return "", bn, "Match", ""

    a = str(ai).strip()
    if not bn:
        # Format AI as 'N years' for the recommendation
        n = _lifespan_to_int(a)
        transformed = _fmt_lifespan(n, lang) if n is not None else a
        return transformed, "", "Differ", reco_text("Lifespan", a, transformed, "")

    a_int = _lifespan_to_int(a)
    b_int = _lifespan_to_int(bn)
    transformed = _fmt_lifespan(a_int, lang) if a_int is not None else a
    bn_display = _fmt_lifespan(b_int, lang) if b_int is not None else bn

    if a_int is not None and b_int is not None and a_int == b_int:
        return transformed, bn_display, "Match", ""
    return transformed, bn_display, "Differ", reco_text("Lifespan", a, transformed, bn_display)


def _lifespan_to_int(raw):
    """Extract the first numeric value from a lifespan string and round to
    whole years. Returns None if no number found.
    Strips '+', '~', 'approx', 'around', and trailing 'years/años/anos'."""
    if raw is None: return None
    s = str(raw).strip()
    if not s: return None
    # Drop common qualifying words (case-insensitive)
    s = re.sub(r"(?i)\b(?:approx(?:imately)?|around|about|over|more\s+than|m[áa]s\s+de|cerca\s+de)\b", " ", s)
    # Drop signs and ranges: '+', '~', '>', '>=', etc.
    s = re.sub(r"[+~>]", " ", s)
    # If a range like "25-30", take the first number
    m = re.search(r"-?\d+(?:[.,]\d+)?", s)
    if not m: return None
    raw_num = m.group(0).replace(",", ".")
    try:
        n = float(raw_num)
    except ValueError:
        return None
    return int(round(n))


def _fmt_lifespan(n, lang):
    if n is None: return ""
    word = {"es": "años", "pt": "anos", "en": "years"}.get(lang, "years")
    # Singular form for 1
    if n == 1:
        word = {"es": "año", "pt": "ano", "en": "year"}.get(lang, "year")
    return f"{n} {word}"


def _strip_hierarchy(token):
    """AI sometimes emits 'Sector > Type | Sector > Type'. Keep only the
    leaf token after the last '>' so the TIE mapping matches the type
    label, not the hierarchical path."""
    s = str(token or "").strip()
    if ">" in s:
        s = s.rsplit(">", 1)[-1].strip()
    return s


def _norm_pt_key(s):
    """Normalise a Project Type key for translation lookup. Lower-case,
    collapse whitespace, AND treat ' - ' / ' / ' / '-' / '/' as the same
    separator so 'Road paving - rehabilitation' matches the TIE entry
    'Road paving / rehabilitation'."""
    if s is None: return ""
    out = re.sub(r"\s+", " ", str(s)).strip().lower()
    # Unify separator: turn '-' or '/' (with surrounding spaces) into ' / '
    out = re.sub(r"\s*[-/]\s*", " / ", out)
    return out


def _translate_via_tie(canonical_en, tie, lang, field_key):
    """Generic translator: look up canonical-EN value in
    tie.bna_translations[field_key] and return the lang version
    (es/pt). Falls back to the original canonical-EN if no entry,
    or if the input is already in the target language."""
    if not canonical_en or lang not in ("es", "pt") or tie is None:
        return canonical_en
    try:
        table = (getattr(tie, "bna_translations", {}) or {}).get(field_key, {})
        if not table:
            return canonical_en
        key = str(canonical_en).strip().lower()
        entry = table.get(key)
        if not entry:
            # Reverse lookup: input might already be in es/pt
            for en_key, langs in table.items():
                if (langs.get("es") or "").lower() == key or (langs.get("pt") or "").lower() == key:
                    entry = langs
                    break
        if entry:
            tr = entry.get(lang)
            if tr: return tr
    except Exception:
        pass
    return canonical_en


def _translate_pt_via_tie(canonical_en, tie, lang):
    """Backward-compat wrapper — Project Type translation."""
    return _translate_via_tie(canonical_en, tie, lang, "project_type")


def _translate_with_paren(raw, tie, lang, field_key):
    """Translate a value that may carry a parenthetical qualifier:
    'Public (PPP/PFI)' translates the head, preserves the parens."""
    if not raw:
        return raw
    s = str(raw).strip()
    m = re.match(r"^(.*?)\s*(\([^)]*\))\s*$", s)
    if m:
        head, paren = m.group(1).strip(), m.group(2)
        return f"{_translate_via_tie(head, tie, lang, field_key)} {paren}"
    return _translate_via_tie(s, tie, lang, field_key)


def rule_project_type(ai, x, b, tie, lang):
    """Many-to-many Project Type comparison.
    AI value is split on comma/semicolon/pipe into individual project types.
    Each token's hierarchical prefix ('Sector > ') is stripped, then mapped
    to canonical English via TIE 'Project Type' sheet, then translated to
    the selected display language via 'Project Type Translations'.

    Matching always uses the canonical English form so a PT/ES display
    language doesn't break comparison against the BNA value (also normalized).
    """
    if _is_blank(ai): return "", _val(b), "Match", ""
    # Always split on , ; | regardless of which is present
    items = _split_csv(ai) if any(c in str(ai) for c in ",;|") else [str(ai)]
    # Strip 'Sector > ' prefix per token
    leaf_items = [_strip_hierarchy(t) for t in items]
    # Map each leaf to canonical English (TIE Project Type sheet)
    canonical_en_items = [(tie.lookup_mapping(tie.project_type_mapping, t) or t) if tie else t
                          for t in leaf_items]
    # Translate each canonical to display language
    transformed_items = [_translate_pt_via_tie(t, tie, lang) for t in canonical_en_items]
    transformed = ", ".join(transformed_items)
    bn = _val(b)
    if not bn:
        return transformed, "", "Differ", reco_text("Project Type", str(ai), transformed, "")
    bna_items = _split_csv(bn)
    # Normalize each BNA item: strip hierarchy, reverse-translate ES/PT
    # back to canonical English so the comparison is language-agnostic.
    bna_canonical_en = []
    for bx in bna_items:
        leaf = _strip_hierarchy(bx)
        # Use the existing project_type_mapping; if not mapped, the value
        # itself may already be canonical. We do an explicit reverse lookup
        # below in case the input is an ES/PT cell.
        canonical = leaf
        try:
            table = (getattr(tie, "bna_translations", {}) or {}).get("project_type", {})
            key = leaf.strip().lower()
            if key not in table:
                for en_key, langs in table.items():
                    if (langs.get("es") or "").lower() == key or (langs.get("pt") or "").lower() == key:
                        canonical = en_key
                        break
        except Exception:
            pass
        # Also try TIE Project Type external-term mapping
        mapped = tie.lookup_mapping(tie.project_type_mapping, canonical) if tie else None
        bna_canonical_en.append(mapped or canonical)

    def _depluralise(tok):
        # crude EN singularisation — drop trailing 's' / 'es' on tokens
        # >=4 chars so "Runways" matches "Runway", "Terminals" matches
        # "Terminal", "Concessions" matches "Concession".
        if len(tok) >= 4 and tok.endswith("es") and tok[-3] not in "aeiou":
            return tok[:-2]
        if len(tok) >= 4 and tok.endswith("s"):
            return tok[:-1]
        return tok

    def _norm_pt(s):
        # lowercase, strip leading 'Main ', collapse whitespace, drop trailing
        # punctuation. Plural-insensitive token form for comparison.
        s = re.sub(r"^\s*main\s+", "", str(s or "").strip(), flags=re.IGNORECASE)
        s = _strip_accents(s) if "_strip_accents" in globals() else s
        s = re.sub(r"\s+", " ", s).strip().lower()
        # Tokenise and depluralise each token, then rejoin
        toks = [_depluralise(t) for t in s.split() if t]
        return " ".join(toks)

    # Compare on canonical-English forms so display language doesn't break match
    bna_norm = [_norm_pt(bx) for bx in bna_canonical_en]

    def _matches_any(ai_item):
        a = _norm_pt(ai_item)
        if not a: return True  # blank AI item — nothing to validate
        for bn_n in bna_norm:
            if not bn_n: continue
            if a == bn_n: return True
            if len(a) >= 4 and (a in bn_n or bn_n in a):
                return True
            # Token overlap — already plural-insensitive (see _norm_pt)
            atok = set(t for t in a.split() if len(t) >= 2)
            btok = set(t for t in bn_n.split() if len(t) >= 2)
            if len(atok) >= 1 and len(btok) >= 1:
                shared = atok & btok
                denom = min(len(atok), len(btok))
                # 0.5 ratio is enough — "passenger terminal" (2) vs
                # "airport passenger terminal" (3) shares 2/2 after
                # depluralisation, so this Matches.
                if denom and len(shared) / denom >= 0.5 and len(shared) >= 1:
                    return True
        return False

    # Translate BNA tokens to the target display language so the
    # output sheet shows them in ES/PT alongside the AI transformed value.
    bna_display_items = [_translate_pt_via_tie(t, tie, lang) for t in bna_canonical_en]
    bna_display = ", ".join(bna_display_items) if bna_display_items else bn
    unmatched_en = [t for t in canonical_en_items if not _matches_any(t)]
    if not unmatched_en:
        return transformed, bna_display, "Match", ""
    unmatched_display = [_translate_pt_via_tie(t, tie, lang) for t in unmatched_en]
    return transformed, bna_display, "Differ", reco_text("Project Type", str(ai), ", ".join(unmatched_display), bna_display)


def rule_milestones(ai, x, b, tie, lang):
    if _is_blank(ai): return "", _val(b), "Match", ""
    a = str(ai).strip(); bn = _val(b)
    items = [s.strip() for s in re.split(r"\n|;", bn) if s.strip()]
    latest = items[-1] if items else ""
    if not latest: return a, "", "Differ", reco_missing(a)
    if _meaningful_diff(a, latest): return a, latest, "Differ", reco_missing(a)
    return a, latest, "Match", ""


def _year_only(raw):
    """Return int(year) if the input looks like a bare year (e.g. '2024',
    'Year 2024', '2024.0'); otherwise None. Months/days disqualify it."""
    if raw is None: return None
    s = str(raw).strip()
    if not s: return None
    # Strip trailing .0 from Excel-numeric years
    s = re.sub(r"\.0+$", "", s)
    # If any month name (en/es/pt, full or short) appears -> not year-only
    low = s.lower()
    for token in re.findall(r"[a-zà-ÿ]+", low):
        if token in ALL_MONTH_LOOKUP: return None
    digits = re.findall(r"\d+", s)
    if not digits: return None
    # Year-only inputs have exactly one number, 4 digits long, in plausible range
    if len(digits) == 1 and len(digits[0]) == 4:
        y = int(digits[0])
        if 1900 <= y <= 2100: return y
    return None


def _bna_year(raw):
    """Pull the year from a BNA date string. Returns int or None."""
    dt = parse_date(raw)
    if dt: return dt.year
    if raw is None: return None
    m = re.search(r"\b(19|20)\d{2}\b", str(raw))
    return int(m.group(0)) if m else None


def rule_schedule_date(label):
    """Compare AI date and BNA date by Month+Year only (ignore day).
    Both AI and BNA values are reformatted with `fmt_month_year(..., lang)`
    so the output columns read in the researcher's chosen language."""
    def _r(ai, x, b, tie, lang):
        bn = _val(b)
        bn_dt = parse_date(bn) if bn else None
        bn_display = fmt_month_year(bn_dt, lang) if bn_dt else (bn or "")

        if _is_blank(ai):
            return "", bn_display, "Match", ""
        dt = parse_date(ai)
        ai_year_only = _year_only(ai)
        if dt:
            transformed = fmt_month_year(dt, lang)
        elif ai_year_only:
            transformed = str(ai_year_only)
        else:
            transformed = str(ai).strip()
        if _is_blank(bn):
            return transformed, "", "Differ", reco_text(label, str(ai), transformed, "")
        # Year-only AI: match if year aligns with BNA's year
        if ai_year_only:
            bna_y = _bna_year(bn)
            if bna_y and bna_y == ai_year_only:
                return transformed, bn_display, "Match", ""
        # Month+Year comparison
        if dt and bn_dt and dt.year == bn_dt.year and dt.month == bn_dt.month:
            return transformed, bn_display, "Match", ""
        # If both parse to the same Month-Year string in any of the languages, also Match
        if dt and bn_dt:
            for L in ("en", "es", "pt"):
                if fmt_month_year(dt, L).lower() == fmt_month_year(bn_dt, L).lower():
                    return transformed, bn_display, "Match", ""
        # String fallback
        if transformed.strip().lower() == bn.strip().lower():
            return transformed, bn_display, "Match", ""
        return transformed, bn_display, "Differ", reco_text(label, str(ai), transformed, bn_display)
    return _r


def rule_pass_through(label):
    def _r(ai, x, b, tie, lang):
        if _is_blank(ai):
            return "", "", "Match", ""
        a = str(ai).strip()
        # 'Not in BNA' translated to selected language for the BNA cell
        not_in_bna = {"en": "Not in BNA", "es": "No está en BNA", "pt": "Não está em BNA"}.get(lang, "Not in BNA")
        return a, not_in_bna, "Differ", reco_text(label, a, a, not_in_bna, lang=lang)
    return _r


def rule_latlon(ai, x, b, tie, lang):
    if _is_blank(ai): return "", _val(b), "Match", ""
    p = parse_latlon(ai)
    transformed = f"{p[0]}, {p[1]}" if p else str(ai)
    bn = _val(b); bp = parse_latlon(bn) if bn else None
    if not bp: return transformed, "", "Differ", reco_text("Latitude and Longitude", str(ai), transformed, "")
    if p and abs(p[0]-bp[0]) < 0.001 and abs(p[1]-bp[1]) < 0.001:
        return transformed, bn, "Match", ""
    return transformed, bn, "Differ", reco_text("Latitude and Longitude", str(ai), transformed, bn)


def rule_main_works(ai, x, b, tie, lang):
    return rule_project_description(ai, x, b, tie, lang)


def rule_documentation(ai, x, b, tie, lang):
    if _is_blank(ai): return "", "", "Match", ""
    a = str(ai).strip()
    return a, "Informational only", "Differ", f"Project Documentation (informational): {a}"


def _strip_contact_decoration(s):
    """Strip trailing parentheticals from a person name:
      - email:    'Jane Doe (jane@x.com)'           -> 'Jane Doe'
      - phone:    'John (+51 9 1234 5678)'           -> 'John'
      - role:     'Ana (Manager, Procurement)'       -> 'Ana'
    Only strips trailing '(...)' segments. Keeps inline parens that
    don't sit at the end (rare for person names)."""
    if not s: return s
    out = re.sub(r"\s*\([^()]*\)\s*$", "", str(s)).strip()
    # Repeat once in case there are two trailing parentheticals
    out = re.sub(r"\s*\([^()]*\)\s*$", "", out).strip()
    return out or str(s).strip()


def _contact_role(label):
    def _r(ai, x, b, tie, lang):
        if _is_blank(ai): return "", _val(b), "Match", ""
        a_raw = str(ai).strip()
        # Strip trailing email/phone parenthetical from AI value before
        # comparison and display, e.g. 'GIAN CARLO SILVA ANCCO
        # (gsilva@proinversion.gob.pe)' -> 'GIAN CARLO SILVA ANCCO'.
        a = _strip_contact_decoration(a_raw)
        bna_names = b if isinstance(b, list) else _split_csv(_val(b))
        bna_names = [_strip_contact_decoration(n) for n in bna_names if n]
        if not bna_names: return a, "", "Differ", reco_text(label, a, a, "")
        a_n = _norm_name(a)
        if any(_norm_name(bb) == a_n for bb in bna_names):
            return a, ", ".join(bna_names), "Match", ""
        return a, ", ".join(bna_names), "Differ", reco_text(label, a, a, ", ".join(bna_names))
    return _r


def _strip_plural(s):
    """Drop trailing 's' from each token so 'megawatts' compares equal to
    'megawatt', 'tonnes' to 'tonne', etc. Keeps tokens shorter than 4 chars
    untouched (avoid stripping 't', 'kw', 'mw')."""
    if not s: return s
    out = []
    for tok in str(s).split():
        if len(tok) >= 4 and tok.endswith("s"):
            out.append(tok[:-1])
        else:
            out.append(tok)
    return " ".join(out)


def _capacity_canonical_unit(text, tie):
    """Look up the canonical UNIT for a capacity unit phrase using the
    editable 'Capacity Units' sheet. Returns the canonical short form
    (e.g. 'b/d') or the lowercased input if no alias exists.

    Consults 'Capacity Unit Translations' so an ES/PT phrase
    (e.g. 'quilômetros', 'kilómetros') reverse-maps to the English
    phrase first, then resolves via the alias table.

    Also tries a plural-insensitive fallback ('megawatts' → 'megawatt')
    so BNA's plural form matches the singular alias in the TIE sheet."""
    if not text: return ""
    aliases = getattr(tie, "capacity_unit_aliases", None) or {}
    key = re.sub(r"\s+", " ", str(text)).strip().lower()
    if key in aliases:
        return aliases[key]
    cleaned = re.sub(r"\s*\([^)]+\)\s*$", "", key).strip()
    if cleaned in aliases:
        return aliases[cleaned]
    # Plural → singular fallback
    sing_key = _strip_plural(key)
    if sing_key != key and sing_key in aliases:
        return aliases[sing_key]
    sing_cleaned = _strip_plural(cleaned)
    if sing_cleaned != cleaned and sing_cleaned in aliases:
        return aliases[sing_cleaned]
    # ES/PT reverse-lookup via Capacity Unit Translations
    trans = getattr(tie, "capacity_unit_translations", None) or {}
    for en_key, langs in trans.items():
        es = (langs.get("es") or "").strip().lower()
        pt = (langs.get("pt") or "").strip().lower()
        if key == es or key == pt or cleaned == es or cleaned == pt:
            if en_key in aliases:
                return aliases[en_key]
            return en_key
        # Plural-insensitive translation lookup
        if sing_key == _strip_plural(es) or sing_key == _strip_plural(pt):
            if en_key in aliases: return aliases[en_key]
            return en_key
    return cleaned or key


_CAPACITY_HEDGES = re.compile(
    r"\b(?:estimated|estimate|estimated:|estimate:|potential|potentially|"
    r"approximately|approx\.?|approxim|about|around|up\s*to|target(?:ed)?|"
    r"estimado|estimada|aproximadamente|hasta|cerca\s+de|"
    r"estimada?|aproximadamente|at[ée]\s+|cerca\s+de)\b\s*:?",
    re.IGNORECASE)


def _strip_capacity_hedges(s):
    """Drop leading hedging words like 'Potential', 'Estimated', 'Approximately'
    from a capacity expression. Leaves the number+unit intact."""
    if not s: return s
    out = _CAPACITY_HEDGES.sub("", str(s)).strip(" ,;:-")
    out = re.sub(r"\s+", " ", out)
    return out


def _trim_capacity_unit(unit_text):
    """Drop trailing 'of <product>' / 'de <product>' phrases from a unit
    string so 't/y of lithium carbonate' compares equal to 't/y'."""
    if not unit_text: return unit_text
    out = re.split(r"\s+(?:of|de|do|da|dos|das)\s+", str(unit_text), maxsplit=1,
                   flags=re.IGNORECASE)[0]
    return out.strip(" ,;:-")


def _parse_capacity_item(item, tie):
    """Parse one capacity expression (e.g. '750 megawatt hour',
    '4,800 t/y', 'Copper 1,000 tonnes per year', 'Potential 15,600 t/y
    of lithium carbonate') into (number, canonical unit).
    Returns (None, '') if no number is present.

    Hedging words ('Potential', 'Estimated', 'Approximately', etc.) and
    trailing 'of <product>' tails are stripped before parsing so AI and
    BNA expressions match on number + canonical unit regardless of how
    they phrased the value."""
    if item is None: return None, ""
    s = _strip_capacity_hedges(str(item).strip())
    if not s: return None, ""
    m = re.search(r"-?\d[\d.,\s]*", s)
    if not m: return None, ""
    num_raw = m.group(0).strip()
    num = parse_number(num_raw)
    if num is None: return None, ""
    after = s[m.end():].strip(" ,;:-")
    before = s[:m.start()].strip(" ,;:-")
    mult, after = _extract_multiplier(after)
    if mult == 1 and before:
        mult, before = _extract_multiplier(before)
    num = num * mult
    raw_unit = (after or before).strip(" ,;:-")
    # Try canonical lookup with the FULL unit text first (handles
    # 'number of passengers per year' which contains 'of' but is itself
    # a known canonical alias). Only fall back to 'of/de' splitting when
    # the full phrase doesn't resolve.
    canonical = _capacity_canonical_unit(raw_unit, tie)
    if canonical == raw_unit.strip().lower() or not canonical:
        unit_text = _trim_capacity_unit(raw_unit)
        canonical = _capacity_canonical_unit(unit_text, tie)
    return num, canonical


def _translate_capacity_unit(unit_en, tie, lang):
    """Translate a canonical EN capacity unit name to lang (es/pt) using
    tie.capacity_unit_translations. Returns the original unit on miss."""
    if not unit_en or lang not in ("es", "pt") or tie is None:
        return unit_en
    try:
        trans = getattr(tie, "capacity_unit_translations", None) or {}
        key = str(unit_en).strip().lower()
        entry = trans.get(key)
        if entry:
            tr = entry.get(lang)
            if tr: return tr
    except Exception:
        pass
    return unit_en


def _format_capacity_item(item, tie, lang):
    """Re-render a single capacity item with the lang-translated unit
    while preserving the original number. Falls back to original text
    when parsing fails."""
    if not item:
        return ""
    raw = str(item).strip()
    num, canonical = _parse_capacity_item(raw, tie)
    if num is None or not canonical:
        return raw
    unit_disp = _translate_capacity_unit(canonical, tie, lang) if lang in ("es", "pt") else canonical
    # Render whole numbers without a trailing .0
    if abs(num - round(num)) < 1e-9:
        num_str = f"{int(round(num)):,}"
    else:
        num_str = f"{num:,.2f}"
    return f"{num_str} {unit_disp}".strip()


def _format_capacity_list(raw, tie, lang):
    if not raw:
        return ""
    items = _split_csv(raw) if any(c in str(raw) for c in ",;\n") else [str(raw)]
    parts = [_format_capacity_item(it, tie, lang) for it in items if str(it).strip()]
    parts = [p for p in parts if p]
    return ", ".join(parts) if parts else str(raw).strip()


def rule_capacity(ai, x, b, tie, lang):
    """Capacity comparison.

    Both sides are split into items (comma / semicolon / newline). Each
    item is parsed as (number, canonical_unit) using the 'Capacity Units'
    TIE sheet. Many-to-many comparison: if any AI item matches any BNA
    item (number within 0.1% AND canonical unit equal), the row is a
    Match. Transformed AI value and BNA value are re-rendered with the
    target-language unit names so the output reads cleanly in ES/PT.
    """
    bn = _val(b)
    bn_display = _format_capacity_list(bn, tie, lang) if bn else ""

    if _is_blank(ai):
        return "", bn_display, "Match", ""
    raw_ai = str(ai).strip()
    transformed = _format_capacity_list(raw_ai, tie, lang) or raw_ai

    ai_items = _split_csv(ai) if any(c in str(ai) for c in ",;\n") else [str(ai)]
    bn_items = _split_csv(bn) if any(c in str(bn) for c in ",;\n") else ([bn] if bn else [])

    ai_pairs = [_parse_capacity_item(it, tie) for it in ai_items]
    ai_pairs = [p for p in ai_pairs if p[0] is not None]
    bn_pairs = [_parse_capacity_item(it, tie) for it in bn_items]
    bn_pairs = [p for p in bn_pairs if p[0] is not None]

    if not bn_pairs:
        return transformed, "", "Differ", reco_text("Capacity", str(ai), transformed, "")

    def _match(a_num, a_unit, b_num, b_unit):
        if a_num is None or b_num is None: return False
        denom = max(1.0, abs(a_num), abs(b_num))
        if abs(a_num - b_num) / denom > 0.001: return False
        if not a_unit or not b_unit: return True
        return a_unit == b_unit

    if not ai_pairs:
        return transformed, bn_display, "Differ", reco_text("Capacity", str(ai), transformed, bn_display)
    all_matched = all(
        any(_match(an, au, bnum, bu) for bnum, bu in bn_pairs)
        for an, au in ai_pairs
    )
    if all_matched:
        return transformed, bn_display, "Match", ""
    return transformed, bn_display, "Differ", reco_text("Capacity", str(ai), transformed, bn_display)


RULES = {
    "project name": rule_project_name,
    "owner company": rule_owner,
    "concessionaire / operator company": rule_concession,
    "contractor company": rule_contractor,
    "engineering company": rule_engineering_co,
    "equipment / technology provider": rule_equipment_co,
    "consultancy company": rule_consultancy_co,
    "project stage": rule_project_stage,
    "project description": rule_project_description,
    "description": rule_project_description,
    "descripción": rule_project_description,
    "descripción del proyecto": rule_project_description,
    "descrição": rule_project_description,
    "descrição do projeto": rule_project_description,
    "property type": rule_property_type,
    "development type": rule_development_type,
    "capex": rule_capex,
    "lifespan": rule_lifespan,
    "project type": rule_project_type,
    "milestones": rule_milestones,
    "announcement date": rule_schedule_date("Announcement Date"),
    "completion_end of construction date": rule_schedule_date("Completion / End of Construction Date"),
    "construction start date": rule_schedule_date("Construction Start Date"),
    "contractor tendering start date": rule_schedule_date("Contractor Tendering Start Date"),
    "detailed engineering start date": rule_schedule_date("Detailed Engineering Start Date"),
    "environmental approval date": rule_schedule_date("Environmental Approval Date"),
    "environmental approval": rule_schedule_date("Environmental Approval Date"),
    "environmental and social approval": rule_schedule_date("Environmental Approval Date"),
    "environmental and social approval date": rule_schedule_date("Environmental Approval Date"),
    "tendering start date": rule_schedule_date("Tendering Start Date"),
    # All Month+Year date fields use rule_schedule_date so AI value and BNA
    # value match when (year, month) align — irrespective of language
    # (DICIEMBRE 2030 == Dezembro 2030 == December 2030) and irrespective
    # of "Estimated:" / "Confirmado:" prefixes.
    "operations start date": rule_schedule_date("Operations Start Date"),
    "start of operation date": rule_schedule_date("Operations Start Date"),
    "end of operation date": rule_schedule_date("End of Operation Date"),
    "environmental impact assessment submission_presentation date": rule_schedule_date("EIA Submission/Presentation Date"),
    "feasibility studies start date": rule_schedule_date("Feasibility Studies Start Date"),
    "pre-feasibility studies start date": rule_schedule_date("Pre-feasibility Studies Start Date"),
    "latitude and longitude": rule_latlon,
    "main works description": rule_main_works,
    "project manager": _contact_role("Project Manager"),
    "purchasing manager": _contact_role("Purchasing Manager"),
    "engineering manager": _contact_role("Engineering Manager"),
    "capacity": rule_capacity,
    "products required": rule_pass_through("Products required"),
    "services required": rule_pass_through("Services required"),
}


def _key(s):
    return re.sub(r"\s+", " ", str(s or "").strip().lower())


def _bna_last_expert_review(bna_fields):
    if not bna_fields: return None
    for k, v in bna_fields.items():
        if str(k).strip().lower() == "last expert review":
            return v
    return None


def _maybe_downgrade_to_stale(verdict, ai_extra, bna_fields):
    if verdict != "Differ": return verdict
    if _is_blank(ai_extra): return verdict
    bna_review = _bna_last_expert_review(bna_fields)
    if _is_blank(bna_review): return verdict
    ai_dt = parse_date(ai_extra)
    bna_dt = parse_date(bna_review)
    if ai_dt is None or bna_dt is None: return verdict
    if ai_dt <= bna_dt:
        return "Stale AI"
    return verdict


def apply_rule(field_name, ai_value, ai_extra, bna_data, tie, lang, bna_fields=None):
    key = _key(field_name)
    if _is_blank(ai_value):
        bn_disp = _val(bna_data)
        if not bn_disp or _is_blank(bn_disp):
            return "", "", "Missing on Both", ""
        return "", bn_disp, "Missing on AI", ""
    fn = RULES.get(key)
    if fn is None:
        ai = "" if _is_blank(ai_value) else str(ai_value).strip()
        bn = _val(bna_data)
        if not ai and not bn: return "", "", "Match", ""
        if not bn:
            verdict = _maybe_downgrade_to_stale("Differ", ai_extra, bna_fields)
            return ai, "", verdict, reco_text(str(field_name), ai, ai, "", lang=lang)
        if ai.strip().lower() == bn.strip().lower():
            return ai, bn, "Match", ""
        verdict = _maybe_downgrade_to_stale("Differ", ai_extra, bna_fields)
        return ai, bn, verdict, reco_text(str(field_name), ai, ai, bn, lang=lang)
    transformed, bna_value, match, reco = fn(ai_value, ai_extra, bna_data, tie, lang)
    new_match = _maybe_downgrade_to_stale(match, ai_extra, bna_fields)
    return transformed, bna_value, new_match, reco