File size: 118,650 Bytes
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffaa98
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
0ffaa98
 
 
89fcaa4
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
89fcaa4
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffaa98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffaa98
 
 
 
 
 
 
27c9320
0ffaa98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef822cd
 
 
 
 
 
 
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
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
"""BNA Scraper (Playwright) — robust login + tab-by-tab structured extraction."""
from __future__ import annotations
import html as _stdhtml
import os
import re
import shutil
import tempfile
import time
import unicodedata as _ud
from typing import Callable, Dict, List, Optional, Any


def _strip_accents_local(s):
    """Drop diacritics for case + accent insensitive company dedupe."""
    if not s: return ""
    nfkd = _ud.normalize("NFKD", str(s))
    return "".join(ch for ch in nfkd if not _ud.combining(ch))
try:
    from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout
except Exception:
    sync_playwright = None
    PWTimeout = Exception


EMAIL_SELECTORS = ["input[type='email']", "input[name='email']", "input[name='username']",
                   "input[id*='email' i]", "input[id*='user' i]",
                   "input[placeholder*='email' i]", "input[placeholder*='correo' i]"]
PASSWORD_SELECTORS = ["input[type='password']", "input[name='password']",
                      "input[id*='password' i]", "input[placeholder*='password' i]",
                      "input[placeholder*='contraseña' i]"]
SUBMIT_SELECTORS = ["button[type='submit']", "input[type='submit']",
                    "button:has-text('Log in')", "button:has-text('Login')",
                    "button:has-text('Sign in')", "button:has-text('Iniciar')",
                    "button:has-text('Ingresar')", "button:has-text('Entrar')"]
LOGGED_IN_MARKERS = ["a:has-text('Log out')", "a:has-text('Logout')",
                     "a:has-text('Cerrar sesión')", "[class*='user-menu']"]
ENTRY_URLS = ["https://app.bnamericas.com/", "https://app.bnamericas.com/home"]


def _ensure_tab(url, tab):
    if "?" in url:
        base = re.sub(r"([&?])tab=[^&]*", "", url).rstrip("?&")
        sep = "&" if "?" in base else "?"
        return f"{base}{sep}tab={tab}"
    return f"{url}?tab={tab}"


class BNAScraper:
    def __init__(self, log=print, headless=True, manual_login=False,
                 manual_wait_secs=180, debug_dir=None, company_chips=None,
                 bna_lang="en"):
        self.log = log
        self.headless = headless
        self.manual_login = manual_login
        self.manual_wait_secs = manual_wait_secs
        self.debug_dir = debug_dir
        # Target BNA UI language (matches user-selected output language).
        # Aligned in load_project() right after the project page renders.
        self.bna_lang = (bna_lang or "en").lower()
        # Company chip labels to harvest under the Companies radio. List of
        # exact chip labels as they appear on BNA's Companies & Contacts tab.
        # Driven by the TIE 'Company Chip Mapping' sheet — gui.py builds this
        # list from there. Falls back to the default 6 if not supplied.
        self.company_chips = list(company_chips) if company_chips else [
            "Owner", "Concessionaire/operator", "Construction and Management",
            "Engineering", "Provider", "Consultancy",
        ]
        self._pw = None
        self._browser = None
        self._context = None
        self._page = None
        self._temp_dir = None
        self._project_url = ""

    def __enter__(self):
        if sync_playwright is None:
            raise RuntimeError("Playwright not installed.")
        self._pw = sync_playwright().start()
        self._temp_dir = tempfile.mkdtemp(prefix="bna_sess_")
        # Stealth launch flags — BNamericas' Cloudflare layer silently
        # rejects browsers that look automated (the navigator.webdriver
        # flag is the giveaway). These flags + the init script below mask
        # the most common tells without affecting normal behaviour.
        self._browser = self._pw.chromium.launch(
            headless=self.headless,
            args=[
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox",
                "--disable-dev-shm-usage",
            ],
        )
        # Map the user's Output Language selection to a browser locale so
        # BNA's Accept-Language-based content negotiation serves the
        # right variant. en-US for English, es-ES for Spanish, pt-BR for
        # Portuguese (most BNA Portuguese content is Brazilian-targeted).
        _locale_map = {"en": "en-US", "es": "es-ES", "pt": "pt-BR"}
        _ctx_locale = _locale_map.get(self.bna_lang, "en-US")
        _accept_lang = {
            "en-US": "en-US,en;q=0.9",
            "es-ES": "es-ES,es;q=0.9,en;q=0.5",
            "pt-BR": "pt-BR,pt;q=0.9,en;q=0.5",
        }[_ctx_locale]
        self._context = self._browser.new_context(
            ignore_https_errors=False, java_script_enabled=True,
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            viewport={"width": 1440, "height": 900},
            locale=_ctx_locale,
            extra_http_headers={"Accept-Language": _accept_lang})
        # Mask the most common headless / Playwright tells before any
        # page script reads them. Each line below targets a single check
        # that BNAmericas' Cloudflare layer is known to look at:
        #   - navigator.webdriver        (the "I'm automated" flag)
        #   - window.chrome              (missing in headless Chromium)
        #   - navigator.plugins / .mimeTypes (empty in headless)
        #   - navigator.languages        (must match Accept-Language)
        #   - Permissions.query notifications  (returns "denied" in headless,
        #                                       real Chrome returns "default")
        _langs_for_locale = {
            "en-US": "['en-US','en']",
            "es-ES": "['es-ES','es','en']",
            "pt-BR": "['pt-BR','pt','en']",
        }.get(_ctx_locale, "['en-US','en']")
        try:
            self._context.add_init_script(
                "Object.defineProperty(navigator,'webdriver',{get:()=>undefined});"
                "window.chrome=window.chrome||{runtime:{},loadTimes:()=>({}),csi:()=>({})};"
                "Object.defineProperty(navigator,'plugins',{get:()=>[1,2,3,4,5]});"
                "Object.defineProperty(navigator,'mimeTypes',{get:()=>[1,2]});"
                f"Object.defineProperty(navigator,'languages',{{get:()=>{_langs_for_locale}}});"
                "const _origQ=window.navigator.permissions&&window.navigator.permissions.query;"
                "if(_origQ){window.navigator.permissions.query=(p)=>"
                "  p&&p.name==='notifications'"
                "    ?Promise.resolve({state:Notification.permission})"
                "    :_origQ.call(window.navigator.permissions,p);}"
            )
        except Exception:
            pass
        self._page = self._context.new_page()
        self._page.set_default_timeout(30000)
        # Network listener: stash every JSON response — BNA's frontend fetches
        # project data (incl. lat/lon) via XHR. We mine those payloads later.
        self._json_blobs = []
        def _on_response(resp):
            try:
                ct = (resp.headers or {}).get("content-type", "")
                if "json" not in ct.lower(): return
                u = resp.url or ""
                # Skip noisy assets
                if any(s in u for s in ("google", "analytics", "tracking", "sentry")): return
                body = resp.text()
                if body and len(body) < 2_000_000:
                    self._json_blobs.append((u, body))
            except Exception:
                pass
        try:
            self._context.on("response", _on_response)
        except Exception:
            pass
        return self

    def __exit__(self, exc_type, exc, tb):
        try:
            if self._context:
                try: self._context.clear_cookies()
                except Exception: pass
                self._context.close()
            if self._browser: self._browser.close()
            if self._pw: self._pw.stop()
        finally:
            if self._temp_dir and os.path.isdir(self._temp_dir):
                shutil.rmtree(self._temp_dir, ignore_errors=True)

    def _try_fill(self, selectors, value):
        for sel in selectors:
            try:
                el = self._page.locator(sel).first
                if el.count() > 0 and el.is_visible(timeout=2000):
                    el.fill(value, timeout=4000); return sel
            except Exception: continue
        return None

    def _try_click(self, selectors):
        for sel in selectors:
            try:
                el = self._page.locator(sel).first
                if el.count() > 0 and el.is_visible(timeout=2000):
                    el.click(timeout=4000); return sel
            except Exception: continue
        return None

    def _is_logged_in(self):
        url = (self._page.url or "").lower()
        if "login=true" in url or "/home" in url or "/project/" in url: return True
        if "/login" in url or "signin" in url: return False
        for sel in LOGGED_IN_MARKERS:
            try:
                if self._page.locator(sel).first.count() > 0: return True
            except Exception: continue
        return False

    def _scroll(self, steps=8, pause=400):
        for _ in range(steps):
            try: self._page.evaluate("window.scrollBy(0, window.innerHeight);")
            except Exception: pass
            self._page.wait_for_timeout(pause)
        try: self._page.evaluate("window.scrollTo(0, 0);")
        except Exception: pass

    def inject_cookies(self, raw: str) -> bool:
        """Accept a BNAmericas session as a raw cookie string (the same
        format you'd copy from DevTools → Application → Cookies). Splits
        on `; ` into name=value pairs, scopes them to .bnamericas.com,
        loads the home page, and confirms we're logged in.

        Returns True when the injected session is valid (the home page
        renders as a signed-in user). Returns False when the cookies
        don't yield a logged-in session — the caller should then fall
        back to credential login.
        """
        if not raw or not raw.strip():
            return False
        pairs = []
        for chunk in raw.replace("\n", ";").split(";"):
            chunk = chunk.strip()
            if not chunk or "=" not in chunk:
                continue
            name, _, value = chunk.partition("=")
            name = name.strip()
            value = value.strip()
            if not name:
                continue
            pairs.append({
                "name": name, "value": value,
                "domain": ".bnamericas.com", "path": "/",
                "secure": True, "httpOnly": False, "sameSite": "Lax",
            })
        if not pairs:
            self.log("No usable cookies parsed from session string.")
            return False
        try:
            self._context.add_cookies(pairs)
        except Exception as e:
            self.log(f"Could not apply cookies: {e}")
            return False
        try:
            self._page.goto(ENTRY_URLS[0],
                            wait_until="domcontentloaded", timeout=25000)
            self._page.wait_for_timeout(1500)
        except Exception as e:
            self.log(f"Home-page load after cookie inject failed: {e}")
            return False
        for _ in range(6):
            if self._is_logged_in():
                self.log("Cookie session accepted.")
                return True
            self._page.wait_for_timeout(1000)
        self.log("Cookie session not recognised — looks expired.")
        return False

    def login(self, email, password):
        if self.manual_login:
            return self._manual_login()
        for url in ENTRY_URLS:
            try:
                self.log(f"Navigating to {url}")
                self._page.goto(url, wait_until="domcontentloaded", timeout=25000)
                self._page.wait_for_timeout(1200)
                if self._page.locator(PASSWORD_SELECTORS[0]).first.count() > 0: break
            except Exception as e:
                self.log(f"goto {url} failed: {e}")
        if self._try_fill(EMAIL_SELECTORS, email) is None:
            self.log("Email field not found. Switching to manual login.")
            return self._manual_login()
        if self._try_fill(PASSWORD_SELECTORS, password) is None:
            self.log("Password field not found.")
            return False
        if self._try_click(SUBMIT_SELECTORS) is None:
            try: self._page.keyboard.press("Enter")
            except Exception: pass
        try: self._page.wait_for_load_state("networkidle", timeout=30000)
        except Exception: pass
        self._page.wait_for_timeout(1500)
        for _ in range(8):
            if self._is_logged_in():
                self.log(f"Login success. URL: {self._page.url}")
                return True
            self._page.wait_for_timeout(1000)
        self.log(f"Login not confirmed. Final URL: {self._page.url}")
        return False

    def _manual_login(self):
        if self.headless:
            self.log("Manual login requires visible browser.")
            return False
        try: self._page.goto(ENTRY_URLS[0], wait_until="domcontentloaded", timeout=20000)
        except Exception: pass
        self.log(f"MANUAL LOGIN: please sign in. Waiting up to {self.manual_wait_secs}s")
        deadline = time.time() + self.manual_wait_secs
        while time.time() < deadline:
            self._page.wait_for_timeout(1500)
            if self._is_logged_in():
                self.log(f"Manual login detected. URL: {self._page.url}")
                return True
        self.log("Manual login timed out.")
        return False

    def detect_bna_language(self):
        """Detect BNA UI language. Returns 'en' / 'es' / 'pt' or None.

        Tries two approaches in order:
          1. The globe-icon dropdown button (most reliable when present).
             The button's text content is the 2-letter code (en/es/pt).
          2. Content fingerprinting — look for unmistakable Spanish or
             Portuguese keywords in the page body. This catches cases where
             the dropdown widget isn't on the page yet.
        Logs every step for diagnostics.
        """
        self.log("Detecting BNA UI language...")
        # ---- Try 1: globe-icon dropdown button ----
        # Globe-bearing selectors come FIRST. The generic
        # 'button#dropdown-basic' often matches a non-language dropdown
        # (e.g. a sort/filter widget) on the page, so we only fall back
        # to it as a last resort and STRICTLY validate the text.
        # We also iterate ALL matches per selector (not just .first) and
        # pick the one whose visible text is exactly a 2-letter code.
        candidates = (
            "button.dropdown-toggle:has(.fa-globe)",
            "button:has(.fa-globe)",
            "button:has(svg[data-icon='globe'])",
            "button:has(i.fa-globe)",
            "[data-testid='dropdown-basic']:has(.fa-globe)",
            "[data-testid='dropdown-basic']",
            "button#dropdown-basic",
        )
        for sel in candidates:
            try:
                loc = self._page.locator(sel)
                n = loc.count()
                if n == 0:
                    continue
                for i in range(min(n, 10)):
                    try:
                        btn = loc.nth(i)
                        txt = (btn.inner_text(timeout=2500) or "").strip().lower()
                        self.log(f"BNA language widget '{sel}'[{i}] inner_text={txt!r}")
                        cleaned = re.sub(r"[^a-z]", "", txt)
                        if cleaned in ("en", "es", "pt"):
                            self.log(f"BNA UI language detected via widget: {cleaned.upper()}")
                            return cleaned
                    except Exception:
                        continue
            except Exception as e:
                self.log(f"BNA language widget {sel} probe error: {e}")
                continue

        # ---- Try 2: content fingerprint ----
        try:
            txt = (self._page.inner_text("body") or "").lower()
        except Exception:
            txt = ""
        # Portuguese-only markers (NOT Spanish)
        pt_markers = ("antiga", "compañia"[:4] + "ia", "empresas e contatos",
                      "última revisão", "etapa atual", "tipo de propriedade",
                      "tipo de desenvolvimento", "obras principais",
                      "vida útil", "olá")
        # Spanish-only markers (NOT Portuguese)
        es_markers = ("etapa actual", "tipo de propiedad", "tipo de desarrollo",
                      "obras principales", "última revisión",
                      "compañías y contactos", "compañía", "hola",
                      "última revisión experta")
        # English markers
        en_markers = ("milestones, news", "current stage", "property type",
                      "development type", "principal works", "lifespan")
        pt_hits = sum(1 for m in pt_markers if m in txt)
        es_hits = sum(1 for m in es_markers if m in txt)
        en_hits = sum(1 for m in en_markers if m in txt)
        self.log(f"BNA content fingerprint hits — en={en_hits}, es={es_hits}, pt={pt_hits}")
        if pt_hits > es_hits and pt_hits > en_hits and pt_hits >= 1:
            self.log("BNA UI language detected via content fingerprint: PT")
            return "pt"
        if es_hits > pt_hits and es_hits > en_hits and es_hits >= 1:
            self.log("BNA UI language detected via content fingerprint: ES")
            return "es"
        if en_hits >= 1 and en_hits >= es_hits and en_hits >= pt_hits:
            self.log("BNA UI language detected via content fingerprint: EN")
            return "en"
        self.log("BNA language could not be detected.")
        return None

    def set_bna_language(self, target_lang):
        """Switch BNA UI language to the user-selected target ('en'/'es'/'pt').
        Detects BNA's current language first; if it already matches, returns
        True with no action. Otherwise opens the globe dropdown and picks the
        target. Returns True on success.

        The dropdown options use a stable parenthesized code at the end of
        each label: 'English (En)' / 'Inglés (En)' / 'Inglês (En)' all share
        '(En)'. We match on that suffix so the click works regardless of
        which language the dropdown is currently rendering its labels in.
        """
        target = (target_lang or "en").lower()
        if target not in ("en", "es", "pt"): target = "en"
        target_code = {"en": "(En)", "es": "(Es)", "pt": "(Pt)"}[target]
        current = self.detect_bna_language()
        if current == target:
            self.log(f"BNA UI already in {target.upper()}.")
            return True
        if current:
            self.log(f"BNA UI is in {current.upper()}; switching to {target.upper()} to match your selection.")
        else:
            self.log(f"BNA language widget not found; trying to switch to {target.upper()} blindly.")
        try:
            for sel in (
                "[data-testid='dropdown-basic']",
                "button.dropdown-toggle:has(.fa-globe)",
                "button:has(.fa-globe)",
            ):
                try:
                    btn = self._page.locator(sel).first
                    if btn.count() == 0: continue
                    if not btn.is_visible(timeout=1500): continue
                    btn.click(timeout=3000)
                    self._page.wait_for_timeout(500)
                    for opt_sel in (
                        f"text={target_code}",
                        f"a:has-text('{target_code}')",
                        f"li:has-text('{target_code}')",
                        f"[role='menuitem']:has-text('{target_code}')",
                        f"button:has-text('{target_code}')",
                    ):
                        try:
                            o = self._page.locator(opt_sel).first
                            if o.count() > 0 and o.is_visible(timeout=1500):
                                o.click(timeout=3000)
                                self._page.wait_for_timeout(2500)
                                self.log(f"Switched BNA UI to {target.upper()}.")
                                return True
                        except Exception: continue
                    break
                except Exception: continue
        except Exception as e:
            self.log(f"set_bna_language: {e}")
        self.log(f"Could not switch BNA UI; will rely on multilingual regex.")
        return False

    def load_project(self, project_url):
        self.log("Loading project page...")
        try: self._page.goto(project_url, wait_until="domcontentloaded", timeout=45000)
        except Exception as e: self.log(f"goto warning: {e}")
        try: self._page.wait_for_load_state("networkidle", timeout=30000)
        except Exception: pass
        self._page.wait_for_timeout(1500)
        # Per-page language alignment safety net. BNA's language
        # preference doesn't always carry over to subsequent project
        # page loads, so we re-check after each navigation and re-trigger
        # the dropdown click if the page rendered in the wrong language.
        if self.bna_lang in ("en", "es", "pt"):
            current = self.detect_bna_language()
            if current and current != self.bna_lang:
                self.log(
                    f"Project page rendered in {current.upper()} but "
                    f"output language is {self.bna_lang.upper()}; "
                    f"re-aligning before extraction."
                )
                try:
                    if self.set_bna_language(self.bna_lang):
                        # After the switch BNA usually reloads in-place;
                        # wait for that and re-navigate just to be safe
                        # so anchor / fragment hash state is clean.
                        self._page.wait_for_timeout(1500)
                        try:
                            self._page.goto(project_url,
                                            wait_until="domcontentloaded",
                                            timeout=30000)
                            self._page.wait_for_load_state(
                                "networkidle", timeout=20000)
                        except Exception:
                            pass
                        self._page.wait_for_timeout(1000)
                except Exception as e:
                    self.log(f"Per-page lang re-align failed: {e}")
        self._scroll(steps=5, pause=400)
        self._project_url = project_url
        return True

    def _click_radio(self, label):
        for sel in (f"label:has-text('{label}')", f"text='{label}'",
                    f"input[type='radio'][value*='{label.lower()}']"):
            try:
                el = self._page.locator(sel).first
                if el.count() > 0 and el.is_visible(timeout=1500):
                    el.click(timeout=3000)
                    self._page.wait_for_timeout(800)
                    return True
            except Exception: continue
        return False

    def _extract_companies_and_contacts(self):
        """Walk the unified BNA table.
        Layout:
          Headers: Company | Role | Website | Contact | Project position | Phone | Email
          Company rows: cells[0] = name, cells[1] = "Owner Participation: 100%"
          Contact rows: cells[0] = empty, cells[1] = name, cells[2] = "Pos (Mapped)"
        Returns (companies_list, contacts_list).
        """
        comps, contacts = [], []
        try: tables = self._page.locator("table").all()
        except Exception: tables = []
        target = None
        for tb in tables:
            try: head = (tb.locator("thead").inner_text(timeout=1500) or "").lower()
            except Exception: head = ""
            if "company" in head and "role" in head and ("contact" in head or "project position" in head):
                target = tb; break
        if target is None:
            return comps, contacts
        try: rows = target.locator("tbody tr").all()
        except Exception: rows = []
        for tr in rows:
            try:
                cells = tr.locator("td").all()
            except Exception: continue
            if not cells: continue
            def _txt(c):
                try: return (c.inner_text(timeout=1000) or "").strip()
                except Exception: return ""
            c0 = _txt(cells[0]) if len(cells) > 0 else ""
            c1 = _txt(cells[1]) if len(cells) > 1 else ""
            c2 = _txt(cells[2]) if len(cells) > 2 else ""
            # Strip URLs and "Show contacts" footer
            def _clean(s):
                import re as _re
                s = _re.split(r"(?i)\bShow\s+contacts\b", s, maxsplit=1)[0]
                s = _re.sub(r"https?://\S+", " ", s)
                s = _re.sub(r"\s*\(\d+\)\s*", " ", s)
                lines = [l.strip() for l in s.splitlines() if l.strip()]
                return lines[0].strip() if lines else ""
            c0c = _clean(c0); c1c = _clean(c1); c2c = _clean(c2)
            # Company row: cells[0] non-empty AND row has a company link
            link_text = ""
            try:
                lk = cells[0].locator("a").first
                if lk.count() > 0:
                    link_text = (lk.inner_text(timeout=900) or "").strip()
            except Exception: pass
            company_name = link_text or c0c
            if company_name and company_name.lower() not in ("company", "role"):
                # Role is in cell[1] — strip "Participation: NN%" tail
                role_raw = c1c
                role_clean = re.sub(r"\bParticipation:\s*\d+%?", "", role_raw, flags=re.IGNORECASE).strip()
                role_clean = role_clean.split("\n")[0].strip()
                if role_clean.lower() not in ("role", ""):
                    comps.append({"company": company_name, "role": role_clean})
            elif (not c0c) and c1c and c2c:
                # Contact row: cells[1]=Name, cells[2]=Position with "(bracket)" mapped role
                if c1c.lower() in ("contact", "name"): continue
                contacts.append({"name": c1c, "position": c2c})
        return comps, contacts

    def _extract_role_table(self):
        out = []
        URL_RE = re.compile(r"https?://\S+", re.IGNORECASE)
        EMAIL_RE = re.compile(r"[\w\.-]+@[\w\.-]+")
        def _clean(s):
            # Truncate everything from 'Show contacts' onward (footer link)
            s = re.split(r"(?i)\bShow\s+contacts\b", s, maxsplit=1)[0]
            # Drop URLs / emails
            s = URL_RE.sub(" ", s)
            s = EMAIL_RE.sub(" ", s)
            # Drop trailing counts like ' (2)'
            s = re.sub(r"\s*\(\d+\)\s*", " ", s)
            lines = [l.strip(" ,") for l in s.splitlines() if l.strip()]
            cleaned = [l for l in lines if l.lower() not in ("company", "role", "company (2)")]
            return cleaned[0].strip() if cleaned else ""
        try: tables = self._page.locator("table").all()
        except Exception: tables = []
        for tb in tables:
            try: head_text = (tb.locator("thead").inner_text(timeout=1500) or "").lower()
            except Exception: head_text = ""
            if "company" not in head_text or "role" not in head_text: continue
            try: rows = tb.locator("tbody tr").all()
            except Exception: rows = []
            for tr in rows:
                try:
                    cells = tr.locator("td").all()
                    if len(cells) < 2: continue
                    # Prefer the first hyperlink text inside the company cell
                    company = ""
                    try:
                        link = cells[0].locator("a").first
                        if link.count() > 0:
                            ltext = (link.inner_text(timeout=1200) or "").strip()
                            if ltext and not ltext.lower().startswith("http"):
                                company = ltext
                    except Exception: pass
                    if not company:
                        company = _clean((cells[0].inner_text(timeout=1500) or "").strip())
                    role = _clean((cells[-1].inner_text(timeout=1500) or "").strip())
                    if company and company.lower() not in ("company", "company (2)", "role"):
                        out.append({"company": company, "role": role})
                except Exception: continue
        if not out:
            try: txt = self._page.inner_text("body")
            except Exception: txt = ""
            for m in re.finditer(
                r"\b(Owner|Former owner|Concessionaire/operator|Concessionaire|Operator|Main contractor|EPC|EPCM|Engineering|Consultancy|Technology provider|Equipment)\b[^\n]*\n([^\n]+)",
                txt):
                role = m.group(1).strip()
                company = _clean(m.group(2).strip())
                if not (2 < len(company) < 200): continue
                low = company.lower()
                if low.startswith(("participation", "general management")): continue
                if re.match(r"^(?:january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|sept|oct|nov|dec|enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)\s+\d{4}\b", low): continue
                if re.match(r"^\d{4}[-/]\d{1,2}", company): continue
                if re.match(r"^(?:not yet disclosed|not disclosed|tbd|n/a)", low): continue
                out.append({"company": company, "role": role})
        return out

    def _extract_contact_table(self):
        out = []
        try: tables = self._page.locator("table").all()
        except Exception: tables = []
        for tb in tables:
            try: head_text = (tb.locator("thead").inner_text(timeout=1500) or "").lower()
            except Exception: head_text = ""
            if "name" not in head_text or "position" not in head_text: continue
            try: rows = tb.locator("tbody tr").all()
            except Exception: rows = []
            for tr in rows:
                try:
                    cells = tr.locator("td").all()
                    if len(cells) < 2: continue
                    name = (cells[0].inner_text(timeout=1500) or "").strip()
                    position = (cells[-1].inner_text(timeout=1500) or "").strip()
                    if name:
                        out.append({"name": name.split("\n")[0].strip(),
                                    "position": position.split("\n")[0].strip()})
                except Exception: continue
        return out

    # ---------- Milestones ----------
    def _looks_like_milestone(self, t):
        if not t: return False
        if len(t) < 50 or len(t) > 4000: return False
        if not re.search(r"[a-z]{3,}", t): return False
        if not re.search(r"[.!?]", t): return False
        # Skip nav-style or single-word labels
        if re.fullmatch(r"[A-Z][A-Z\s,&]+", t.split("\n")[0]): return False
        # Must contain whitespace (real sentence)
        if t.count(" ") < 6: return False
        return True

    def _clean_milestone(self, t):
        # Strip leading date prefix if present
        t = re.sub(
            r"^\s*([A-Za-zÀ-ÿ]{3,9}\s+\d{1,2},?\s*\d{4}|\d{1,2}[/\.\-]\d{1,2}[/\.\-]\d{2,4}|\d{4}-\d{2}-\d{2})\s*[:\-]?\s*",
            "", t)
        t = re.sub(r"\s+", " ", t).strip()
        return t

    def _extract_milestones(self):
        """Locate Milestones section, return first substantive paragraph(s).
        BNA usually shows newest first; we grab that paragraph regardless of
        whether a date appears inline."""
        out = []

        # Strategy 1: DOM walk SCOPED TO MILESTONE/TIMELINE CONTAINERS.
        # Without scoping, the first descriptive paragraph on the page
        # (usually the project Description) gets falsely identified as
        # a milestone because it passes _looks_like_milestone(). Limit
        # the search to elements that live inside a container whose
        # class contains 'milestone' or 'timeline' — that's BNA's own
        # marker for the milestones panel.
        try:
            # If neither container exists on the page we skip Strategy 1
            # entirely and let Strategy 2 (body-text anchor) handle it.
            has_container = False
            try:
                for c_sel in ("[class*='milestone' i]", "[class*='timeline' i]"):
                    if self._page.locator(c_sel).first.count() > 0:
                        has_container = True
                        break
            except Exception:
                has_container = False

            if has_container:
                for sel in (
                    "[class*='milestone' i] article",
                    "[class*='milestone' i] li",
                    "[class*='milestone' i] p",
                    "[class*='timeline' i] article",
                    "[class*='timeline' i] li",
                    "[class*='timeline' i] p",
                ):
                    try: items = self._page.locator(sel).all()
                    except Exception: items = []
                    for it in items[:120]:
                        try: t = (it.inner_text(timeout=900) or "").strip()
                        except Exception: continue
                        if self._looks_like_milestone(t):
                            cleaned = self._clean_milestone(t)
                            if cleaned and not any(o["text"] == cleaned for o in out):
                                out.append({"date": "", "text": cleaned})
                    if out: break
        except Exception as e:
            self.log(f"DOM milestones error: {e}")

        # Strategy 2: body-text paragraph scan after 'Milestones' (en/es/pt)
        def _find_anchor(txt):
            for word in ("Milestones", "Hitos", "Marcos"):
                idx = txt.find(word)
                if idx >= 0:
                    return idx + len(word)
            return -1
        if not out:
            try: txt = self._page.inner_text("body")
            except Exception: txt = ""
            i = _find_anchor(txt)
            if i >= 0:
                tail = txt[i:]
                paras = [p.strip() for p in re.split(r"\n\s*\n+", tail) if p.strip()]
                for p in paras:
                    if self._looks_like_milestone(p):
                        out.append({"date": "", "text": self._clean_milestone(p)})
                        break

        # Strategy 3: collapse line-by-line — the paragraph may be on adjacent
        # non-blank lines that pip into one paragraph in the page's flow.
        if not out:
            try: txt = self._page.inner_text("body")
            except Exception: txt = ""
            i = _find_anchor(txt)
            if i >= 0:
                tail = txt[i:]
                lines = [l.strip() for l in tail.splitlines()]
                # Greedy: collect consecutive non-empty lines, test the joined block
                buf = []
                for line in lines:
                    if not line:
                        if buf:
                            block = " ".join(buf)
                            if self._looks_like_milestone(block):
                                out.append({"date": "", "text": self._clean_milestone(block)})
                                break
                        buf = []
                    else:
                        buf.append(line)
                if not out and buf:
                    block = " ".join(buf)
                    if self._looks_like_milestone(block):
                        out.append({"date": "", "text": self._clean_milestone(block)})

        self.log(f"Milestones parsed: {len(out)}")
        return out

    def _pick_latest_milestone(self, milestones):
        if not milestones: return ""
        # Page lists newest first; just take the first hit text
        return (milestones[0].get("text", "") or "").strip()

    def _harvest_visible_contact_names(self):
        """Return contact names whose row is currently *visible* on the page.
        Strategy: find every contact-row anchor (<a href*='/person/'>) that is
        actually rendered (not display:none / hidden / aria-hidden)."""
        names = []
        try:
            anchors = self._page.locator("a[href*='/person/']").all()
        except Exception:
            anchors = []
        for a in anchors:
            try:
                if not a.is_visible(timeout=600):
                    continue
                t = (a.inner_text(timeout=800) or "").strip()
                if not t: continue
                if t.lower() in ("name", "contact", "people"): continue
                if not (2 < len(t) < 120): continue
                # Skip tab/breadcrumb links by checking parent is a row/cell
                if t not in names:
                    names.append(t)
            except Exception:
                continue
        return names

    # Chip-name aliases — when BNA UI is in Spanish/Portuguese and the
    # configured chip is English, click whichever variant the page renders.
    _CHIP_ALIASES = {
        "Owner": ["Owner", "Dueño", "Proprietário"],
        "Concessionaire/operator": ["Concessionaire/operator",
                                     "Concesionaria/operador",
                                     "Concesionaria/operadora",
                                     "Concessionária/operadora",
                                     "Concessionária / operadora"],
        "Construction and Management": ["Construction and Management",
                                         "Construcción y gestión",
                                         "Construção e Gestão"],
        "Engineering": ["Engineering", "Ingeniería", "Ingenieria", "Engenharia"],
        "Provider": ["Provider", "Proveedor", "Provedor", "Fornecedor"],
        "Consultancy": ["Consultancy", "Asesoría", "Asesoria", "Consultoria"],
        "All": ["All", "Todos", "Todas"],
        "Engineering area": ["Engineering", "Ingeniería", "Ingenieria", "Engenharia"],
        "Procurement / Purchasing": ["Procurement / Purchasing",
                                       "Adquisiciones / Compras",
                                       "Compras / Adquisiciones",
                                       "Aquisições / Compras"],
        "Project": ["Project", "Proyecto", "Projeto"],
    }

    def _click_chip(self, label):
        """Click an area chip. Tries the requested label first, then any
        Spanish/Portuguese alias. Returns True on success."""
        candidates = [label] + [a for a in self._CHIP_ALIASES.get(label, []) if a != label]
        for variant in candidates:
            for sel in (
                f"button:has-text('{variant}')",
                f"label:has-text('{variant}')",
                f"a:has-text('{variant}')",
                f"[role='tab']:has-text('{variant}')",
                f"[role='button']:has-text('{variant}')",
                f"[class*='chip' i]:has-text('{variant}')",
                f"[class*='filter' i]:has-text('{variant}')",
                f"[class*='tag' i]:has-text('{variant}')",
                f"span:has-text('{variant}')",
            ):
                try:
                    el = self._page.locator(sel).first
                    if el.count() == 0: continue
                    if not el.is_visible(timeout=1200): continue
                    el.click(timeout=3000, force=True)
                    return True
                except Exception:
                    continue
        return False

    def _extract_managers_by_chip(self, fields):
        """Bracket-parse is the PRIMARY path. The Contacts table shows the
        position string ending in '(Level - Area)' for every contact (e.g.
        '(Chief Executives - Engineering)', '(Managers - Project)',
        '(Technicians and Professionals - Procurement / Purchasing)').
        We map Area → role:
          Engineering              → Engineering Manager
          Project                  → Project Manager
          Procurement / Purchasing → Purchasing Manager

        Chip filter is unreliable (BNA's printable DOM never hides rows), so
        this purely-textual approach is the ground truth. Debug HTML dumps
        are still saved per chip state for traceability.
        """
        # Save debug dumps (best-effort, won't block primary logic)
        if self.debug_dir:
            try:
                os.makedirs(self.debug_dir, exist_ok=True)
                with open(os.path.join(self.debug_dir, "contacts_baseline.html"),
                         "w", encoding="utf-8") as f:
                    f.write(self._page.content() or "")
            except Exception: pass

        # Click each chip just to capture state-changed dumps for forensics
        for chip_label in ("Engineering", "Procurement / Purchasing", "Project"):
            try:
                if self._click_chip(chip_label):
                    self._page.wait_for_timeout(900)
                    if self.debug_dir:
                        fname = f"contacts_chip_{chip_label.replace(' / ', '_').replace(' ', '_')}.html"
                        with open(os.path.join(self.debug_dir, fname),
                                 "w", encoding="utf-8") as f:
                            f.write(self._page.content() or "")
            except Exception: pass

        # ---- TIER 0: highlight-company card (Owner + Project Manager) ----
        # BNA renders the OWNER company card with a curated Project chip
        # showing exactly which contact is the project manager. The set
        # of names is used as a FILTER on the bracket-parse output —
        # never as a direct add — because the owner-card view may also
        # list contacts who appear under a different chip (General
        # management etc.) and would be wrong for Project Manager.
        owner_pms = self._extract_owner_project_managers()
        owner_pm_norm = set()
        if owner_pms:
            self.log(f"Owner-card Project Managers (filter set): {owner_pms}")
            for n in owner_pms:
                owner_pm_norm.add(re.sub(r"\s+", " ", n.strip().lower()))

        # ---- PRIMARY: bracket-parse every contact row ----
        try:
            contacts = self._extract_contact_table_with_position()
        except Exception as e:
            self.log(f"Bracket-parse error: {e}")
            contacts = []
        self.log(f"Bracket-parse contacts: {len(contacts)} rows")

        # Map managers by AREA only (level is ignored). The bracket on each
        # contact's Project Position is "(Level - Area)". The Area portion
        # determines the management role:
        #   Engineering              -> Engineering Manager
        #   Procurement / Purchasing -> Purchasing Manager
        #   Project                  -> Project Manager
        # Any level (Chief Executives, Heads, Managers, Technicians, etc.)
        # qualifies as long as the area matches. This is the canonical rule
        # applied across every project the application processes.
        AREA_TO_ROLE = {
            "engineering": "Engineering Manager",
            "ingeniería": "Engineering Manager",
            "ingenieria": "Engineering Manager",
            "engenharia": "Engineering Manager",
            "procurement / purchasing": "Purchasing Manager",
            "adquisiciones / compras": "Purchasing Manager",
            "compras / adquisiciones": "Purchasing Manager",
            "aquisições / compras": "Purchasing Manager",
            "compras / aquisições": "Purchasing Manager",
            "purchasing": "Purchasing Manager",
            "compras": "Purchasing Manager",
            "procurement": "Purchasing Manager",
            "adquisiciones": "Purchasing Manager",
            "aquisições": "Purchasing Manager",
            "project": "Project Manager",
            "proyecto": "Project Manager",
            "projeto": "Project Manager",
        }

        # Each contact may appear in multiple rows on BNA's live Contacts
        # view (one row per role assignment). To keep the output clean, every
        # NAME is mapped to at most ONE manager role — its FIRST recognised
        # role wins. This stops a person whose primary role is Engineering
        # from leaking into Purchasing or Project just because they have a
        # secondary assignment there.
        already_assigned = {}  # name_lower -> role
        decisions = []
        def _norm_name_local(s):
            return re.sub(r"\s+", " ", str(s or "").strip().lower())

        for c in contacts:
            pos = (c.get("position") or "").strip()
            name = (c.get("name") or "").strip()
            if not name or name.lower() in ("name", "contact", "people"): continue
            brackets = re.findall(r"\(([^()]+)\)", pos)
            if not brackets:
                decisions.append((name, pos, "skip: no bracket"))
                continue
            # Use the FIRST bracket — represents the contact's primary role.
            bracket = re.sub(r"\s+", " ", brackets[0].strip())
            if " - " in bracket:
                area = bracket.split(" - ", 1)[1].strip()
            else:
                area = bracket.strip()
            role = AREA_TO_ROLE.get(area.lower())
            if not role:
                decisions.append((name, pos, f"skip: area '{area}' not a target"))
                continue
            nk = _norm_name_local(name)
            if nk in already_assigned:
                # Name already mapped to a (possibly different) role — keep
                # the first assignment, drop this duplicate row.
                prev = already_assigned[nk]
                decisions.append((name, pos, f"skip: already '{prev}', this row says '{role}'"))
                continue
            # Bracket parse is authoritative for Project Manager. The
            # earlier owner-card filter excluded legitimate project
            # managers because the regex-based extraction picked up
            # wrong names from outside the owner card (Maricunga case).
            # The bracket "(Managers - Project)" / "(Heads - Project)"
            # comes from BNA's own curation per-contact, so trust it.
            # owner_pm_norm is now informational only (logged earlier).
            already_assigned[nk] = role
            fields.setdefault(f"manager::{role}", []).append(name)
            decisions.append((name, pos, f"assigned: {role}"))

        # Log + persist decisions for traceability across all future projects
        for role in ("Project Manager", "Purchasing Manager", "Engineering Manager"):
            v = fields.get(f"manager::{role}", [])
            self.log(f"{role}: {', '.join(v) if v else '(none)'}")
        if self.debug_dir:
            try:
                with open(os.path.join(self.debug_dir, "manager_decisions.txt"),
                         "w", encoding="utf-8") as f:
                    for n, p, d in decisions:
                        f.write(f"NAME={n} | POS={p} | DECISION={d}\n")
            except Exception: pass

    def _extract_all_companies_with_roles(self):
        """Return [{'company', 'role'}] for every company on the Companies
        & Contacts tab. BNA renders this section in THREE layouts:

          (A0) Highlighted Owner card — `<div class="highlight-company">`
               with role in <b> and company in `a.fw-bold`. Used by the
               Spanish/Portuguese live UI for the primary owner.
          (A) Live UI list — `<div class="list-collapsed__item">` blocks.
          (B) Printable / table — header may be 'Company/Role' (en),
               'Compañía/Rol' (es) or 'Empresa/Função' (pt).
        """
        out = []
        # ---------- (A0) highlight-company cards ----------
        try:
            cards = self._page.locator(".highlight-company").all()
        except Exception:
            cards = []
        for card in cards:
            try:
                role = ""
                bs = card.locator("b").all()
                for b in bs:
                    t = (b.inner_text(timeout=800) or "").strip()
                    if t and t.lower() not in ("show contacts", "mostrar contactos"):
                        role = t; break
                company = ""
                links = card.locator("a.fw-bold[href*='/company/']").all()
                if not links:
                    links = card.locator("a[href*='/company/']").all()
                for lk in links:
                    t = (lk.inner_text(timeout=800) or "").strip()
                    if t and not t.lower().startswith("http"):
                        company = re.sub(r"\s+", " ", t).strip(); break
                if company:
                    out.append({"company": company, "role": role})
            except Exception:
                continue

        # ---------- (A) list-collapsed__item layout ----------
        # Note: tiers A and B both run and append to `out`. Dedup at the
        # end. Earlier code returned after A which made tier B unreachable
        # whenever ANY list-collapsed__item existed; we now always run
        # both so the printable table fallback can rescue companies the
        # live UI hides behind chip filters.
        try:
            items = self._page.locator("[class*='list-collapsed__item']").all()
        except Exception:
            items = []
        if items:
            for item in items:
                # Company name: first /company/ link inside this item
                company = ""
                try:
                    link = item.locator("a[href*='/company/']").first
                    if link.count() > 0:
                        t = (link.inner_text(timeout=800) or "").strip()
                        if t and not t.lower().startswith("http"):
                            company = re.sub(r"\s+", " ", t).strip()
                except Exception: pass
                if not company:
                    continue

                # Role: the px-2 (or 30% width) sub-div has the role text.
                # Try multiple selectors for resilience.
                role = ""
                for sel in (
                    "div.px-2",
                    "div[class*='px-2']",
                    "div[style*='width: 30%']",
                    "div[style*='width:30%']",
                ):
                    try:
                        loc = item.locator(sel).first
                        if loc.count() > 0:
                            t = (loc.inner_text(timeout=800) or "").strip()
                            if t:
                                # Strip "Participation: 100%" trailer
                                t = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", t)[0].strip()
                                role = t.split("\n")[0].strip()
                                break
                    except Exception: continue

                # Last-resort: scan the item's full text and pick the first
                # non-URL, non-link line that isn't "Show contacts" or the
                # company name itself.
                if not role:
                    try: full = item.inner_text(timeout=800) or ""
                    except Exception: full = ""
                    lines = [l.strip() for l in full.splitlines() if l.strip()]
                    for l in lines:
                        if l == company: continue
                        if re.match(r"(?i)^\s*show\s+contacts\b", l): continue
                        if l.lower().startswith("http"): continue
                        if l.lower() in ("follow", "participation"): continue
                        role = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", l)[0].strip()
                        break

                out.append({"company": company, "role": role})
            # NOTE: don't return here — tier B (the PDF / printable
            # table) often holds extra companies the live UI hides
            # behind chip filters. Keep going.

        # ---------- (B) table fallback ----------
        try: tables = self._page.locator("table").all()
        except Exception: tables = []
        target = None
        for tb in tables:
            try: head = (tb.locator("thead").inner_text(timeout=1500) or "").lower()
            except Exception: head = ""
            company_token = any(k in head for k in ("company", "compañía", "compania", "compañia", "empresa", "empresas"))
            role_token = any(k in head for k in ("role", "rol", "função", "funcao"))
            if company_token and role_token:
                target = tb; break
        # Walk EVERY descendant tr — including those inside nested tables.
        # If Tier B couldn't lock on a labelled table, skip this walk
        # entirely. Tier C (static-HTML orphan-tbody rescue) below works
        # off the raw page HTML and will catch the rows on its own.
        rows = []
        if target is not None:
            try: rows = target.locator("tr").all()
            except Exception: rows = []
        for tr in rows:
            try:
                # Skip rows that wrap a nested table (the inner rows are
                # already captured separately).
                if tr.locator("table").count() > 0:
                    continue
            except Exception: pass
            try: cells = tr.locator("td").all()
            except Exception: continue
            if len(cells) < 2: continue
            company = ""
            try:
                lk = cells[0].locator("a[href*='/company/']").first
                if lk.count() > 0:
                    t = (lk.inner_text(timeout=900) or "").strip()
                    if t and not t.lower().startswith("http"):
                        company = t.split("\n")[0].strip()
            except Exception: pass
            if not company:
                try: raw = (cells[0].inner_text(timeout=900) or "").strip()
                except Exception: raw = ""
                raw = re.split(r"(?i)\b(?:Show\s+contacts|Mostrar\s+contactos|Mostrar\s+contatos)\b", raw, maxsplit=1)[0]
                raw = re.sub(r"https?://\S+", " ", raw)
                raw = re.sub(r"\s*\(\d+\)\s*", " ", raw)
                lines = [l.strip() for l in raw.splitlines() if l.strip()]
                lines = [l for l in lines if l.lower() not in ("company", "role", "contact")]
                if lines: company = lines[0]
            if not company: continue
            if re.match(r"(?i)^\s*show\s+contacts\b", company): continue
            role = ""
            for c in cells[1:]:
                try: t = (c.inner_text(timeout=900) or "").strip()
                except Exception: t = ""
                if not t: continue
                if t.lower().startswith("http"): continue
                if re.match(r"(?i)^\s*show\s+contacts\b", t): continue
                t = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", t)[0].strip()
                role = t.split("\n")[0].strip()
                break
            out.append({"company": company, "role": role})

        # ---------- (C) orphan-tbody rescue ----------
        # BNA's PT/ES print HTML sometimes closes the companies table after
        # the FIRST data row and emits each subsequent company as a sibling
        # <tbody> after </table>. Browsers don't always reparent these so
        # target.locator("tr") misses them.
        #
        # NOTE: Walking every <tbody> on the page via Playwright is slow
        # (each handle call is a round-trip). On pages with many tables
        # this could take long enough to break downstream tabs. So we do
        # the orphan-tbody rescue via the static HTML pulled in one shot
        # — no per-element Playwright calls.
        try:
            page_html = self._page.content() or ""
        except Exception:
            page_html = ""
        if page_html:
            try:
                # Pull every tr that has at least 2 cells and a /company/
                # link in cell 0. Cap iterations as a safety net.
                tr_pat = re.compile(r"<tr[^>]*>([\s\S]*?)</tr>", re.IGNORECASE)
                td_pat = re.compile(r"<td[^>]*>([\s\S]*?)</td>", re.IGNORECASE)
                link_pat = re.compile(
                    r'<a[^>]+href=["\'][^"\']*?/company/[^"\']*?["\'][^>]*?>([\s\S]*?)</a>',
                    re.IGNORECASE)
                tag_strip = re.compile(r"<[^>]+>")
                import html as _html
                seen_orphan = set()
                count = 0
                for tr_m in tr_pat.finditer(page_html):
                    count += 1
                    if count > 500:  # safety cap
                        break
                    inner = tr_m.group(1)
                    if "<table" in inner.lower():
                        continue  # row wrapping nested table
                    tds = td_pat.findall(inner)
                    if len(tds) < 2:
                        continue
                    lk = link_pat.search(tds[0])
                    if not lk:
                        continue
                    # Decode HTML entities (&amp; -> &, &quot; -> ", &#x27; -> ')
                    # BEFORE strip + collapse so 'Neoingeniería P&amp;T'
                    # collapses to 'Neoingeniería P&T' and dedupes against
                    # the live-DOM-captured 'Neoingeniería P&T' copy.
                    company = _html.unescape(lk.group(1))
                    company = re.sub(r"\s+", " ", tag_strip.sub(" ", company)).strip()
                    if not company:
                        continue
                    if re.match(r"(?i)^\s*show\s+contacts\b", company):
                        continue
                    # Role from cell 1
                    role_html = _html.unescape(tds[1])
                    role = re.sub(r"\s+", " ", tag_strip.sub(" ", role_html)).strip()
                    role = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", role)[0].strip()
                    role = role.split("\n")[0].strip()
                    key = (company.lower(), role.lower())
                    if key in seen_orphan:
                        continue
                    seen_orphan.add(key)
                    out.append({"company": company, "role": role})
            except Exception as e:
                self.log(f"Orphan-tbody rescue error: {e}")

        # De-dupe by (company, role) — multiple tiers may emit the same row
        seen = set(); deduped = []
        for r in out:
            key = (re.sub(r"\s+", " ", str(r.get("company", "")).strip().lower()),
                   re.sub(r"\s+", " ", str(r.get("role", "")).strip().lower()))
            if key in seen: continue
            seen.add(key); deduped.append(r)
        return deduped

    @staticmethod
    def _chip_for_role(role_text):
        """Map a BNA role string to the chip bucket it belongs to.
        Accepts English / Spanish / Portuguese role text. Returns None if no
        recognized term is found.

        BNA usually formats role cells as '<Role label> - <description>'.
        Classification MUST run on the role label only — running it on
        the full text causes false positives (e.g. 'Feasibility study -
        Cooperation agreement for engineering and construction of a
        pilot plant' would wrongly match Engineering on the word
        'engineering' inside the description). Trim on first ' - '.
        """
        if not role_text: return None
        r_full = re.sub(r"\s+", " ", str(role_text).lower()).strip()
        if not r_full: return None
        # Use only the head (before ' - ' / ' — '). Em-dash and en-dash also.
        r = re.split(r"\s+[-–—]\s+", r_full, maxsplit=1)[0].strip()
        if not r: r = r_full
        # Owner / Dueño / Proprietário
        if (r == "owner" or r.startswith("owner ") or r.startswith("owners")
            or r == "dueño" or r == "dueno" or r.startswith("dueño ")
            or r.startswith("propietario") or r.startswith("proprietário")
            or r.startswith("proprietario")):
            return "Owner"
        # Concessionaire / Operator (en/es/pt)
        if any(k in r for k in ("concessionaire", "operator",
                                "concesionari", "concesionario", "operador",
                                "concessionári", "concessionario", "operador")):
            return "Concessionaire/operator"
        # Construction and management — en/es/pt + sub-roles
        if any(k in r for k in (
            "construction and management",
            "construcción y gestión", "construccion y gestion",
            "construção e gestão", "construcao e gestao",
            "main contractor",
            "contratista principal", "contratante principal",
            "epc",
            "main works constructor", "constructora obras principales",
            "construtor das obras principais",
            "complementary works", "obras complementarias", "obras complementares",
            "construction management",
            "gestión de la construcción", "gestao da construcao",
            "gestão de construção",
        )):
            return "Construction and Management"
        # Engineering / Ingeniería / Engenharia
        if ("engineering" in r or "ingeniería" in r or "ingenieria" in r
            or "engenharia" in r
            or r == "feed" or r.startswith("feed ")):
            return "Engineering"
        # Provider / Proveedor / Provedor / Fornecedor / Supplier
        if any(k in r for k in (
            "provider", "supplier",
            "proveedor", "provedor", "fornecedor",
        )):
            return "Provider"
        # Consultancy / Asesoría / Consultoria + technical advisory & studies.
        # NOTE: Financial Advisor and Legal Advisor are intentionally NOT
        # mapped here — BNA exposes them as their own chips and including
        # them under Consultancy pollutes the consultancy list with
        # banks / law firms that the AI side never lists as consultants.
        if any(k in r for k in (
            "consultancy", "consultant",
            "asesoría técnica", "asesoria tecnica", "consultoría", "consultoria",
            "feasibility study", "estudio de factibilidad", "estudo de viabilidade",
            "prefeasibility study", "estudio de prefactibilidad", "estudo de pré-viabilidade",
            "preliminary economic assessment", "pea",
            "evaluación económica preliminar", "avaliação econômica preliminar",
            "environmental study", "estudio ambiental", "estudo ambiental",
            "prospecting services", "servicios de prospección", "serviços de prospecção",
            "resources/reserves estimation",
            "estimación de recursos", "estimativa de recursos",
        )):
            return "Consultancy"
        return None

    def _extract_latlon_from_page(self, fields):
        """Extract project Latitude/Longitude from the current page.
        Strategy (try in order, take FIRST plausible match):
          1. Google Static Maps img: 'staticmap?...center=LAT,LON'
          2. Generic '?center=LAT,LON' in any URL on the page
          3. 'q=LAT,LON' or '@LAT,LON' (Google Maps share-style)
          4. data-lat / data-lng attributes
          5. JSON 'lat':X,'lng':Y in any embedded script

        On success writes Latitude, Longitude, Coordinates AND the AI
        field key 'Latitude and Longitude' for direct lookup.
        Logs every attempt, persists a latlon_debug.txt for traceability.
        """
        attempts = []
        try: page_html = self._page.content() or ""
        except Exception: page_html = ""
        try: page_text = self._page.inner_text("body") or ""
        except Exception: page_text = ""

        sources = [("page.content()", page_html),
                   ("page.inner_text('body')", page_text)]
        # Also include captured XHR JSON blobs
        try:
            for u, body in (self._json_blobs or [])[-30:]:
                sources.append((f"xhr:{u[-50:]}", body))
        except Exception: pass

        patterns = [
            ("staticmap center", r"staticmap\?[^\"']*?center=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"),
            ("?center=", r"[?&]center=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"),
            ("?ll=",      r"[?&]ll=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"),
            ("?q=",       r"[?&]q=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"),
            ("@lat,lon",  r"@(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"),
            ("markers",   r"markers=color:[^&]+%7C(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"),
            ("data-lat/lng", r"data-lat[\"']?=[\"']?(-?\d{1,3}\.\d+).*?data-l(?:ng|on|ongitude)[\"']?=[\"']?(-?\d{1,3}\.\d+)"),
            ('"lat":n,"lng":n', r"[\"']lat(?:itude)?[\"']\s*:\s*(-?\d{1,3}\.\d+)[^\d-]+[\"']l(?:o?n|ong|ongitude)[\"']\s*:\s*(-?\d{1,3}\.\d+)"),
        ]

        found = None
        for name, src in sources:
            for label, pat in patterns:
                try:
                    m = re.search(pat, src, re.IGNORECASE | re.DOTALL)
                except Exception:
                    continue
                if not m: continue
                lat_s, lon_s = m.group(1), m.group(2)
                try:
                    la = float(lat_s); lo = float(lon_s)
                except ValueError:
                    continue
                if not (-90 <= la <= 90 and -180 <= lo <= 180):
                    attempts.append((name, label, f"out-of-range {la},{lo}"))
                    continue
                attempts.append((name, label, f"FOUND {lat_s},{lon_s}"))
                found = (lat_s, lon_s)
                break
            if found: break

        if found:
            lat, lon = found
            fields["Latitude"] = lat
            fields["Longitude"] = lon
            fields["Coordinates"] = f"{lat}, {lon}"
            # Also store with the canonical AI field name for direct lookup
            fields["Latitude and Longitude"] = f"{lat}, {lon}"
            self.log(f"Coordinates: {lat}, {lon}")
        else:
            self.log("Lat/Lon not found in page content.")

        # Persist debug log
        if self.debug_dir:
            try:
                os.makedirs(self.debug_dir, exist_ok=True)
                with open(os.path.join(self.debug_dir, "latlon_debug.txt"),
                         "w", encoding="utf-8") as f:
                    f.write(f"Found: {found}\n\n")
                    for n, label, dec in attempts:
                        f.write(f"  source={n} | pattern={label} | {dec}\n")
                    if not attempts:
                        f.write("(no attempts logged - all patterns missed)\n")
                # Also dump first 500 chars of the page HTML containing 'center='
                try:
                    i = page_html.lower().find("center=")
                    if i >= 0:
                        ctx = page_html[max(0, i - 200):i + 300]
                        with open(os.path.join(self.debug_dir, "latlon_context.html"),
                                 "w", encoding="utf-8") as f:
                            f.write(ctx)
                except Exception: pass
            except Exception: pass

    def _extract_companies_under_chip(self):
        """After a chip is clicked, find the visible Company-column values.
        Strategy:
          - Locate the table whose header includes 'Company' and 'Role'.
          - Walk visible rows; pull the Company cell text (or its <a> link).
          - Stop appending the moment a row's text starts with 'Show contacts'
            (case-insensitive); do NOT include that row.
        Returns a list of unique company names (preserve order).
        """
        names = []
        try: tables = self._page.locator("table").all()
        except Exception: tables = []
        target = None
        for tb in tables:
            try: head = (tb.locator("thead").inner_text(timeout=1500) or "").lower()
            except Exception: head = ""
            company_token = any(k in head for k in ("company", "compañía", "compania", "compañia", "empresa", "empresas"))
            role_token = any(k in head for k in ("role", "rol", "função", "funcao"))
            if company_token and role_token:
                target = tb; break
        if target is None:
            return names
        try: rows = target.locator("tbody tr").all()
        except Exception: rows = []
        for tr in rows:
            try:
                row_text = (tr.inner_text(timeout=1000) or "").strip()
            except Exception:
                row_text = ""
            # Stop sentinel: rows that begin with "Show contacts"
            if re.match(r"(?i)^\s*(?:show\s+contacts|mostrar\s+contactos|mostrar\s+contatos)\b", row_text):
                break
            try:
                cells = tr.locator("td").all()
            except Exception:
                continue
            if not cells:
                continue
            # Company name lives in the first cell. Prefer the link text.
            company = ""
            try:
                lk = cells[0].locator("a").first
                if lk.count() > 0:
                    t = (lk.inner_text(timeout=900) or "").strip()
                    if t and not t.lower().startswith("http"):
                        company = t.split("\n")[0].strip()
            except Exception: pass
            if not company:
                try:
                    raw = (cells[0].inner_text(timeout=900) or "").strip()
                except Exception:
                    raw = ""
                # Strip URLs and "Show contacts" footer
                raw = re.split(r"(?i)\b(?:Show\s+contacts|Mostrar\s+contactos|Mostrar\s+contatos)\b", raw, maxsplit=1)[0]
                raw = re.sub(r"https?://\S+", " ", raw)
                # Drop trailing counts like " (2)"
                raw = re.sub(r"\s*\(\d+\)\s*", " ", raw)
                lines = [l.strip() for l in raw.splitlines() if l.strip()]
                # Reject header rows
                lines = [l for l in lines if l.lower() not in ("company", "role")]
                if lines:
                    company = lines[0]
            if not company:
                continue
            if re.match(r"(?i)^\s*show\s+contacts\b", company):
                break
            if company not in names:
                names.append(company)
        return names

    def _extract_companies_by_chip(self, fields):
        """Populate fields['company::<Chip>'] for every chip in self.company_chips.

        Strategy:
          PRIMARY  - read every row in the unfiltered All-table; classify each
                     company by its Role text (no chip click required). This
                     is the ground-truth path because BNA's role text is
                     always shown.
          SECONDARY- if the All parse returns nothing, fall back to per-chip
                     click + parse. This rescues edge cases where the All
                     table isn't rendered as expected.

        Decisions are persisted to company_decisions.txt for traceability.
        """
        if self.debug_dir:
            try:
                os.makedirs(self.debug_dir, exist_ok=True)
                with open(os.path.join(self.debug_dir, "companies_baseline.html"),
                         "w", encoding="utf-8") as f:
                    f.write(self._page.content() or "")
            except Exception: pass

        decisions = []

        # Make sure 'All' chip is selected so every row is visible.
        try:
            self._click_chip("All")
            self._page.wait_for_timeout(800)
        except Exception: pass
        try: self._scroll(steps=3, pause=300)
        except Exception: pass

        # Pre-seed every configured chip with an empty list so the comparator
        # always finds the key (avoids "Not Available" when chip simply has
        # no companies on this project).
        for chip_label in self.company_chips:
            fields.setdefault(f"company::{chip_label}", [])

        # ---- PRIMARY: All-table parse + role-based grouping ----
        rows = self._extract_all_companies_with_roles()
        self.log(f"All-table: {len(rows)} company rows.")
        if rows:
            for row in rows:
                chip = self._chip_for_role(row.get("role", ""))
                if not chip:
                    decisions.append(("(unmapped)", row.get("company", ""),
                                       row.get("role", ""), "no chip mapping"))
                    continue
                bucket_key = f"company::{chip}"
                # Try to match chip to one of the configured chip names —
                # case-insensitive. If not found, still create the bucket.
                target_chip = chip
                for cfg in self.company_chips:
                    if cfg.lower() == chip.lower():
                        target_chip = cfg; break
                bucket_key = f"company::{target_chip}"
                fields.setdefault(bucket_key, [])
                # Case + accent + entity insensitive dedupe so the same
                # company captured by multiple tiers (live DOM + static
                # HTML rescue, with or without &amp; entities) only
                # appears once in the final list.
                cname = row["company"]
                cnorm = re.sub(r"\s+", " ",
                                _strip_accents_local(cname).lower()
                                ).strip()
                existing_norms = {
                    re.sub(r"\s+", " ",
                           _strip_accents_local(x).lower()).strip()
                    for x in fields[bucket_key]
                }
                if cnorm and cnorm not in existing_norms:
                    fields[bucket_key].append(cname)
                decisions.append((target_chip, row["company"], row.get("role", ""),
                                   "assigned via All-table"))
        else:
            # ---- SECONDARY: per-chip click + parse ----
            self.log("All-table empty; falling back to per-chip click harvest.")
            for chip_label in self.company_chips:
                ok = self._click_chip(chip_label)
                if not ok:
                    decisions.append((chip_label, "(none)", "(none)", "chip not clickable"))
                    continue
                self._page.wait_for_timeout(1200)
                try: self._scroll(steps=2, pause=300)
                except Exception: pass
                names = self._extract_companies_under_chip()
                fields[f"company::{chip_label}"] = names
                for n in names:
                    decisions.append((chip_label, n, "(per-chip)", "harvested"))
                if self.debug_dir:
                    try:
                        fname = "companies_chip_" + re.sub(r"[^A-Za-z0-9]+", "_",
                                                           chip_label).strip("_") + ".html"
                        with open(os.path.join(self.debug_dir, fname),
                                 "w", encoding="utf-8") as f:
                            f.write(self._page.content() or "")
                    except Exception: pass

        # Log final per-chip results
        for chip_label in self.company_chips:
            v = fields.get(f"company::{chip_label}", [])
            self.log(f"Chip '{chip_label}': {len(v)} companies -> {v}")

        if self.debug_dir:
            try:
                with open(os.path.join(self.debug_dir, "company_decisions.txt"),
                         "w", encoding="utf-8") as f:
                    for chip, comp, role, decision in decisions:
                        f.write(f"CHIP={chip} | COMPANY={comp} | ROLE={role} | DECISION={decision}\n")
            except Exception: pass

    def _extract_owner_project_managers(self):
        """Extract Project Manager(s) shown in BNA's curated owner card
        (`<div class="highlight-company">`). The card contains:
          - <b>Proprietário|Owner|Propietario</b> (role tag)
          - <a href="/company/...">Owner company name</a>
          - <button>...Projeto|Project|Proyecto (N)</button>  (filter chip)
          - <a href="/person/...">Person name</a>  (the project manager)

        Returns list of person names extracted, [] if none.
        Static-HTML regex pass to keep it fast and not block on Playwright."""
        names = []
        try:
            html = self._page.content() or ""
        except Exception:
            return names
        if not html or "highlight-company" not in html:
            return names
        try:
            # Capture each highlight-company block
            card_pat = re.compile(
                r'<div[^>]*class="[^"]*highlight-company[^"]*"[^>]*>([\s\S]*?)(?=<div[^>]*class="[^"]*highlight-company|</div>\s*</div>\s*<div[^>]*class="mb-3|$)',
                re.IGNORECASE)
            person_link_pat = re.compile(
                r'<a[^>]+href="[^"]*?/person/[^"]*?"[^>]*>([\s\S]*?)</a>',
                re.IGNORECASE)
            tag_strip = re.compile(r"<[^>]+>")
            for cm in card_pat.finditer(html):
                block = cm.group(1)
                # Look for the chip label that signals project filter
                # (case-insensitive, multilingual). The presence of any one
                # of these markers indicates the contacts below are
                # project-related.
                if not re.search(r"\b(?:Project|Proyecto|Projeto)\s*\(\d+\)",
                                 block, re.IGNORECASE):
                    continue
                import html as _html2
                for pm in person_link_pat.finditer(block):
                    raw = _html2.unescape(pm.group(1))
                    name = re.sub(r"\s+", " ", tag_strip.sub(" ", raw)).strip()
                    if name and name not in names:
                        names.append(name)
        except Exception as e:
            self.log(f"Owner-card PM extraction error: {e}")
        return names


    def _extract_contact_table_with_position(self):
        """Walk every <tr> on the contacts view; return rows where one cell
        carries a person name and another cell carries the position string
        ending in '(Level - Area)'. Robust to header drift and multi-line
        cells (the bracket may sit on its own line in inner_text)."""
        out = []
        try: rows = self._page.locator("tr").all()
        except Exception: rows = []
        for tr in rows:
            try:
                cells = tr.locator("td").all()
            except Exception: continue
            if len(cells) < 2: continue
            texts = []
            for cell in cells:
                try: t = (cell.inner_text(timeout=600) or "").strip()
                except Exception: t = ""
                if t: texts.append(t)
            if len(texts) < 2: continue
            # Position cell: the FIRST cell containing a "( ... - ... )" bracket
            position = ""
            position_idx = -1
            for idx, t in enumerate(texts):
                # Flatten newlines for bracket detection
                flat = re.sub(r"\s+", " ", t)
                if re.search(r"\([^()]+ - [^()]+\)", flat):
                    position = flat
                    position_idx = idx
                    break
            # Name cell: the cell BEFORE the position cell (typical order:
            # Name | Position | Phone | Email)
            if position_idx > 0:
                name_raw = texts[position_idx - 1]
            else:
                name_raw = texts[0]
                # If first cell has no person, scan forward for one that does
                # (skip pure phone / email cells)
                for t in texts:
                    low = t.lower()
                    if "@" in low or re.fullmatch(r"[\d\-\s\.\(\)\+]+", t.strip()):
                        continue
                    name_raw = t; break
            name = name_raw.split("\n")[0].strip()
            # Reject phone/email-only or junk cells
            if not name: continue
            if "@" in name: continue
            if re.fullmatch(r"[\d\-\s\.\(\)\+]+", name): continue
            if name.lower() in ("name", "contact", "company", "role"): continue
            # If we still don't have a position, fall back to the cell
            # immediately after the name cell
            if not position and len(texts) >= 2:
                position = re.sub(r"\s+", " ", texts[1])
            out.append({"name": name, "position": position})
        return out

    def extract_fields(self):
        fields = {}
        url = self._project_url or self._page.url

        # Companies & Contacts
        try:
            cc_url = _ensure_tab(url, "companies-contacts")
            self.log(f"Loading Companies & Contacts: {cc_url}")
            self._page.goto(cc_url, wait_until="domcontentloaded", timeout=30000)
            try: self._page.wait_for_load_state("networkidle", timeout=20000)
            except Exception: pass
            self._page.wait_for_timeout(1200)
            self._click_radio("Companies")
            self._page.wait_for_timeout(800)
            self._scroll(steps=4, pause=300)
            # NEW canonical path: chip-by-chip harvest into company::<Chip>
            self._extract_companies_by_chip(fields)
            # Lat/Lon — BNA renders a Google Static Maps thumbnail on the
            # Companies & Contacts page. The img URL contains
            # '?center=LAT,LON'. Pull it from the page content directly.
            self._extract_latlon_from_page(fields)
            # Legacy: also keep the unified contacts list parsed from the
            # Companies-radio table (used downstream by managers if needed).
            try:
                _, contacts_unified = self._extract_companies_and_contacts()
            except Exception:
                contacts_unified = []
            self._click_radio("Contacts")
            self._page.wait_for_timeout(1200)
            self._scroll(steps=4, pause=300)
            self._extract_managers_by_chip(fields)
        except Exception as e:
            self.log(f"Companies & Contacts extraction error: {e}")

        # Milestones
        try:
            ms = []
            for slug in ("milestones-news-reports", "milestones", "milestones-news",
                         "hitos-noticias-reportes", "hitos", "marcos-noticias-relatorios", "marcos"):
                ms_url = _ensure_tab(url, slug)
                self.log(f"Loading Milestones tab: {ms_url}")
                self._page.goto(ms_url, wait_until="domcontentloaded", timeout=30000)
                try: self._page.wait_for_load_state("networkidle", timeout=20000)
                except Exception: pass
                self._page.wait_for_timeout(1500)
                self._scroll(steps=8, pause=500)
                # Always dump for inspection
                if self.debug_dir:
                    try:
                        os.makedirs(self.debug_dir, exist_ok=True)
                        with open(os.path.join(self.debug_dir, "milestones_text.txt"), "w", encoding="utf-8") as f:
                            f.write(self._page.inner_text("body") or "")
                        with open(os.path.join(self.debug_dir, "milestones_page.html"), "w", encoding="utf-8") as f:
                            f.write(self._page.content() or "")
                        self.log(f"Saved milestones debug dump in {self.debug_dir}")
                    except Exception as de:
                        self.log(f"Milestones debug save error: {de}")
                ms = self._extract_milestones()
                if ms: break
            if ms:
                latest_text = self._pick_latest_milestone(ms)
                fields["Milestones"] = latest_text
                self.log(f"Latest milestone: {latest_text[:200]}")
            else:
                self.log("No milestones found.")
        except Exception as e:
            self.log(f"Milestones extraction error: {e}")

        # Latitude / Longitude — out-of-the-box: scan RAW HTML + iframe srcs + JSON state
        try:
            lat = lon = None

            def _try(text):
                if not text: return None, None
                # 1) Standard label-based pair (full precision)
                m = re.search(
                    r"latitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})[^\d+\-]+longitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})",
                    text, re.IGNORECASE)
                if m: return m.group(1), m.group(2)
                # 2) Reversed order (lng first)
                m = re.search(
                    r"longitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})[^\d+\-]+latitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})",
                    text, re.IGNORECASE)
                if m: return m.group(2), m.group(1)
                # 3) Single labels split anywhere
                la = re.search(r"latitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})", text, re.IGNORECASE)
                lo = re.search(r"longitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})", text, re.IGNORECASE)
                if la and lo: return la.group(1), lo.group(1)
                # 4) JSON-style: "lat":-23.44, "lng":-70.08 (or lon, longitude)
                m = re.search(
                    r"[\"']lat(?:itude)?[\"']\s*:\s*([+-]?\d+\.\d{2,})[^\d]+[\"']l(?:o?n|ong|ongitude)[\"']\s*:\s*([+-]?\d+\.\d{2,})",
                    text)
                if m: return m.group(1), m.group(2)
                # 5) HTML data-attributes: data-lat="X" data-lng="Y"
                la2 = re.search(r"data-l(?:at|atitude)\s*=\s*[\"']([+-]?\d+\.\d{2,})[\"']", text, re.IGNORECASE)
                lo2 = re.search(r"data-l(?:ng|on|ongitude)\s*=\s*[\"']([+-]?\d+\.\d{2,})[\"']", text, re.IGNORECASE)
                if la2 and lo2: return la2.group(1), lo2.group(1)
                # 6) Google Maps URL pattern: q=lat,lng or center=lat,lng or @lat,lng,
                m = re.search(r"(?:[?&](?:q|center|ll)=|@)([+-]?\d{1,3}\.\d{2,}),\s*([+-]?\d{1,3}\.\d{2,})", text)
                if m:
                    a, b = float(m.group(1)), float(m.group(2))
                    if -90 <= a <= 90 and -180 <= b <= 180:
                        return m.group(1), m.group(2)
                # 7) MapBox marker / pin pattern: pin-s+ff0000(lng,lat)
                m = re.search(r"\(([+-]?\d{1,3}\.\d{2,}),([+-]?\d{1,3}\.\d{2,})\)", text)
                if m:
                    # MapBox is lng,lat
                    a, b = float(m.group(1)), float(m.group(2))
                    if -180 <= a <= 180 and -90 <= b <= 90:
                        return m.group(2), m.group(1)
                return None, None

            # Strategy: navigate to Map tab, click 'View Map', then click the star/marker
            # for the main project to open a tooltip containing the coordinates.
            try:
                map_url = _ensure_tab(url, "map")
                self._page.goto(map_url, wait_until="domcontentloaded", timeout=30000)
                try: self._page.wait_for_load_state("networkidle", timeout=20000)
                except Exception: pass
                self._page.wait_for_timeout(1500)
                # Click 'View Map' / 'Ver mapa' button
                for vsel in ("button:has-text('View on map')", "button:has-text('View Map')",
                             "a:has-text('View on map')", "a:has-text('View Map')",
                             "button:has-text('Ver mapa')", "a:has-text('Ver mapa')",
                             "button:has-text('Ver no mapa')"):
                    try:
                        v = self._page.locator(vsel).first
                        if v.count() > 0 and v.is_visible(timeout=1500):
                            v.click(timeout=3000)
                            self._page.wait_for_timeout(1500)
                            self.log(f"Clicked: {vsel}")
                            break
                    except Exception: continue
                # Wait for map markers to render
                self._page.wait_for_timeout(2000)
                # Click the main project star/marker. Try several common selectors.
                for msel in ("[aria-label*='Main project' i]", "[title*='Main project' i]",
                             "img[src*='star' i]", "img[alt*='star' i]",
                             "[class*='main-marker' i]", "[class*='main-project' i]",
                             "[class*='star' i]",
                             "svg [class*='star' i]",
                             "button[aria-label*='star' i]",
                             ".leaflet-marker-icon", "[role='button'][aria-label*='project' i]"):
                    try:
                        marker = self._page.locator(msel).first
                        if marker.count() > 0:
                            marker.click(timeout=3000, force=True)
                            self._page.wait_for_timeout(1500)
                            self.log(f"Clicked marker: {msel}")
                            break
                    except Exception: continue
                self._page.wait_for_timeout(800)
            except Exception as e:
                self.log(f"Map click sequence error: {e}")

            sources = []
            # Source 0: captured JSON blobs from XHR responses (most reliable)
            try:
                for u, body in (self._json_blobs or []):
                    sources.append((f"xhr:{u[-60:]}", body))
            except Exception: pass
            # Source A: raw HTML of currently-loaded page
            try: sources.append(("current_html", self._page.content()))
            except Exception: pass
            # Source B: inner_text fallback
            try: sources.append(("current_text", self._page.inner_text("body")))
            except Exception: pass
            # Source C: iframe srcs
            try:
                ifr = self._page.evaluate("() => Array.from(document.querySelectorAll('iframe')).map(i => i.src).join('|')")
                if ifr: sources.append(("iframes", ifr))
            except Exception: pass
            # Source D: window JSON state (Vue/React often stash it)
            try:
                state = self._page.evaluate("() => JSON.stringify(window.__INITIAL_STATE__||window.__NUXT__||window.__APOLLO_STATE__||{})")
                if state and len(state) > 5: sources.append(("win_state", state))
            except Exception: pass


            for name, txt in sources:
                lat, lon = _try(txt)
                if lat and lon:
                    self.log(f"Lat/Lon found via {name}: {lat}, {lon}")
                    break

            if not (lat and lon):
                for slug in ("map", "location", "general"):
                    if lat and lon: break
                    try:
                        map_url = _ensure_tab(url, slug)
                        self.log(f"Loading {slug} for lat/lon: {map_url}")
                        self._page.goto(map_url, wait_until="domcontentloaded", timeout=30000)
                        try: self._page.wait_for_load_state("networkidle", timeout=20000)
                        except Exception: pass
                        self._page.wait_for_timeout(1500)
                        self._scroll(steps=4, pause=400)
                        for source in (self._page.content(), self._page.inner_text("body")):
                            lat, lon = _try(source)
                            if lat and lon:
                                self.log(f"Lat/Lon found on {slug}: {lat}, {lon}")
                                break
                    except Exception as e:
                        self.log(f"Map ({slug}) error: {e}")

            if lat and lon:
                fields["Latitude"] = lat
                fields["Longitude"] = lon
                fields["Coordinates"] = f"{lat}, {lon}"
                self.log(f"Coordinates: {fields['Coordinates']}")
            else:
                self.log("Latitude/Longitude not found anywhere.")
        except Exception as e:
            self.log(f"Map extraction error: {e}")

        # Schedule tab — date precedes label in the timeline UI
        try:
            sch_url = _ensure_tab(url, "schedule")
            self.log(f"Loading Schedule: {sch_url}")
            self._page.goto(sch_url, wait_until="domcontentloaded", timeout=30000)
            try: self._page.wait_for_load_state("networkidle", timeout=20000)
            except Exception: pass
            self._page.wait_for_timeout(1500)
            self._scroll(steps=6, pause=400)
            sch_text = self._page.inner_text("body")
            # Strip badge tokens (ESTIMATED/MAIN/CONFIRMED/...) that BNA
            # renders inline as colored chips. They show up two ways:
            #  1) Full word glued / on its own line: "AUGUST 2025ESTIMATED"
            #  2) Single uppercase initial glued to year: "AUGUST 2025E"
            # Both must be removed before the date<->label regex runs.
            BADGE_RE = r"(?:ESTIMATED|MAIN|CONFIRMED|UPDATED|PROPOSED|PRELIMINARY|TARGET|PRIMARY|SECONDARY|EXPECTED)\b"
            sch_text = re.sub(BADGE_RE, " ", sch_text)
            # Strip ANY uppercase-letter run sitting between a 4-digit year
            # and end-of-line (catches the single-letter "E" badge).
            sch_text = re.sub(r"(\d{4})[A-Z]+(?=\s*$)", r"\1",
                              sch_text, flags=re.MULTILINE)
            sch_text = re.sub(r"[ \t]+", " ", sch_text)
            sch_text = re.sub(r" *\n *", "\n", sch_text)
            sch_text = re.sub(r"\n{2,}", "\n", sch_text)
            # Each schedule field has en/es/pt aliases. We try every alias
            # and store under the canonical English key.
            # NOTE: PT labels on BNA use "da" (not "de") and use
            # "empreiteiro" / "detalhamento" — match what the platform
            # actually renders, not what a translator might guess.
            schedule_aliases = {
                "Project Announced": [
                    "Project Announced", "Proyecto Anunciado",
                    "Projeto Anunciado"],
                "Start of Operation": [
                    "Start of Operation",
                    "Inicio de Operación", "Inicio de la Operación",
                    "Início da Operação", "Início de Operação"],
                "End of Operation": [
                    "End of Operation",
                    "Fin de Operación",
                    "Fim da Operação", "Fim de Operação"],
                "Start of Construction": [
                    "Start of Construction",
                    "Inicio de Construcción", "Inicio de la Construcción",
                    "Início da Construção", "Início de Construção"],
                "End of Construction": [
                    "End of Construction",
                    "Fin de Construcción",
                    "Fim da Construção", "Fim de Construção"],
                "Start of Main Contractor Tendering": [
                    "Start of Main Contractor Tendering",
                    "Inicio de Licitación de Contratista Principal",
                    "Inicio de Licitación del Contratista Principal",
                    "Início da Licitação do Empreiteiro Principal",
                    "Início de Licitação do Empreiteiro Principal",
                    "Início da Licitação do Contratante Principal",
                    "Início de Licitação do Contratante Principal"],
                "Start of Detailed Engineering": [
                    "Start of Detailed Engineering",
                    "Inicio de Ingeniería Detallada",
                    "Inicio de ingeniería de detalle",
                    "Inicio de Ingeniería de Detalle",
                    "Início da Engenharia de Detalhamento",
                    "Início de Engenharia de Detalhamento",
                    "Início da Engenharia Detalhada",
                    "Início de Engenharia Detalhada",
                    "Início da Engenharia de Detalhe",
                    "Início de Engenharia de Detalhe"],
                "Environmental and Social Approval": [
                    "Environmental and Social Approval",
                    "Aprobación Ambiental y Social",
                    "Aprovação Ambiental e Social"],
            }
            # Persist schedule snapshot for diagnostics
            if self.debug_dir:
                try:
                    os.makedirs(self.debug_dir, exist_ok=True)
                    with open(os.path.join(self.debug_dir, "schedule_text.txt"),
                             "w", encoding="utf-8") as f:
                        f.write(sch_text or "")
                except Exception: pass
            # 'Not yet disclosed' equivalents in EN/ES/PT — used to mark a
            # schedule date as explicitly unset (not assigned to next row).
            unset_token = (r"NOT\s+YET\s+DISCLOSED|NOT\s+DISCLOSED|"
                           r"A[úu]n\s+no\s+divulgado|A[úu]n\s+no\s+publicado|"
                           r"No\s+divulgado|No\s+publicado|"
                           r"Ainda\s+n[ãa]o\s+divulgado|N[ãa]o\s+divulgado|"
                           r"TBD|N\/A")
            date_token = (rf"(?:{unset_token}|"
                          r"[A-Za-zÀ-ÿ]+\s+\d{4}|"
                          r"\d{1,2}[/\.\-]\d{1,2}[/\.\-]\d{2,4}|"
                          r"\d{4}-\d{2}-\d{2})")
            unset_re = re.compile(rf"^(?:{unset_token})$", re.IGNORECASE)
            for canonical, aliases in schedule_aliases.items():
                found = False
                for label in aliases:
                    # ONLY date-then-label is reliable on BNA's Schedule tab.
                    # The previous label-then-date fallback was too greedy:
                    # when a field had 'Aún no divulgado' (no date), it
                    # picked up the NEXT field's date and mis-assigned it.
                    pat = rf"(?mi)^\s*({date_token})\s*\n\s*{re.escape(label)}\b"
                    m = re.search(pat, sch_text)
                    if not m: continue
                    val = m.group(1).strip()
                    if unset_re.fullmatch(val):
                        # Explicitly marked unset — leave this field blank.
                        found = True; break
                    fields[canonical] = val
                    self.log(f"Schedule {canonical}: {val}")
                    found = True; break
                if found: continue
        except Exception as e:
            self.log(f"Schedule extraction error: {e}")

        # General tab
        try:
            gen_url = _ensure_tab(url, "general")
            self.log(f"Loading General: {gen_url}")
            self._page.goto(gen_url, wait_until="domcontentloaded", timeout=30000)
            try: self._page.wait_for_load_state("networkidle", timeout=20000)
            except Exception: pass
            self._page.wait_for_timeout(1500)
            self._scroll(steps=6, pause=400)
            # Always save a snapshot of the General tab for diagnostics
            if self.debug_dir:
                try:
                    os.makedirs(self.debug_dir, exist_ok=True)
                    with open(os.path.join(self.debug_dir, "general_page.html"),
                             "w", encoding="utf-8") as f:
                        f.write(self._page.content() or "")
                    with open(os.path.join(self.debug_dir, "general_text.txt"),
                             "w", encoding="utf-8") as f:
                        f.write(self._page.inner_text("body") or "")
                except Exception: pass
            text = self._page.inner_text("body")
            # Strip inline badge tokens (ESTIMATED/MAIN/...) so they don't
            # corrupt extracted values like Capex "102.4 US$ mnESTIMATED".
            # Case-sensitive ALL-CAPS match (see Schedule tab for rationale).
            text = re.sub(
                r"(?:ESTIMATED|MAIN|CONFIRMED|UPDATED|PROPOSED|PRELIMINARY|TARGET|PRIMARY|SECONDARY|EXPECTED)\b",
                " ", text)
            # Single-letter badge initial glued to a 4-digit year ('2025E')
            text = re.sub(r"(\d{4})[A-Z]+(?=\s*$)", r"\1",
                          text, flags=re.MULTILINE)
            text = re.sub(r"[ \t]+", " ", text)
            text = re.sub(r" *\n *", "\n", text)
            text = re.sub(r"\n{2,}", "\n", text)
            # Multilingual label aliases — each English target field maps to a
            # set of equivalent labels (English / Spanish / Portuguese) BNA may
            # render. The scraper finds whichever variant the page is using.
            label_aliases = {
                "Capex": ("Capex", "CAPEX"),
                "Lifespan": ("Lifespan", "Vida útil", "Vida util",
                             "Tempo de vida", "Tempo de Vida"),
                "Development type": ("Development type", "Tipo de desarrollo",
                                     "Tipo de desenvolvimento"),
                "Property Type": ("Property Type", "Tipo de propiedad",
                                  "Tipo de propriedade"),
                "Current stage": ("Current stage", "Etapa actual", "Etapa atual",
                                  "Fase actual", "Fase atual"),
                "Last expert review": ("Last expert review", "Última Revisión Experta",
                                       "Última Revisão Especializada", "Última Revisão",
                                       "Última revisão de especialistas"),
                "Latitude": ("Latitude", "Latitud"),
                "Longitude": ("Longitude", "Longitud"),
            }
            # BNA renders inline badges (ESTIMATED/ESTIMADO/CONFIRMED/...)
            # glued to numeric values, e.g. "215 US$ mnESTIMADO". Strip
            # them so downstream comparison sees just the value.
            GEN_BADGE_RE = re.compile(
                r"\s*(?:ESTIMATED|ESTIMADO|CONFIRMED|CONFIRMADO|UPDATED|ATUALIZADO|"
                r"PROPOSED|PROPUESTO|PROPOSTO|PRELIMINARY|PRELIMINAR|TARGET|META|"
                r"PRIMARY|SECONDARY|EXPECTED|PRINCIPAL)\b\s*$",
                re.IGNORECASE)
            for canonical, aliases in label_aliases.items():
                for label in aliases:
                    m = re.search(
                        rf"(?mi)^{re.escape(label)}\s*[:\n]\s*([^\n]+(?:\n[^\n]+){{0,2}})",
                        text)
                    if m:
                        val = m.group(1).strip().split("\n\n")[0].strip().split("\n")[0].strip()
                        # Strip trailing badge token glued to numeric value
                        val = GEN_BADGE_RE.sub("", val).strip()
                        fields[canonical] = val
                        break
            mc = re.search(
                r"(?ims)\b(?:Project\s+Type\s+and\s+capacity|Tipo\s+y\s+capacidad\s+del\s+proyecto|Tipo\s+de\s+proyecto\s+y\s+capacidad|Tipo\s+e\s+capacidade\s+do\s+projeto|Tipo\s+de\s+projeto\s+e\s+capacidade)\b\s*[:\n]\s*(.+?)(?=\n\s*(?:Topics|Temas|T[óo]picos|Property\s+Type|Tipo\s+de\s+propiedad|Tipo\s+de\s+propriedade|Map|Mapa|Companies|Compañ[ií]as|Empresas|Description|Descripci[óo]n|Descri[çc][ãa]o|Schedule|Cronograma)\b)",
                text)
            if mc:
                fields["Project Type and capacity"] = re.sub(r"\s+", " ", mc.group(1)).strip()
            try:
                page_html = self._page.content() or ""
                section = re.search(
                    r"(?is)(?:Project\s+Type\s+and\s+capacity|Tipo\s+y\s+capacidad\s+del\s+proyecto|Tipo\s+de\s+proyecto\s+y\s+capacidad|Tipo\s+e\s+capacidade\s+do\s+projeto|Tipo\s+de\s+projeto\s+e\s+capacidade)[\s\S]{0,80}?(<div[\s\S]*?)(?:<h3|<div[^>]+id=\"map\"|Topics|Temas|T[óo]picos)",
                    page_html)
                if section:
                    chunk = section.group(1)
                    raw_items = re.findall(
                        r"<p[^>]*class=\"[^\"]*mb-0[^\"]*\"[^>]*>([\s\S]*?)</p>",
                        chunk)
                    items = []
                    for raw in raw_items:
                        # Strip BNA's badge spans. Multiple class signatures
                        # are used: badge / pill / tag / chip / label
                        # (generic) AND 'icon-status main-project-type'
                        # (the 'Principal' marker on the primary project
                        # type entry). Catch them all.
                        x = re.sub(
                            r"<span[^>]*class=\"[^\"]*(?:badge|pill|tag-pill|chip|label|icon-status|main-project-type)[^\"]*\"[^>]*>[\s\S]*?</span>",
                            " ", raw, flags=re.IGNORECASE)
                        x = re.sub(r"<[^>]+>", " ", x)
                        x = re.sub(
                            r"\b(?:main|estimated|confirmed|updated|proposed|preliminary|target|primary|secondary|expected)\b",
                            " ", x, flags=re.IGNORECASE)
                        # Strip a trailing 'Principal' word that may have
                        # leaked through inner_text without HTML markup.
                        x = re.sub(r"\s+Principal\s*$", "", x)
                        x = re.sub(r"\s+", " ", x).strip()
                        if x: items.append(x)
                    project_types = []
                    capacities = []
                    for it in items:
                        m = re.search(r"\d", it)
                        if not m:
                            project_types.append(it); continue
                        name_part = it[:m.start()].strip(" ,;:-")
                        cap_part  = it[m.start():].strip()
                        if name_part: project_types.append(name_part)
                        if cap_part:  capacities.append(cap_part)
                    def _dedupe(seq):
                        seen = set(); out = []
                        for x in seq:
                            k = re.sub(r"\s+", " ", x.lower()).strip()
                            if k and k not in seen:
                                seen.add(k); out.append(x)
                        return out
                    project_types = _dedupe(project_types)
                    capacities    = _dedupe(capacities)
                    if project_types:
                        fields["Project Type"] = ", ".join(project_types)
                    if capacities:
                        fields["Capacity"] = ", ".join(capacities)
                    self.log(f"Project Type items: {project_types}")
                    self.log(f"Capacity items: {capacities}")
            except Exception as e:
                self.log(f"Project Type/Capacity split error: {e}")
            stop_words = (
                "Property Type", "Tipo de propiedad", "Tipo de propriedade",
                "Project Type and capacity", "Tipo y capacidad del proyecto",
                "Tipo de proyecto y capacidad", "Tipo e capacidade do projeto",
                "Tipo de projeto e capacidade",
                "Capex",
                "Lifespan", "Vida útil", "Tempo de vida",
                "Development type", "Tipo de desarrollo", "Tipo de desenvolvimento",
                "Current stage", "Etapa actual", "Etapa atual",
                "Fase actual", "Fase atual",
                "Last expert review", "Última Revisión", "Última Revisão",
                "Última revisão de especialistas",
                "Topics", "Temas", "Tópicos",
                "Principal works", "Obras principales", "Obras principais",
                "Trabalhos principais", "Trabalhos Principais",
                "Latitude", "Latitud", "Longitude", "Longitud",
                "Map", "Mapa",
                "Companies", "Compañías", "Compañias", "Empresas",
            )
            stop_re = "|".join(re.escape(s) for s in stop_words)
            md = re.search(
                rf"(?ims)\b(?:Description|Descripción|Descrição)\b\s*[:\n]\s*(.+?)(?:\n\s*(?:{stop_re})\b)",
                text)
            if md:
                desc = re.sub(r"\n{2,}", "\n\n", md.group(1).strip())
                fields["Description"] = desc
        except Exception as e:
            self.log(f"General extraction error: {e}")

        # Principal works tab
        try:
            for slug in ("products-services-principal-works", "products-services", "principal-works",
                         "productos-servicios-obras-principales", "productos-servicios",
                         "produtos-servicos-obras-principais",
                         "produtos-servicos-e-obras-principais",
                         "produtos-e-servicos-obras-principais",
                         "produtos-servicos", "trabalhos-principais"):
                pw_url = _ensure_tab(url, slug)
                self.log(f"Loading Principal Works: {pw_url}")
                self._page.goto(pw_url, wait_until="domcontentloaded", timeout=30000)
                try: self._page.wait_for_load_state("networkidle", timeout=20000)
                except Exception: pass
                self._page.wait_for_timeout(1500)
                self._scroll(steps=8, pause=500)
                pw_text = self._page.inner_text("body")
                pw_match = (
                    "Principal works" in pw_text or "Principal Works" in pw_text
                    or "Obras principales" in pw_text or "Obras Principales" in pw_text
                    or "Obras principais" in pw_text or "Obras Principais" in pw_text
                    or "Trabalhos principais" in pw_text or "Trabalhos Principais" in pw_text
                    or "Principales Trabajos" in pw_text or "Principales trabajos" in pw_text
                    or "Trabajos Principales" in pw_text or "Trabajos principales" in pw_text
                )
                if pw_match:
                    stop_words = ("Disclaimer", "Exención de Responsabilidad", "Isenção",
                                  "Products and services", "Products & services",
                                  "Productos y servicios", "Productos, servicios",
                                  "Produtos e serviços",
                                  "Topics", "Temas", "Tópicos",
                                  "Companies", "Compañías", "Compañias",
                                  "Schedule", "Cronograma",
                                  "Map", "Mapa",
                                  "Documents", "Documentos")
                    stop_re = "|".join(re.escape(s) for s in stop_words)
                    # Words that look like content but are actually nav /
                    # tab labels on BNA. If a chunk is mostly these, the
                    # Principal Works section is effectively empty.
                    NAV_WORDS = {
                        "notes", "notas", "general", "general ",
                        "principal works", "obras principales", "obras principais",
                        "trabalhos principais", "principales trabajos",
                        "trabajos principales",
                        "products and services", "products & services",
                        "productos y servicios", "productos, servicios",
                        "productos, servicios y obras principales",
                        "produtos e serviços", "produtos e servicos",
                        "products, services & principal works",
                        "schedule", "cronograma", "map", "mapa",
                        "companies", "compañías", "compañias", "empresas",
                        "companies & contacts", "compañías y contactos",
                        "compañías y contactos",
                        "empresas e contatos",
                        "milestones, news & reports", "milestones",
                        "hitos, noticias y reportes", "hitos",
                        "marcos, noticias", "marcos, notícias",
                        "documents", "documentos",
                        "description", "descripción", "descrição",
                    }

                    def _strip_nav_lines(chunk):
                        """Remove lines anywhere in the chunk that are
                        exact matches of nav words, then collapse blank
                        runs. Keeps real content."""
                        out_lines = []
                        for ln in chunk.splitlines():
                            if ln.strip().lower() in NAV_WORDS: continue
                            out_lines.append(ln)
                        cleaned = "\n".join(out_lines)
                        cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
                        return cleaned.strip(" :\n\t")

                    def _is_meaningful(chunk):
                        """Drop chunks that are just nav / tab names or are
                        too short to plausibly describe principal works."""
                        if not chunk or not chunk.strip(): return False
                        cleaned = _strip_nav_lines(chunk)
                        if len(cleaned) < 30: return False
                        words = re.findall(r"[A-Za-zÀ-ÿ]{2,}", cleaned)
                        return len(words) >= 5

                    candidates = []
                    for hm in re.finditer(
                            r"(?im)\b(?:Principal\s+[Ww]orks|Obras\s+[Pp]rincipales|Obras\s+[Pp]rincipais|Trabalhos\s+[Pp]rincipais|Principales\s+[Tt]rabajos|Trabajos\s+[Pp]rincipales)\b",
                            pw_text):
                        start = hm.end()
                        rest = pw_text[start:]
                        cut = re.search(rf"(?ims)\n\s*(?:{stop_re})\b", rest)
                        chunk = rest[:cut.start()] if cut else rest
                        chunk = chunk.strip(" :\n\t")
                        if chunk and not re.match(rf"(?i)^(?:{stop_re}|Products\s+and\s+services|Productos\s+y\s+servicios|Produtos\s+e\s+serviços)\b", chunk):
                            if _is_meaningful(chunk):
                                candidates.append(chunk)
                    if candidates:
                        body = max(candidates, key=len)
                        # Strip nav prefix lines from the final body too.
                        body = _strip_nav_lines(body)
                        if body:
                            fields["Principal works"] = body
                            self.log(f"Principal works captured: {len(body)} chars")
                            break
                    # ---- HTML <ul><li>...</li></ul> bullet fallback ----
                    # Some projects render Principal Works as bullet lists
                    # only — the inner_text path collapses them oddly and
                    # the regex misses them. Scan the page HTML for any
                    # <ul> sitting after a Principal Works heading and
                    # pull the <li> items.
                    try:
                        pw_html = self._page.content() or ""
                    except Exception:
                        pw_html = ""
                    if pw_html:
                        head_re = (r'(?is)<h\d[^>]*>\s*'
                                   r'(?:Principal\s+[Ww]orks|Obras\s+[Pp]rincipales|'
                                   r'Obras\s+[Pp]rincipais|Trabalhos\s+[Pp]rincipais|'
                                   r'Principales\s+[Tt]rabajos|Trabajos\s+[Pp]rincipales)'
                                   r'\s*</h\d>')
                        head_m = re.search(head_re, pw_html)
                        scan_from = head_m.end() if head_m else 0
                        chunk = pw_html[scan_from:]
                        ul_match = re.search(r"(?is)<ul[^>]*>([\s\S]*?)</ul>", chunk)
                        if ul_match:
                            ul_html = ul_match.group(1)
                            items = re.findall(r"(?is)<li[^>]*>([\s\S]*?)</li>", ul_html)
                            cleaned_items = []
                            for it in items:
                                text_only = re.sub(r"<[^>]+>", " ", it)
                                text_only = re.sub(r"\s+", " ", text_only).strip()
                                if text_only and len(text_only) >= 2:
                                    cleaned_items.append(text_only)
                            if cleaned_items:
                                body = "\n".join(cleaned_items)
                                fields["Principal works"] = body
                                self.log(f"Principal works (bullet path): {len(cleaned_items)} items")
                                break
        except Exception as e:
            self.log(f"Principal works extraction error: {e}")
        if not fields:
            self.log("No fields extracted. Saving debug dump.")
            self._save_debug()
        if self.debug_dir:
            try:
                os.makedirs(self.debug_dir, exist_ok=True)
                with open(os.path.join(self.debug_dir, "all_bna_fields.txt"),
                         "w", encoding="utf-8") as f:
                    f.write(f"Total fields: {len(fields)}\n\n")
                    for k in sorted(fields.keys()):
                        v = fields[k]
                        if isinstance(v, list):
                            v_str = "[" + ", ".join(repr(x) for x in v) + "]"
                        else:
                            v_str = repr(v)
                        if len(v_str) > 1000:
                            v_str = v_str[:1000] + f"... (+{len(v_str)-1000} chars)"
                        f.write(f"{k}: {v_str}\n")
            except Exception as e:
                self.log(f"all_bna_fields dump failed: {e}")
        self.log(f"Total normalized BNA fields: {len(fields)}")
        return fields

    def _save_debug(self):
        try:
            if not self.debug_dir:
                self.debug_dir = os.path.join(os.getcwd(), "debug")
            os.makedirs(self.debug_dir, exist_ok=True)
            with open(os.path.join(self.debug_dir, "page.html"), "w", encoding="utf-8") as f:
                f.write(self._page.content() or "")
            with open(os.path.join(self.debug_dir, "page_text.txt"), "w", encoding="utf-8") as f:
                f.write(self._page.inner_text("body") or "")
        except Exception as e:
            self.log(f"debug dump error: {e}")