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
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
"""BNA Comparator -- Web Edition."""
from __future__ import annotations

import io
import json
import os
import re
import subprocess
import sys
import tempfile
import threading
import time
import uuid
import zipfile
from datetime import datetime
from pathlib import Path

import streamlit as st

# Add engine folder to sys.path so we can import team_session for the
# Admin tab. batch_runner already runs from inside engine/ as a
# subprocess, so this is only needed for the in-process UI handler.
_ENGINE_DIR = Path(__file__).resolve().parent / "engine"
if str(_ENGINE_DIR) not in sys.path:
    sys.path.insert(0, str(_ENGINE_DIR))
import team_session  # noqa: E402
import feedback_store  # noqa: E402


# -------------------------------------------------------------------
# Run queue β€” single process-wide queue so concurrent researcher
# clicks serialize cleanly. Streamlit runs all sessions in one Python
# process, so a module-level threading.Lock + list is sufficient.
# -------------------------------------------------------------------
_QUEUE_LOCK = threading.Lock()
_QUEUE: list[dict] = []  # [{"id": str, "started": bool}]


def queue_enqueue(sid: str) -> None:
    with _QUEUE_LOCK:
        if not any(q["id"] == sid for q in _QUEUE):
            _QUEUE.append({"id": sid, "started": False})


def queue_position(sid: str) -> int:
    """0 = my turn now. N>0 = N batches ahead. -1 = not in queue."""
    with _QUEUE_LOCK:
        for i, q in enumerate(_QUEUE):
            if q["id"] == sid:
                return i
        return -1


def queue_mark_started(sid: str) -> None:
    with _QUEUE_LOCK:
        for q in _QUEUE:
            if q["id"] == sid:
                q["started"] = True
                return


def queue_dequeue(sid: str) -> None:
    with _QUEUE_LOCK:
        _QUEUE[:] = [q for q in _QUEUE if q["id"] != sid]

HERE = Path(__file__).resolve().parent


st.set_page_config(
    page_title="BNA vs AI -- Batch",
    page_icon="🧭",
    layout="wide",
    initial_sidebar_state="collapsed",
)


CSS = """
<style>
  #MainMenu, footer, header[data-testid="stHeader"] {visibility: hidden;}
  [data-testid="stToolbar"] {display: none;}
  .block-container {padding-top: 0 !important; max-width: 1200px; background: #FFFFFF;}
  body, .stApp {background: #FFFFFF !important;}

  .bna-header {
    background: linear-gradient(90deg, #2541B2 0%, #6B3FA0 60%, #8338EC 100%);
    color: #FFFFFF; padding: 28px 36px; border-radius: 0 0 8px 8px;
    margin: 0 -24px 24px -24px;
    display: flex; align-items: center; gap: 18px;
  }
  .bna-header .icon {
    width: 44px; height: 44px;
    background: rgba(255,255,255,0.18); border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 22px;
  }
  .bna-header h1 {margin: 0; font-size: 30px; font-weight: 700; line-height: 1.1;}
  .bna-header p {margin: 4px 0 0 0; font-size: 14px; opacity: 0.92;}

  .stTabs [data-baseweb="tab-list"] {
    gap: 8px; border-bottom: 2px solid #E5E7EB; background: #FFFFFF; padding: 0 12px;
  }
  .stTabs [data-baseweb="tab"] {
    height: 56px !important; padding: 0 32px !important;
    background: transparent; border-radius: 8px 8px 0 0;
    color: #4B5563 !important; font-weight: 600 !important; font-size: 17px !important;
  }
  .stTabs [data-baseweb="tab"] p {font-size: 17px !important; font-weight: 600 !important;}
  .stTabs [aria-selected="true"] {
    color: #2541B2 !important; border-bottom: 4px solid #2541B2 !important; background: #F8FAFC !important;
  }

  [data-testid="stVerticalBlock"] > [data-testid="stVerticalBlockBorderWrapper"] {
    background: #FFFFFF; border: 1px solid #E5E7EB; border-radius: 10px;
    padding: 26px 32px !important; box-shadow: 0 1px 3px rgba(0,0,0,0.04);
  }

  .stTextInput input, .stSelectbox > div > div, .stFileUploader section {
    background: #FFFFFF !important; color: #111827 !important;
    border: 1px solid #D1D5DB !important; border-radius: 6px !important;
  }
  .stTextInput input::placeholder {color: #9CA3AF !important;}
  .stTextInput label, .stSelectbox label, .stFileUploader label, .field-label {
    color: #111827 !important; font-weight: 500 !important;
  }
  .field-label {font-size: 14px; padding-top: 10px;}

  h2.section-title {
    font-size: 20px; margin: 0 0 18px 0; color: #1F2937;
    display: flex; align-items: center; gap: 8px;
  }
  h2.section-title .gear {color: #2541B2;}

  /* ── Run batch (primary) ── orange ─────────────────────────────── */
  div.stButton > button[kind="primary"] {
    background: linear-gradient(180deg, #F97316 0%, #EA580C 100%) !important;
    color: white !important; border: none !important; font-weight: 600 !important;
    padding: 10px 22px !important; border-radius: 8px !important;
  }
  div.stButton > button[kind="primary"]:hover:not(:disabled) {
    background: linear-gradient(180deg, #EA580C 0%, #C2410C 100%) !important;
  }
  div.stButton > button[kind="primary"]:disabled {
    background: #F3F4F6 !important; color: #9CA3AF !important;
  }
  /* ── Download results ZIP ── BNAmericas blue ───────────────────── */
  div.stDownloadButton > button {
    background: linear-gradient(180deg, #2541B2 0%, #1E3A8A 100%) !important;
    color: #FFFFFF !important; border: none !important; font-weight: 600 !important;
    padding: 10px 22px !important; border-radius: 8px !important;
  }
  div.stDownloadButton > button:hover:not(:disabled) {
    background: linear-gradient(180deg, #1E3A8A 0%, #172554 100%) !important;
  }
  div.stDownloadButton > button:disabled,
  div.stButton > button:disabled[data-testid='btn_download_disabled'] {
    background: #E5E7EB !important; color: #9CA3AF !important;
  }
  /* ── Clear ── light-grey fill ──────────────────────────────────── */
  div.stButton > button:not([kind="primary"]) {
    background: #E5E7EB !important; color: #374151 !important;
    border: 1px solid #D1D5DB !important;
    font-weight: 500 !important; padding: 10px 22px !important; border-radius: 8px !important;
  }
  div.stButton > button:not([kind="primary"]):hover:not(:disabled) {
    background: #D1D5DB !important; color: #111827 !important;
    border-color: #9CA3AF !important;
  }
  div.stButton > button:not([kind="primary"]):disabled {
    background: #F3F4F6 !important; color: #9CA3AF !important;
    border: 1px solid #E5E7EB !important;
  }

  /* Status banners under the action row */
  .status-banner {
    margin-top: 18px; padding: 14px 18px; border-radius: 10px;
    display: flex; align-items: center; gap: 12px; font-size: 14px;
  }
  .status-banner .icon {font-size: 18px;}
  .status-banner.running {
    background: linear-gradient(90deg, #EFF6FF 0%, #F5F3FF 100%);
    border: 1px solid #C7D2FE; color: #3730A3;
  }
  .status-banner.success {
    background: linear-gradient(90deg, #ECFDF5 0%, #F0FDF4 100%);
    border: 1px solid #A7F3D0; color: #065F46;
  }
  .status-banner.error {
    background: #FEF2F2; border: 1px solid #FECACA; color: #991B1B;
  }
  .status-banner b {font-weight: 600;}
  .pulse-dot {
    width: 10px; height: 10px; border-radius: 50%; background: #4F46E5;
    animation: pulse 1.4s infinite;
  }
  @keyframes pulse {
    0%, 100% {opacity: 1; transform: scale(1);}
    50% {opacity: 0.4; transform: scale(1.3);}
  }

  .kpi-tile {
    background: #FFFFFF; border: 1px solid #E5E7EB; border-left: 4px solid #2541B2;
    border-radius: 8px; padding: 16px 18px; margin-bottom: 12px;
  }
  .kpi-tile .label {color: #6B7280; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em;}
  .kpi-tile .value {color: #111827; font-size: 28px; font-weight: 600; margin-top: 4px;}
  .kpi-tile.match {border-left-color: #16A34A;}
  .kpi-tile.differ {border-left-color: #F59E0B;}
  .kpi-tile.stale {border-left-color: #8B5CF6;}
  .kpi-tile.missing {border-left-color: #6B7280;}

  .stProgress > div > div > div {background: linear-gradient(90deg, #2541B2, #8338EC) !important;}

  /* Streamlit shows a "Press Enter to apply" hint next to text inputs
     whenever the value changes. It looks like an error tooltip and
     confuses non-technical users. Hide it. */
  [data-testid="InputInstructions"] {display: none !important;}
  [data-testid="stTextInput"] [data-baseweb="input"] + div {display: none !important;}

  /* --- Connection gate (3-tier) -------------------------------------- */
  .gate-title {color: #1E3A8A; font-size: 22px; font-weight: 600;
               margin: 4px 0 4px 0; display: flex; align-items: center; gap: 10px;}
  .gate-sub {color: #6B7280; font-size: 13px; margin: 0 0 20px 0;}

  .tier-card {
    background: #FFFFFF; border: 1px solid #E5E7EB;
    border-radius: 10px; padding: 16px 18px; margin-bottom: 14px;
    display: flex; align-items: flex-start; gap: 14px;
  }
  .tier-card.primary {background: linear-gradient(90deg, #EFF6FF 0%, #F5F3FF 100%);
                      border-color: #C7D2FE;}
  .tier-icon {font-size: 22px; flex-shrink: 0; line-height: 1.2;
              width: 36px; height: 36px; border-radius: 8px;
              display: flex; align-items: center; justify-content: center;
              background: rgba(255,255,255,0.6);}
  .tier-card.primary .tier-icon {color: #3730A3;}
  .tier-card .tier-body {flex: 1;}
  .tier-card h4 {margin: 0 0 4px 0; font-size: 15px; font-weight: 600;
                 color: #111827;}
  .tier-card.primary h4 {color: #3730A3;}
  .tier-card p {margin: 0 0 10px 0; font-size: 13px; color: #4B5563;
                line-height: 1.5;}
  .tier-card.primary p {color: #3730A3;}

  .connected-pill {
    display: inline-flex; align-items: center; gap: 8px;
    background: #ECFDF5; color: #065F46; border: 1px solid #A7F3D0;
    padding: 6px 12px; border-radius: 20px; font-size: 13px;
    font-weight: 500;
  }
  .connected-pill .dot {width: 8px; height: 8px; border-radius: 50%;
                        background: #10B981;}
</style>
"""
st.markdown(CSS, unsafe_allow_html=True)


_team_pw = os.environ.get("BNA_WEB_PASSWORD", "").strip()
if _team_pw:
    if "auth_ok" not in st.session_state:
        st.session_state.auth_ok = False
    if not st.session_state.auth_ok:
        st.markdown(
            '<div class="bna-header"><div class="icon">πŸ”’</div>'
            '<div><h1>BNA Comparator</h1>'
            '<p>Team-internal -- please sign in to continue.</p>'
            '</div></div>',
            unsafe_allow_html=True,
        )
        pw = st.text_input("Team password", type="password", key="_pw")
        if st.button("Sign in", type="primary"):
            if pw == _team_pw:
                st.session_state.auth_ok = True
                st.rerun()
            else:
                st.error("Wrong password.")
        st.stop()


st.markdown(
    '<div class="bna-header"><div class="icon">πŸ“¦</div>'
    '<div><h1>Compare many projects in one shot</h1>'
    '<p>Upload one ZIP of AI Excels, pick a language, hit Run</p>'
    '</div></div>',
    unsafe_allow_html=True,
)


ss = st.session_state
ss.setdefault("last_run", None)
ss.setdefault("last_zip_bytes", None)
ss.setdefault("last_zip_name", "")
ss.setdefault("log_lines", [])
ss.setdefault("progress_rows", [])
ss.setdefault("trigger_run", False)
ss.setdefault("uploader_nonce", 0)
ss.setdefault("run_status", "idle")  # idle | running | success | error
ss.setdefault("run_error_msg", "")
ss.setdefault("queue_id", None)
ss.setdefault("zip_layout", {})


REQUIRED_ZIP_FOLDERS = ("Input", "Output", "Summary")


def _validation_error(title: str, body: str) -> None:
    """Surface a validation failure in BOTH tabs and halt the run.

    The Inputs tab needs to see the error too β€” without this it stays
    stuck on the pulsing "Working on your batch…" banner because the
    validation runs inside `with tab_log:` and st.stop() doesn't
    re-render the Inputs side.

    Flow:
      1. Push the failure into ss.run_status / ss.run_error_msg so the
         Inputs status block displays the same error banner on rerun.
      2. Append a [ERROR] line to ss.log_lines so the Log tab keeps it
         in the live trace.
      3. Trigger a rerun β€” after that, both tabs render the error.
    """
    # Strip HTML for the plain-text log and error_msg, keep markup for UI.
    plain = re.sub(r"<[^>]+>", "", body).strip()
    ss.run_status = "error"
    ss.run_error_msg = f"{title}\n\n{plain}"
    ss.log_lines.append(f"[ERROR] Validation failed: {title} β€” {plain}")

    # Render in the current context (Log tab when called from trigger_run)
    # so the researcher sees something immediately, even before the rerun.
    st.markdown(
        f'<div class="status-banner error">'
        f'<div class="icon">⚠️</div>'
        f'<div><b>{title}</b><br>{body}</div>'
        f'</div>',
        unsafe_allow_html=True,
    )
    # Also clear the run queue and Streamlit-stop the current run.
    try:
        if ss.get("queue_id"):
            queue_dequeue(ss.queue_id)
            ss.queue_id = None
    except Exception:
        pass
    st.rerun()


def _stage_zip(upload, into_dir: Path) -> Path:
    """Strict validation pipeline for the single-ZIP upload.

    The Comparator now accepts exactly one ZIP, with this internal
    structure:

        Comparator_<batch-name>.zip
        β”œβ”€β”€ Input/      ← AI Excel files (.xlsx)
        β”œβ”€β”€ Output/     ← (created/managed by Comparator; can be empty)
        └── Summary/    ← (created/managed by Comparator; can be empty)

    Any deviation raises a clear, actionable validation message and
    halts the run before the engine starts. The engine then reads AI
    Excels from `Input/`, writes per-project results to `Output/`, and
    drops the batch summary into `Summary/`.
    """
    into_dir.mkdir(parents=True, exist_ok=True)

    # --- 1) File presence ----------------------------------------------
    if upload is None:
        _validation_error(
            "No file uploaded",
            "Drop a ZIP into the uploader. The Comparator accepts exactly "
            "one ZIP per run β€” see the panel for the required folder layout.",
        )

    raw_name = (upload.name or "").strip()
    if not raw_name:
        _validation_error(
            "Upload has no filename",
            "Your browser sent a file with an empty name. Try uploading again, "
            "or rename the ZIP before uploading.",
        )

    # --- 2) Extension --------------------------------------------------
    if not raw_name.lower().endswith(".zip"):
        _validation_error(
            f'"{raw_name}" is not a ZIP file',
            "The Comparator only accepts a single <code>.zip</code> archive. "
            "Right-click the folder containing your Input/Output/Summary "
            "folders β†’ <b>Send to β†’ Compressed (zipped) folder</b>, then "
            "upload the resulting <code>.zip</code>.",
        )

    # --- 3) Save to disk -----------------------------------------------
    basename = raw_name.replace("\\", "/").split("/")[-1] or raw_name
    zip_path = into_dir / basename
    try:
        zip_path.write_bytes(upload.getvalue() or b"")
    except Exception as e:
        _validation_error(
            "Could not save your upload",
            f"Something went wrong saving <code>{basename}</code> to the "
            f"server: <code>{e}</code>. Try uploading again.",
        )

    # --- 4) Valid ZIP --------------------------------------------------
    try:
        zf = zipfile.ZipFile(zip_path, "r")
    except zipfile.BadZipFile:
        _validation_error(
            f'"{basename}" is not a valid ZIP',
            "The file uploaded with a <code>.zip</code> extension but its "
            "contents are corrupted or in a different format. Re-create the "
            "ZIP and upload again.",
        )

    # --- 5) Structure: Input / Output / Summary at the top level -------
    # Walk the ZIP namelist to find which top-level folders exist. We
    # tolerate either Comparator_xxx/Input/ (single root wrapper, e.g.
    # Windows ZIP creates this) OR Input/ directly at the root.
    with zf:
        names = zf.namelist()
        # Build a map of top-level entries β†’ list of children. A folder
        # entry shows up as either an explicit empty dir entry ending in /
        # (`Input/`) or via its children (`Input/data.xlsx`). A loose file
        # at the root has no children.
        is_dir: dict[str, bool] = {}
        nested_under: dict[str, set[str]] = {}
        loose_files: set[str] = set()
        for n in names:
            normalized = n.replace("\\", "/")
            parts = [p for p in normalized.split("/") if p]
            if not parts:
                continue
            top = parts[0]
            if len(parts) == 1 and not normalized.endswith("/"):
                # Loose file at root (e.g. Summary.xlsx)
                loose_files.add(top)
                is_dir.setdefault(top, False)
            else:
                is_dir[top] = True
                if len(parts) >= 2:
                    nested_under.setdefault(top, set()).add(parts[1])

        # Treat Summary leniently: a 'Summary.xlsx' (or .xls/.xlsm) file at
        # the root counts the same as a 'Summary/' folder β€” researchers
        # often keep the previous summary workbook beside Input/ and
        # Output/ folders. We'll auto-create Summary/ during extract and
        # move the file inside.
        summary_loose_file = ""
        for f in loose_files:
            if f.lower().startswith("summary.") and f.lower().endswith(
                (".xlsx", ".xls", ".xlsm")
            ):
                summary_loose_file = f
                break

        # The folders we count toward "structure satisfied"
        top_level_folders = {k for k, v in is_dir.items() if v}
        wrapper = ""

        has_all_folders = all(f in top_level_folders for f in REQUIRED_ZIP_FOLDERS)
        has_input_output_plus_summary_file = (
            "Input" in top_level_folders
            and "Output" in top_level_folders
            and summary_loose_file
        )

        if has_all_folders:
            wrapper = ""
        elif has_input_output_plus_summary_file:
            # Layout will be normalised after extraction (move file into Summary/)
            wrapper = ""
        elif len(top_level_folders) == 1 and not loose_files:
            only = next(iter(top_level_folders))
            children = nested_under.get(only, set())
            if all(folder in children for folder in REQUIRED_ZIP_FOLDERS):
                wrapper = only
            else:
                _validation_error(
                    "ZIP is missing the required folders",
                    f"Your ZIP contains a single top folder <code>{only}/</code>, "
                    f"but inside it we expected <code>Input/</code>, "
                    f"<code>Output/</code>, and <code>Summary/</code>. "
                    f"Found instead: <code>{', '.join(sorted(children)) or '(empty)'}</code>.",
                )
        else:
            # Build a friendly "found" description for the error
            found_bits = []
            for f in sorted(top_level_folders):
                found_bits.append(f"<code>{f}/</code>")
            for f in sorted(loose_files):
                found_bits.append(f"<code>{f}</code>")
            found_desc = ", ".join(found_bits) or "<code>(empty ZIP)</code>"

            missing = [f for f in REQUIRED_ZIP_FOLDERS if f not in top_level_folders]
            # Special-case: Summary was uploaded as a file with a non-Excel
            # extension or wrong name.
            extra_hint = ""
            if "Summary" in missing and any(
                f.lower().startswith("summary") for f in loose_files
            ):
                extra_hint = (
                    "<br><br>It looks like you have a <code>Summary</code> "
                    "item at the root but it's a file, not a folder. "
                    "Either put it inside a <code>Summary/</code> folder, "
                    "rename it to <code>Summary.xlsx</code>, or just delete "
                    "it (the Comparator creates the summary itself)."
                )

            _validation_error(
                "ZIP is missing the required folders",
                f"The ZIP must contain three folders at its root: "
                f"<code>Input/</code>, <code>Output/</code>, "
                f"<code>Summary/</code>.<br>"
                f"Missing: <code>{', '.join(missing) or '(none β€” but layout is off)'}</code>."
                f"<br><br>Found at root: {found_desc}.{extra_hint}",
            )

        # --- 6) Extract -----------------------------------------------
        try:
            zf_ref = zipfile.ZipFile(zip_path, "r")
            with zf_ref:
                zf_ref.extractall(into_dir)
        except Exception as e:
            _validation_error(
                "Could not unpack the ZIP",
                f"Extraction failed with: <code>{e}</code>. Re-create the ZIP "
                f"with standard tooling (Windows: right-click β†’ Send to β†’ "
                f"Compressed; Mac: right-click β†’ Compress) and try again.",
            )

    # Resolve the actual Input/ folder on disk after extraction
    root = into_dir / wrapper if wrapper else into_dir
    input_dir = root / "Input"
    output_dir = root / "Output"
    summary_dir = root / "Summary"

    # Belt-and-braces: make sure the dirs actually exist on disk too
    for d in (input_dir, output_dir, summary_dir):
        d.mkdir(parents=True, exist_ok=True)

    # If the researcher uploaded a loose Summary.xlsx at the root
    # (instead of a Summary/ folder), move it into Summary/ so the
    # engine has a clean layout to write into.
    if not wrapper:  # only need this dance for root-layout ZIPs
        for candidate in root.iterdir():
            if (
                candidate.is_file()
                and candidate.name.lower().startswith("summary.")
                and candidate.name.lower().endswith((".xlsx", ".xls", ".xlsm"))
            ):
                try:
                    candidate.replace(summary_dir / candidate.name)
                except Exception:
                    pass

    # --- 7) Output/ must have at least one Excel file ------------------
    # The AI pipeline's output Excels live under Output/ (possibly nested
    # under per-project subfolders). The Comparator walks Output/ recursively
    # for any .xlsx / .xls / .xlsm.
    excels = []
    for ext in (".xlsx", ".xls", ".xlsm"):
        excels.extend(output_dir.rglob(f"*{ext}"))
    excels = [p for p in excels if not p.name.startswith("~$")]
    if not excels:
        _validation_error(
            "The Output/ folder has no AI Excels",
            "Your ZIP has the right structure, but <code>Output/</code> "
            "(or any of its sub-folders) contains no Excel files. Put your "
            "AI output Excels (<code>.xlsx</code>) anywhere inside "
            "<code>Output/</code> β€” they can be in per-project sub-folders "
            "if you prefer β€” then re-zip and upload again.",
        )

    # Stash the resolved layout on the upload object via attribute trick β€”
    # the run handler reads it back from session_state instead, set there.
    ss.zip_layout = {
        "root": str(root),
        "input": str(input_dir),
        "output": str(output_dir),
        "summary": str(summary_dir),
        "zip_basename": basename,
    }
    return root


def _zip_directory(src: Path) -> bytes:
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
        for root, _, files in os.walk(src):
            for f in files:
                full = Path(root) / f
                arc = full.relative_to(src)
                zf.write(full, arc)
    return buf.getvalue()


def _label(col, text):
    col.markdown(f'<div class="field-label">{text}</div>', unsafe_allow_html=True)


def _kpi(label, value, kind=""):
    return (
        f'<div class="kpi-tile {kind}">'
        f'<div class="label">{label}</div>'
        f'<div class="value">{value}</div>'
        f'</div>'
    )


def _live_error_banner(lines: list[str]) -> str:
    """Build the live error/warning banner HTML for the Inputs tab.
    Only the last few ERROR/WARNING lines are shown so the banner
    stays compact during a long-running batch."""
    error_lines = [l for l in lines if "[ERROR]" in l or "[WARNING]" in l]
    if not error_lines:
        return ""
    recent = error_lines[-5:]
    body = "\n".join(recent).replace("<", "&lt;").replace(">", "&gt;")
    return (
        '<div class="status-banner error" style="margin-top: 14px;">'
        '<div class="icon">⚠️</div>'
        '<div style="flex:1;"><b>Something is going wrong in the run.</b>'
        '<br>The Log tab has the full trace. Latest lines:'
        f'<pre style="white-space: pre-wrap; margin: 8px 0 0; '
        f'font-size: 12px; background: rgba(255,255,255,0.5); '
        f'padding: 8px; border-radius: 4px; max-height: 160px; '
        f'overflow: auto;">{body}</pre>'
        '</div></div>'
    )


def _run_batch_in_subprocess(ai_dir, out_dir, tie_path, email, password,
                              lang, log_box, progress_callback,
                              bna_cookies="", inputs_error_box=None):
    """Spawn a fresh Python subprocess to run the batch. Each subprocess
    gets a clean Playwright instance β€” sidesteps the "Event loop is
    closed" issue we'd hit if we called sync_playwright twice in this
    same Streamlit process."""
    with tempfile.TemporaryDirectory(prefix="bna_ipc_") as ipc:
        ipc_path = Path(ipc)
        out_json = ipc_path / "result.json"
        log_jsonl = ipc_path / "log.jsonl"

        cfg = {
            "ai_zip_path": str(ai_dir),
            "output_folder": str(out_dir),
            "tie_path": str(tie_path),
            "email": email,
            "password": password,
            "bna_cookies": bna_cookies,
            "lang": lang,
            "headless": True,
            "manual_login": False,
        }
        log_jsonl.touch()

        # Pass config via stdin (not as a CLI argument or a config file
        # path). Keeps the BNA password out of the process list and out
        # of any file that might survive a crash.
        cli = HERE / "engine" / "run_batch_cli.py"
        proc = subprocess.Popen(
            [sys.executable, str(cli), str(out_json), str(log_jsonl)],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
        )
        try:
            proc.stdin.write(json.dumps(cfg))
            proc.stdin.close()
        finally:
            cfg = None  # drop the local reference ASAP

        # Tail the log file while the subprocess runs
        last_pos = 0
        saw_error = False
        while proc.poll() is None:
            try:
                with log_jsonl.open("r", encoding="utf-8") as fh:
                    fh.seek(last_pos)
                    new = fh.read()
                    last_pos = fh.tell()
                for line in new.splitlines():
                    if not line.strip():
                        continue
                    try:
                        rec = json.loads(line)
                    except Exception:
                        continue
                    if rec.get("type") == "log":
                        level = str(rec.get("level", "INFO")).upper()
                        ss.log_lines.append(f"[{level}] {rec['message']}")
                        if len(ss.log_lines) > 500:
                            ss.log_lines[:] = ss.log_lines[-500:]
                        if level in ("ERROR", "WARNING"):
                            saw_error = True
                    elif rec.get("type") == "progress":
                        progress_callback(rec["info"])
                try:
                    log_box.code("\n".join(ss.log_lines[-60:]), language="text")
                except Exception:
                    pass
                # Push a live error excerpt into the Inputs tab so the
                # researcher sees problems without having to switch tabs.
                if saw_error and inputs_error_box is not None:
                    try:
                        inputs_error_box.markdown(
                            _live_error_banner(ss.log_lines),
                            unsafe_allow_html=True,
                        )
                    except Exception:
                        pass
            except Exception:
                pass
            time.sleep(0.6)

        # Drain whatever's left in the log file after the subprocess exits
        try:
            with log_jsonl.open("r", encoding="utf-8") as fh:
                fh.seek(last_pos)
                rest = fh.read()
            for line in rest.splitlines():
                if not line.strip():
                    continue
                try:
                    rec = json.loads(line)
                except Exception:
                    continue
                if rec.get("type") == "log":
                    ss.log_lines.append(f"[{rec['level']}] {rec['message']}")
                elif rec.get("type") == "progress":
                    progress_callback(rec["info"])
        except Exception:
            pass

        if not out_json.exists():
            return None, "Subprocess exited without writing a result file."
        result = json.loads(out_json.read_text(encoding="utf-8"))
        if not result.get("ok"):
            return None, result.get("error") + "\n" + result.get("traceback", "")
        return result["summary"], None


# Admin tab is hidden by default. It only appears when the team lead
# visits the app with ``?admin=1`` in the URL. Even when it appears,
# every action inside it requires the secret stored in the HF Space
# environment variable ``ADMIN_PASSWORD`` so a researcher who stumbles
# onto the URL can't see or change anything.
def _admin_mode() -> bool:
    try:
        qp = st.query_params
        return str(qp.get("admin", "")).lower() in ("1", "true", "yes")
    except Exception:
        return False


if _admin_mode():
    tab_inputs, tab_dashboard, tab_log, tab_guide, tab_feedback, tab_admin = st.tabs(
        ["πŸ“‹  Inputs", "πŸ“Š  Dashboard", "πŸ“œ  Log", "πŸ“–  User Guide",
         "πŸ’¬  Send feedback", "πŸ”  Admin"]
    )
else:
    tab_inputs, tab_dashboard, tab_log, tab_guide, tab_feedback = st.tabs(
        ["πŸ“‹  Inputs", "πŸ“Š  Dashboard", "πŸ“œ  Log", "πŸ“–  User Guide",
         "πŸ’¬  Send feedback"]
    )
    tab_admin = None


# ---- Inputs tab ------------------------------------------------------
with tab_inputs:
    with st.container(border=True):
        st.markdown(
            '<h2 class="section-title"><span class="gear">βš™</span> Inputs</h2>',
            unsafe_allow_html=True,
        )

        c1, c2 = st.columns([1, 4])
        _label(c1, "Agentic AI Output Zip")
        with c2:
            ai_zip = st.file_uploader(
                "Agentic AI Output Zip",
                type=["zip"],
                accept_multiple_files=False,
                label_visibility="collapsed",
                key=f"uploader_{ss.uploader_nonce}",
                help="Upload a single .zip with Input/, Output/, and Summary/ folders inside.",
            )
            st.caption(
                "Required ZIP layout: "
                "**`Input/`** Β· "
                "**`Output/`** (your AI output Excels β€” sub-folders OK) Β· "
                "**`Summary/`** (or `Summary.xlsx`). "
                "One ZIP per run."
            )

        c1, c2 = st.columns([1, 4])
        _label(c1, "Output language")
        lang_label = c2.selectbox(
            "Output language",
            options=["English", "EspaΓ±ol", "PortuguΓͺs"],
            index=1,
            label_visibility="collapsed",
            key=f"lang_{ss.uploader_nonce}",
        )
        lang = {"English": "en", "EspaΓ±ol": "es", "PortuguΓͺs": "pt"}[lang_label]

        c1, c2 = st.columns([1, 4])
        _label(c1, "BNA email")
        bna_email = c2.text_input(
            "BNA email", autocomplete="username", label_visibility="collapsed",
            key=f"email_{ss.uploader_nonce}",
        )

        c1, c2 = st.columns([1, 4])
        _label(c1, "BNA password")
        bna_password = c2.text_input(
            "BNA password", type="password",
            autocomplete="current-password", label_visibility="collapsed",
            key=f"password_{ss.uploader_nonce}",
        )

        st.markdown('<div style="height: 18px;"></div>', unsafe_allow_html=True)
        _, c_btns = st.columns([1, 4])
        b1, b2, b3, _ = c_btns.columns([1.4, 1.8, 1.2, 4])

        # Single source of truth for the run-in-progress condition
        is_running = ss.run_status == "running"
        has_results = bool(ss.last_zip_bytes)
        all_inputs_filled = bool(ai_zip and bna_email and bna_password)

        # --- Run batch (primary action) ---------------------------------
        # Enabled only when:
        #   * Nothing is running
        #   * ZIP + email + password are all filled
        # Disabled the moment Run is clicked and until the run finishes
        # (success or error).
        run_disabled = is_running or (not all_inputs_filled)
        if b1.button("β–Ά  Run batch", type="primary",
                     disabled=run_disabled, key="btn_run"):
            ss.trigger_run = True
            ss.run_status = "running"
            ss.last_run = None
            ss.last_zip_bytes = None   # Drop previous result so the
            ss.last_zip_name = ""      # Download button disables for the
                                       # new run (re-enables on success).
            ss.run_error_msg = ""
            # Force an immediate rerun so the button renders as
            # *disabled* (and the Clear/Download buttons too) BEFORE
            # the long-running subprocess block kicks off. Without
            # this rerun, the script keeps executing the rest of the
            # page (where the buttons were already painted as enabled)
            # straight into the subprocess block β€” the researcher
            # would see an enabled Run button for the whole batch.
            st.rerun()

        # --- Download results ZIP ---------------------------------------
        # Enabled only when nothing is running AND a results ZIP exists
        # from the most recent batch. Skinned BNAmericas blue (#2541B2)
        # via the global CSS at the top of this file.
        if has_results and not is_running:
            b2.download_button(
                "⬇  Download results ZIP",
                data=ss.last_zip_bytes,
                file_name=ss.last_zip_name or "bna_comparator_results.zip",
                mime="application/zip",
                key="btn_download",
            )
        else:
            b2.button("⬇  Download results ZIP", disabled=True,
                      key="btn_download_disabled")

        # --- Clear (light-grey safety net) ------------------------------
        # Always enabled when nothing is running. Researchers can clear
        # mistakes even before they've filled every field. Light-grey
        # fill (#E5E7EB) skinned via the global CSS at the top.
        if b3.button("🧹  Clear", disabled=is_running, key="btn_clear"):
            ss.uploader_nonce += 1
            ss.last_run = None
            ss.last_zip_bytes = None
            ss.last_zip_name = ""
            ss.log_lines = []
            ss.progress_rows = []
            ss.run_status = "idle"
            ss.run_error_msg = ""
            st.rerun()

    # Status banner under the inputs card β€” shows run progress / outcome
    if ss.run_status == "running":
        st.markdown(
            '<div class="status-banner running">'
            '<div class="pulse-dot"></div>'
            '<div><b>Working on your batch…</b> &nbsp;'
            'This usually takes a minute or two per project. '
            'Switch to the <b>Log</b> tab to follow along live.</div>'
            '</div>',
            unsafe_allow_html=True,
        )
        if ss.last_run is not None:
            s = ss.last_run
            total = s.get("total", 0) or 1
            done = s.get("ok", 0) + s.get("failed", 0)
            st.progress(
                min(1.0, done / total),
                text=f"{done} of {total} projects processed",
            )
        else:
            st.progress(0.05, text="Starting up the browser session…")
        # Surface any ERROR / WARNING lines already in the log without
        # waiting for the subprocess to finish.
        error_banner = _live_error_banner(ss.log_lines)
        if error_banner:
            st.markdown(error_banner, unsafe_allow_html=True)

    elif ss.run_status == "success" and ss.last_run is not None:
        s = ss.last_run
        st.markdown(
            f'<div class="status-banner success">'
            f'<div class="icon">βœ…</div>'
            f'<div><b>Batch complete!</b> &nbsp;'
            f'Processed <b>{s["ok"]}/{s["total"]}</b> projects '
            f'({s.get("failed", 0)} failed). &nbsp;'
            f'Head to the <b>Dashboard</b> tab to explore results, '
            f'or grab the ZIP above.</div>'
            f'</div>',
            unsafe_allow_html=True,
        )

    elif ss.run_status == "error":
        # Headline banner β€” always visible, points at the Log tab.
        st.markdown(
            f'<div class="status-banner error">'
            f'<div class="icon">⚠️</div>'
            f'<div><b>Something went wrong.</b> &nbsp;'
            f'See the message below for what to do, and switch to the '
            f'<b>Log</b> tab for the full trace.</div>'
            f'</div>',
            unsafe_allow_html=True,
        )
        # Always-visible error message (no need to expand).
        if ss.run_error_msg:
            st.markdown(
                '<div class="status-banner error" style="margin-top: 12px;">'
                '<div class="icon">πŸ“</div>'
                '<div style="flex:1;"><b>Details</b>'
                '<pre style="white-space: pre-wrap; margin: 8px 0 0; '
                'font-size: 12px; background: rgba(255,255,255,0.5); '
                'padding: 8px; border-radius: 4px; max-height: 280px; '
                'overflow: auto;">'
                + (ss.run_error_msg or "(no message)").replace("<", "&lt;").replace(">", "&gt;") +
                '</pre></div></div>',
                unsafe_allow_html=True,
            )


# ---- Dashboard tab ---------------------------------------------------
def _kpi_tile(icon: str, value, label: str, color: str) -> str:
    return (
        f'<div class="dash-tile" style="border-left-color: {color};">'
        f'  <div class="dash-tile-icon" style="color: {color};">{icon}</div>'
        f'  <div class="dash-tile-body">'
        f'    <div class="dash-tile-value">{value}</div>'
        f'    <div class="dash-tile-label">{label}</div>'
        f'  </div>'
        f'</div>'
    )


with tab_dashboard:
    if ss.last_run is None:
        st.info("Run a batch first -- the dashboard fills in once it finishes.")
    else:
        s = ss.last_run
        rows = s.get("rows") or []
        agg = {"matches": 0, "differs": 0, "stale_ai": 0,
               "missing_on_ai": 0, "pending_disclosure": 0, "total_fields": 0}
        rates = []
        recommendations = 0
        for r in rows:
            for k in agg:
                v = r.get(k, 0)
                if isinstance(v, (int, float)):
                    agg[k] += v
            mr = r.get("match_rate", 0)
            if isinstance(mr, (int, float)):
                rates.append(mr)
            recommendations += (r.get("differs", 0) or 0) + (r.get("stale_ai", 0) or 0)
        avg_match_rate = round(sum(rates) / max(1, len(rates)), 1) if rates else 0.0

        # Dashboard-specific styling
        st.markdown("""
        <style>
          .dash-header h3 {color: #1E3A8A; font-size: 22px; margin: 0;}
          .dash-header p {color: #6B7280; font-size: 13px; margin: 2px 0 18px 0;}
          .dash-grid {
            display: grid; grid-template-columns: repeat(4, 1fr);
            gap: 14px; margin-bottom: 18px;
          }
          .dash-tile {
            background: #FFFFFF; border: 1px solid #E5E7EB; border-left: 4px solid #2541B2;
            border-radius: 8px; padding: 16px 18px;
            display: flex; align-items: center; gap: 14px;
            min-height: 70px;
          }
          .dash-tile-icon {font-size: 22px; flex-shrink: 0;}
          .dash-tile-value {font-size: 30px; font-weight: 700; color: #111827; line-height: 1;}
          .dash-tile-label {font-size: 12px; color: #6B7280; margin-top: 4px; text-transform: capitalize;}
          .dash-legend {
            background: #FFFFFF; border: 1px solid #E5E7EB; border-radius: 8px;
            padding: 16px 20px; margin-top: 8px;
          }
          .dash-legend h4 {color: #1E3A8A; font-size: 15px; margin: 0 0 10px 0;
                          display: flex; align-items: center; gap: 8px;}
          .dash-legend ul {margin: 0; padding-left: 18px; color: #374151; font-size: 13px;}
          .dash-legend li {margin: 4px 0;}
          .dash-legend b {color: #1F2937;}

          .pp-header {color: #1E3A8A; font-size: 18px; margin: 22px 0 12px 0;
                      display: flex; align-items: center; gap: 8px;}
          .pp-row {
            display: grid;
            grid-template-columns: 70px 2fr 90px 90px 90px 110px;
            gap: 14px; align-items: center;
            padding: 10px 14px; border-bottom: 1px solid #F3F4F6;
            font-size: 14px;
          }
          .pp-row:hover {background: #F9FAFB;}
          .pp-colhead {
            display: grid;
            grid-template-columns: 70px 2fr 90px 90px 90px 110px;
            gap: 14px; align-items: center;
            padding: 10px 14px; border-bottom: 2px solid #E5E7EB;
            background: #F8FAFC; border-radius: 6px 6px 0 0;
            font-size: 12px; font-weight: 600;
            color: #4B5563; text-transform: uppercase; letter-spacing: 0.05em;
          }
          .pp-dot {width: 10px; height: 10px; border-radius: 50%;}
          .pp-dot.ok {background: #16A34A;}
          .pp-dot.fail {background: #DC2626;}
          .pp-name {color: #111827; font-weight: 500;}
          .pp-m {color: #16A34A;}
          .pp-d {color: #DC2626;}
          .pp-s {color: #8B5CF6;}
          .pp-rate {color: #2541B2; font-weight: 600;}
        </style>
        """, unsafe_allow_html=True)

        # Batch results header
        st.markdown(
            '<div class="dash-header">'
            '<h3>🌿 &nbsp;Batch results</h3>'
            '<p>Across every project in this batch</p>'
            '</div>',
            unsafe_allow_html=True,
        )

        # KPI grid (3 rows Γ— 4 cols, like the desktop app)
        tiles_html = '<div class="dash-grid">'
        tiles_html += _kpi_tile("πŸ“", s.get("total", 0), "Projects", "#2541B2")
        tiles_html += _kpi_tile("βœ…", s.get("ok", 0), "Succeeded", "#16A34A")
        tiles_html += _kpi_tile("⚠️", s.get("failed", 0), "Failed", "#DC2626")
        tiles_html += _kpi_tile("πŸ“Š", f"{avg_match_rate}%", "Match Rate", "#8B5CF6")
        tiles_html += _kpi_tile("πŸ“‹", agg["total_fields"], "Total Fields", "#2541B2")
        tiles_html += _kpi_tile("βœ“", agg["matches"], "Matches", "#16A34A")
        tiles_html += _kpi_tile("β‰ ", agg["differs"], "Differs", "#DC2626")
        tiles_html += _kpi_tile("βŒ›", agg["pending_disclosure"], "Missing on Both", "#6B7280")
        tiles_html += _kpi_tile("β’·", agg["missing_on_ai"], "Missing on AI", "#8B5CF6")
        tiles_html += _kpi_tile("⏰", agg["stale_ai"], "Stale AI", "#8B5CF6")
        tiles_html += _kpi_tile("⭐", recommendations, "Recommendations", "#F97316")
        tiles_html += '</div>'
        st.markdown(tiles_html, unsafe_allow_html=True)

        # Legend
        st.markdown(
            '<div class="dash-legend">'
            '<h4>ℹ️ What do these mean?</h4>'
            '<ul>'
            '<li><b>Matches</b> β€” AI value agrees with BNA value.</li>'
            '<li><b>Differs</b> β€” AI value differs from BNA. Researcher review needed.</li>'
            '<li><b>Missing on Both</b> β€” Field is blank on both sides.</li>'
            '<li><b>Missing on AI</b> β€” BNA has a value; AI doesn\'t.</li>'
            '<li><b>Stale AI</b> β€” AI value is older than BNA\'s last review.</li>'
            '<li><b>Recommendations</b> β€” Differ + Stale AI rows for the researcher to action.</li>'
            '</ul>'
            '</div>',
            unsafe_allow_html=True,
        )

        # Per-project breakdown
        st.markdown(
            '<div class="pp-header">πŸ“‹ &nbsp;Per-project breakdown</div>',
            unsafe_allow_html=True,
        )

        # Column headers
        st.markdown(
            '<div class="pp-colhead">'
            '<div>Status</div>'
            '<div>Project name</div>'
            '<div>Matches</div>'
            '<div>Differs</div>'
            '<div>Stale AI</div>'
            '<div>Match rate</div>'
            '</div>',
            unsafe_allow_html=True,
        )

        for r in rows:
            name = r.get("name", "(unnamed)")
            status_ok = (r.get("status", "") or "").lower() in ("ok", "success", "")
            dot_cls = "ok" if status_ok else "fail"
            m = r.get("matches", 0) or 0
            d = r.get("differs", 0) or 0
            s_ai = r.get("stale_ai", 0) or 0
            mr = r.get("match_rate", 0) or 0
            mr_str = f"{mr}%" if isinstance(mr, (int, float)) else str(mr)
            st.markdown(
                f'<div class="pp-row">'
                f'<div class="pp-dot {dot_cls}"></div>'
                f'<div class="pp-name">{name}</div>'
                f'<div class="pp-m">βœ“ {m}</div>'
                f'<div class="pp-d">β‰  {d}</div>'
                f'<div class="pp-s">⏰ {s_ai}</div>'
                f'<div class="pp-rate">πŸ“Š {mr_str}</div>'
                f'</div>',
                unsafe_allow_html=True,
            )


# ---- Log tab ---------------------------------------------------------
with tab_log:
    if not ss.log_lines:
        st.info("Live log will appear here as the run progresses.")
    else:
        st.code("\n".join(ss.log_lines), language="text")


# ---- User Guide tab --------------------------------------------------
# Single source of truth: GUIDE_FOR_RESEARCHERS.md (edit-then-rebuild
# the PDF via tools/build_guide_pdf.py). The tab renders the markdown
# inline for instant reading, and offers the styled PDF as a download
# for offline / printing use.
with tab_guide:
    _guide_md = HERE / "GUIDE_FOR_RESEARCHERS.md"
    _guide_pdf = HERE / "GUIDE_FOR_RESEARCHERS.pdf"

    # Custom CSS to give the rendered markdown a calm, branded look β€”
    # blue h2 headings, soft borders on tables and code, comfortable
    # spacing. Only applies inside this tab via a scoped container.
    st.markdown(
        "<style>"
        ".guide-wrap h2 {color: #1E3A8A; border-bottom: 2px solid #E5E7EB; "
        "  padding-bottom: 6px; margin-top: 26px;}"
        ".guide-wrap h3 {color: #1E3A8A; margin-top: 18px;}"
        ".guide-wrap table {border-collapse: collapse; width: 100%; "
        "  margin: 12px 0; font-size: 14px;}"
        ".guide-wrap th {background: #F8FAFC; color: #1E3A8A; "
        "  text-align: left; padding: 8px 12px; border-bottom: 2px solid #E5E7EB;}"
        ".guide-wrap td {padding: 8px 12px; border-bottom: 1px solid #F1F5F9; "
        "  vertical-align: top;}"
        ".guide-wrap code {background: #F3F4F6; color: #1E3A8A; "
        "  padding: 1px 6px; border-radius: 4px; font-size: 0.9em;}"
        ".guide-wrap ul {line-height: 1.7;}"
        ".guide-cover {background: #2541B2; color: #FFFFFF; padding: 22px 26px; "
        "  border-radius: 10px; margin-bottom: 18px;}"
        ".guide-cover h2 {color: #FFFFFF !important; border: 0 !important; "
        "  margin: 0 !important; padding: 0 !important; font-size: 22px;}"
        ".guide-cover p {margin: 6px 0 0 0; color: #DBE3F8; font-size: 14px;}"
        "</style>",
        unsafe_allow_html=True,
    )

    # Cover banner + download button row
    col_title, col_dl = st.columns([4, 1])
    with col_title:
        st.markdown(
            '<div class="guide-cover">'
            '<h2>πŸ“– Comparer Tool β€” Quick Guide</h2>'
            '<p>Everything you need for your first batch (and the next hundred).</p>'
            '</div>',
            unsafe_allow_html=True,
        )
    with col_dl:
        if _guide_pdf.exists():
            st.markdown('<div style="height: 14px;"></div>', unsafe_allow_html=True)
            st.download_button(
                "⬇  Download PDF",
                data=_guide_pdf.read_bytes(),
                file_name="Comparer_Tool_User_Guide.pdf",
                mime="application/pdf",
                key="btn_guide_pdf",
            )

    # Render the markdown body (skip the first H1 + lead paragraph,
    # they're already shown in the cover banner above).
    if _guide_md.exists():
        raw_md = _guide_md.read_text(encoding="utf-8")
        body_md = raw_md
        # Drop the first H1 line + its immediate lead paragraph.
        lines = body_md.split("\n")
        out = []
        seen_h1 = False
        skipped_lead = False
        for line in lines:
            if not seen_h1 and line.startswith("# "):
                seen_h1 = True
                continue
            if seen_h1 and not skipped_lead and line.strip() == "":
                continue
            if seen_h1 and not skipped_lead and not line.startswith("#"):
                skipped_lead = True
                continue
            out.append(line)
        body_md = "\n".join(out)
        st.markdown(
            f'<div class="guide-wrap">\n\n{body_md}\n\n</div>',
            unsafe_allow_html=True,
        )
    else:
        st.error(
            "Guide content file is missing. Please upload "
            "`GUIDE_FOR_RESEARCHERS.md` to the Space root."
        )


# ---- Feedback tab ---------------------------------------------------
# Researcher-facing form. Submits feedback (free text + uploaded
# screenshots + technical files from a batch) to disk, and forwards a
# summary email if SMTP is configured on the HF Space.
with tab_feedback:
    st.markdown(
        '<h2 class="section-title"><span class="gear">πŸ’¬</span> Send feedback</h2>',
        unsafe_allow_html=True,
    )
    st.markdown(
        "<p style='color:#4B5563; font-size:14px;'>"
        "Spot something off β€” a wrong match, a confusing column, a feature "
        "you wish existed? Tell the team here. Attach screenshots and the "
        "project's technical files so we can reproduce it quickly."
        "</p>",
        unsafe_allow_html=True,
    )

    if "fb_nonce" not in ss:
        ss.fb_nonce = 0

    with st.form(f"feedback_form_{ss.fb_nonce}", clear_on_submit=False):
        c1, c2 = st.columns(2)
        with c1:
            fb_name = st.text_input(
                "Your name",
                value="",
                placeholder="e.g. Jane Doe",
            )
        with c2:
            fb_email = st.text_input(
                "Your email",
                value="",
                placeholder="jane.doe@bnamericas.com",
            )

        c3, c4 = st.columns(2)
        with c3:
            fb_type = st.selectbox(
                "What kind of feedback?",
                ["Bug β€” something is wrong",
                 "Suggestion β€” improvement idea",
                 "Question β€” how does this work?",
                 "Praise β€” this works well"],
                index=0,
            )
        with c4:
            fb_severity = st.selectbox(
                "Severity (bugs only)",
                ["Low β€” minor / cosmetic",
                 "Medium β€” wrong value but workable",
                 "High β€” blocks my batch"],
                index=0,
            )

        c5, c6 = st.columns(2)
        with c5:
            fb_project = st.text_input(
                "Project name (optional)",
                value="",
                placeholder="e.g. Cerro Bayo Expansion",
            )
        with c6:
            fb_permalink = st.text_input(
                "Project permalink (optional)",
                value="",
                placeholder="e.g. cerro-bayo-expansion",
                help="The BNAmericas permalink for the project β€” copy "
                     "from the URL or from the AI Excel's ProjectData tab.",
            )

        fb_subject = st.text_input(
            "Short subject",
            value="",
            placeholder="One line β€” what's this feedback about?",
        )

        fb_comment = st.text_area(
            "Your feedback",
            value="",
            height=180,
            placeholder=(
                "Describe what happened, what you expected, and what you "
                "actually saw. The more detail the better."
            ),
        )

        fb_screenshots = st.file_uploader(
            "Screenshots (optional β€” drag in one or more images)",
            type=["png", "jpg", "jpeg", "gif", "bmp", "webp"],
            accept_multiple_files=True,
            key=f"fb_shots_{ss.fb_nonce}",
        )

        fb_tech_files = st.file_uploader(
            "Technical files from the batch (optional β€” Excel, Log.txt, "
            "or the whole results ZIP)",
            type=["xlsx", "xls", "csv", "txt", "log", "json", "zip"],
            accept_multiple_files=True,
            key=f"fb_tech_{ss.fb_nonce}",
        )

        fb_submit = st.form_submit_button("πŸ“¨  Submit feedback", type="primary")

    if fb_submit:
        if not (fb_comment or "").strip():
            st.error("Please write at least a short comment before submitting.")
        else:
            attachments = []
            for up in (fb_screenshots or []):
                try:
                    attachments.append((up.name, up.getvalue()))
                except Exception:
                    pass
            for up in (fb_tech_files or []):
                try:
                    attachments.append((up.name, up.getvalue()))
                except Exception:
                    pass

            manifest = feedback_store.save_submission(
                fields={
                    "researcher_name": (fb_name or "").strip(),
                    "researcher_email": (fb_email or "").strip(),
                    "feedback_type": fb_type.split(" β€” ", 1)[0],
                    "severity": fb_severity.split(" β€” ", 1)[0],
                    "project_ref": (fb_project or "").strip(),
                    "permalink": (fb_permalink or "").strip(),
                    "subject": (fb_subject or "").strip(),
                    "comment": fb_comment.strip(),
                },
                attachments=attachments,
            )

            sid = manifest["submission_id"]
            success_html = (
                f'<div style="background:#DCFCE7; color:#166534; '
                f'padding:14px 18px; border-radius:8px; margin:14px 0;">'
                f'βœ… <b>Thanks β€” feedback received.</b><br>'
                f'Reference id: <code>{sid}</code><br>'
                f'<span style="font-size:13px;">The AI Content team '
                f'will review and follow up shortly.</span>'
                f'</div>'
            )
            st.markdown(success_html, unsafe_allow_html=True)

            # Reset the form for the next submission.
            ss.fb_nonce += 1


# ---- Admin tab (hidden β€” team-lead daily session refresh) -----------
# Only renders when ?admin=1 is in the URL AND the team lead enters the
# password configured in the HF Space's ADMIN_PASSWORD secret. Everything
# in this tab is silent for normal researchers.
if tab_admin is not None:
    with tab_admin:
        st.markdown(
            '<h2 class="section-title"><span class="gear">πŸ”</span> '
            'Admin β€” Team session</h2>',
            unsafe_allow_html=True,
        )

        _admin_pwd_expected = os.environ.get("ADMIN_PASSWORD", "")
        if not _admin_pwd_expected:
            st.warning(
                "Admin password is not configured. Set the "
                "`ADMIN_PASSWORD` secret on the Hugging Face Space, "
                "then reload."
            )
        else:
            if not ss.get("admin_authed"):
                _pwd = st.text_input(
                    "Admin password",
                    type="password",
                    key="admin_pwd_input",
                )
                if st.button("Unlock", key="admin_unlock_btn"):
                    if _pwd == _admin_pwd_expected:
                        ss.admin_authed = True
                        st.rerun()
                    else:
                        st.error("Wrong password.")
            else:
                # ---- Session status panel ----
                _age = team_session.age_hours()
                if _age is None:
                    _status_html = (
                        '<div style="background:#FEE2E2; color:#991B1B; '
                        'padding:10px 14px; border-radius:8px; margin:8px 0;">'
                        '⚠️ <b>No team session on file.</b> Researchers '
                        'are falling back to email + password.'
                        '</div>'
                    )
                elif _age < 12:
                    _status_html = (
                        f'<div style="background:#DCFCE7; color:#166534; '
                        f'padding:10px 14px; border-radius:8px; margin:8px 0;">'
                        f'βœ… <b>Session active.</b> Refreshed '
                        f'{_age:.1f} hours ago.'
                        f'</div>'
                    )
                elif _age < 22:
                    _status_html = (
                        f'<div style="background:#FEF3C7; color:#92400E; '
                        f'padding:10px 14px; border-radius:8px; margin:8px 0;">'
                        f'🟑 <b>Session aging.</b> Refreshed '
                        f'{_age:.1f} hours ago β€” please refresh soon.'
                        f'</div>'
                    )
                else:
                    _status_html = (
                        f'<div style="background:#FEE2E2; color:#991B1B; '
                        f'padding:10px 14px; border-radius:8px; margin:8px 0;">'
                        f'⚠️ <b>Session stale.</b> Refreshed '
                        f'{_age:.1f} hours ago β€” researchers will fall '
                        f'back to passwords.'
                        f'</div>'
                    )
                st.markdown(_status_html, unsafe_allow_html=True)

                # ---- How-to (collapsed) ----
                with st.expander("How to copy your BNA cookie (30 seconds)"):
                    st.markdown(
                        "1. Sign in to **app.bnamericas.com** in Chrome, "
                        "Edge, Brave, or Arc.\n"
                        "2. Press `F12` (Mac: `Cmd + Option + I`).\n"
                        "3. Click the **Console** tab.\n"
                        "4. Type: `copy(document.cookie)` then press "
                        "Enter.\n"
                        "5. The cookie is on your clipboard. Paste it "
                        "below and click **Save**."
                    )

                # ---- Paste box + buttons ----
                new_cookie = st.text_area(
                    "Paste fresh BNA session cookie",
                    value="",
                    height=110,
                    placeholder="_bna_session=...; cf_clearance=...; "
                                "XSRF-TOKEN=...",
                    key="admin_cookie_input",
                )
                _b1, _b2, _b3 = st.columns([1, 1, 4])
                with _b1:
                    if st.button(
                        "πŸ’Ύ Save", key="admin_save_btn", type="primary"
                    ):
                        cookie_clean = (new_cookie or "").strip()
                        if len(cookie_clean) < 50 or "=" not in cookie_clean:
                            st.error(
                                "That doesn't look like a cookie string. "
                                "It should be at least 50 characters and "
                                "contain `name=value` pairs."
                            )
                        else:
                            team_session.save_session(
                                cookie_clean,
                                refreshed_by=os.environ.get(
                                    "USER", "team-lead"
                                ),
                            )
                            st.success(
                                "Session saved. Researchers' next batch "
                                "will use it automatically."
                            )
                            st.rerun()
                with _b2:
                    if st.button("πŸ—‘ Clear", key="admin_clear_btn"):
                        team_session.clear_session()
                        st.info("Session cleared.")
                        st.rerun()

                # ---- Feedback inbox ----
                st.markdown(
                    "<div style='margin-top:28px; padding-top:18px; "
                    "border-top:1px solid #E5E7EB;'></div>",
                    unsafe_allow_html=True,
                )
                _fb_records = feedback_store.list_submissions()
                _fb_count = len(_fb_records)
                st.markdown(
                    f"<h3 style='color:#1E3A8A; margin-bottom:6px;'>"
                    f"πŸ’¬ Researcher feedback</h3>"
                    f"<p style='font-size:14px; color:#374151; margin-top:0;'>"
                    f"{_fb_count} submission{'s' if _fb_count != 1 else ''} on file. "
                    f"Edit Status and Notes inline, click Save changes, then "
                    f"download the Excel for your next meeting."
                    f"</p>",
                    unsafe_allow_html=True,
                )

                if _fb_count == 0:
                    st.caption(
                        "No researcher feedback has been submitted yet."
                    )
                else:
                    # Top action row: download buttons.
                    _dl1, _dl2, _ = st.columns([2, 2, 4])
                    with _dl1:
                        st.download_button(
                            "πŸ“Š  Download as Excel",
                            data=feedback_store.export_all_as_excel(),
                            file_name="bna_comparer_feedback.xlsx",
                            mime="application/vnd.openxmlformats-officedocument."
                                 "spreadsheetml.sheet",
                            key="admin_feedback_xlsx",
                            type="primary",
                        )
                    with _dl2:
                        st.download_button(
                            "⬇  Download attachments (.zip)",
                            data=feedback_store.collect_all_as_zip(),
                            file_name="bna_comparer_feedback.zip",
                            mime="application/zip",
                            key="admin_feedback_zip",
                            help="Per-submission folders with feedback.json + "
                                 "screenshots + technical files.",
                        )

                    # Build the editable table.
                    import pandas as pd
                    _rows = []
                    for rec in _fb_records:
                        f = rec.get("fields", {})
                        _rows.append({
                            "Submission ID": rec.get("submission_id", ""),
                            "Received (UTC)": (rec.get("received_at") or "")[:19],
                            "Researcher": f.get("researcher_name") or "Anonymous",
                            "Type": f.get("feedback_type") or "-",
                            "Severity": f.get("severity") or "-",
                            "Permalink": f.get("permalink") or "",
                            "Subject": f.get("subject") or "(no subject)",
                            "Comment": f.get("comment") or "",
                            "Attachments": len(rec.get("attachments", [])),
                            "Status": rec.get("status",
                                              feedback_store.DEFAULT_STATUS),
                            "Admin notes": rec.get("admin_notes", ""),
                        })
                    _df = pd.DataFrame(_rows)

                    edited = st.data_editor(
                        _df,
                        key="admin_fb_editor",
                        use_container_width=True,
                        hide_index=True,
                        column_config={
                            "Submission ID": st.column_config.TextColumn(
                                disabled=True, width="small"),
                            "Received (UTC)": st.column_config.TextColumn(
                                disabled=True, width="small"),
                            "Researcher": st.column_config.TextColumn(
                                disabled=True, width="medium"),
                            "Type": st.column_config.TextColumn(
                                disabled=True, width="small"),
                            "Severity": st.column_config.TextColumn(
                                disabled=True, width="small"),
                            "Permalink": st.column_config.TextColumn(
                                disabled=True, width="medium"),
                            "Subject": st.column_config.TextColumn(
                                disabled=True, width="medium"),
                            "Comment": st.column_config.TextColumn(
                                disabled=True, width="large"),
                            "Attachments": st.column_config.NumberColumn(
                                disabled=True, width="small"),
                            "Status": st.column_config.SelectboxColumn(
                                options=list(feedback_store.STATUS_OPTIONS),
                                required=True, width="small"),
                            "Admin notes": st.column_config.TextColumn(
                                width="large",
                                help="Your notes β€” visible only to you and "
                                     "anyone with admin access."),
                        },
                    )

                    if st.button(
                        "πŸ’Ύ  Save changes",
                        key="admin_fb_save",
                        type="primary",
                    ):
                        updates = {}
                        for _, row in edited.iterrows():
                            sid = row["Submission ID"]
                            updates[sid] = {
                                "status": row["Status"],
                                "admin_notes": row.get("Admin notes", "") or "",
                            }
                        n = feedback_store.update_many(updates)
                        st.success(f"Saved status and notes for {n} submission"
                                   f"{'s' if n != 1 else ''}.")
                        st.rerun()


# ---- The actual run --------------------------------------------------
if ss.trigger_run:
    ss.trigger_run = False
    ss.log_lines = []
    ss.progress_rows = []

    # Give this run a stable session id and join the queue.
    if not ss.get("queue_id"):
        ss.queue_id = f"q_{uuid.uuid4().hex[:12]}"
    sid = ss.queue_id
    queue_enqueue(sid)

    # If someone else is running right now, hold here and show a
    # waiting banner. The Streamlit thread blocks until our turn β€” that
    # is fine: this researcher can't click anything else mid-run anyway.
    with tab_inputs:
        wait_box = st.empty()
        try:
            pos = queue_position(sid)
            while pos > 0:
                ahead = pos
                wait_box.markdown(
                    f'<div class="status-banner running">'
                    f'<div class="pulse-dot"></div>'
                    f'<div><b>You\'re in the queue.</b> &nbsp;'
                    f'{ahead} batch{"es" if ahead != 1 else ""} ahead of you. '
                    f'Your run will start automatically β€” feel free to '
                    f'leave this tab open.</div>'
                    f'</div>',
                    unsafe_allow_html=True,
                )
                time.sleep(2)
                pos = queue_position(sid)
            wait_box.empty()
            queue_mark_started(sid)
        except Exception:
            queue_dequeue(sid)
            ss.queue_id = None
            raise

    # Placeholder in the Inputs tab so the polling loop can push live
    # error excerpts there without the researcher having to switch tabs.
    inputs_error_box = tab_inputs.empty()

    try:
        with tab_log:
            log_box = st.empty()
            log_box.code("[INFO] Run starting in subprocess...", language="text")

            with tempfile.TemporaryDirectory(prefix="bna_web_") as tmp:
                tmp_path = Path(tmp)
                # Strict single-ZIP validation + extract Input/Output/Summary
                staged_root = _stage_zip(ai_zip, tmp_path / "staged")
                layout = ss.zip_layout
                # AI source Excels are inside Output/ (the AI pipeline's
                # outputs become the Comparator's inputs).
                ai_dir = Path(layout["output"])
                # The engine now organises its output into:
                #   <engine_out>/AI Output folder/         (copy of AI source)
                #   <engine_out>/Comparer Tool Output folder/   (engine results)
                # We zip engine_out directly for download β€” researcher
                # gets a clean 2-sub-folder archive.
                engine_out = tmp_path / "results"
                engine_out.mkdir(parents=True, exist_ok=True)
                tie_path = HERE / "resources" / "TIE_Requirements.xlsx"

                def _progress_cb(info):
                    ss.progress_rows.append(info)

                summary, error = _run_batch_in_subprocess(
                    ai_dir=ai_dir, out_dir=engine_out, tie_path=tie_path,
                    email=bna_email, password=bna_password,
                    lang=lang, log_box=log_box, progress_callback=_progress_cb,
                    inputs_error_box=inputs_error_box,
                )
                if error:
                    ss.log_lines.append(f"[ERROR] {error}")
                    ss.run_status = "error"
                    ss.run_error_msg = error
                else:
                    # Engine has already arranged engine_out as the
                    # AI Output folder + Comparer Tool Output folder layout.
                    zip_bytes = _zip_directory(engine_out)
                    ss.last_zip_bytes = zip_bytes
                    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
                    ss.last_zip_name = f"bna_comparator_results_{ts}.zip"
                    ss.last_run = summary
                    ss.run_status = "success"
                    ss.log_lines.append(
                        f"[INFO] Done -- {summary['ok']}/{summary['total']} OK, "
                        f"{summary['failed']} failed."
                    )
    finally:
        queue_dequeue(sid)
        ss.queue_id = None

    st.rerun()