File size: 53,620 Bytes
04306f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Evaluate candidate captions against TCA-Bench GT.

Reads candidate captions from captions/{folder}/captions.json,
evaluates them against GT from gt/, and outputs results to
results/{name}/{timestamp}/.

Usage:
    python evaluate.py --input my-model             # folder name under captions/
    python evaluate.py -i my-model --name run1      # custom result folder name
    python evaluate.py -i my-model --explain        # include per-dimension explanations
    python evaluate.py -i my-model --stage 1v 2     # only run visual + binding eval
    python evaluate.py -i my-model --dry-run        # preview what would run
    python evaluate.py -i my-model --force          # re-evaluate even if results exist

Stages:
    1v  = Stage 1 Visual (3 dimensions, 0-10 each)
    1a  = Stage 1 Audio  (2 dimensions, 0-10 each)
    2   = Stage 2 AV-Binding (correct/total ratio)
    3   = Stage 3 Temporal   (correct/total ratio)

Output structure:
    results/{name}/{YYYY-MM-DD-HH-MM-SS}/
    ├── summary.json       # Aggregate scores + metadata
    ├── report.md          # Human-readable report
    └── details.json       # Per-video parsed results (merged)
"""

from __future__ import annotations

import argparse
import json
import os
import random
import re
import shutil
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar

from rich.console import Console
from rich.panel import Panel
from rich.progress import (
    BarColumn,
    MofNCompleteColumn,
    Progress,
    SpinnerColumn,
    TaskProgressColumn,
    TextColumn,
    TimeElapsedColumn,
    TimeRemainingColumn,
)
from rich.table import Table

console = Console(highlight=False)

# ---------------------------------------------------------------------------
# OpenAI-compatible judge API configuration
# ---------------------------------------------------------------------------
# Set credentials through the environment before running the evaluator.
BASE_URL = (
    os.getenv("TCA_EVAL_BASE_URL")
    or os.getenv("OPENAI_BASE_URL")
    or "https://openrouter.ai/api/v1"
)
API_KEY = (
    os.getenv("TCA_EVAL_API_KEY")
    or os.getenv("OPENROUTER_API_KEY")
    or os.getenv("OPENAI_API_KEY")
    or ""
)
MODEL = os.getenv("TCA_EVAL_MODEL", "gpt-4.1")

# ---------------------------------------------------------------------------
# Paths (relative to this script's location)
# ---------------------------------------------------------------------------
SCRIPT_DIR  = Path(__file__).resolve().parent        # scripts/
PROMPTS_DIR = SCRIPT_DIR / "prompts"                 # scripts/prompts/
MAIN_DIR    = SCRIPT_DIR.parent                      # benchmark root
GT_DIR      = MAIN_DIR / "gt"                        # gt/
CAPTIONS_DIR = MAIN_DIR / "captions"                 # captions/
RESULTS_DIR = MAIN_DIR / "results"                   # results/

# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
ALL_STAGES = ["1v", "1a", "2", "3"]
DEFAULT_CONCURRENCY = 16
MAX_RETRIES = 60
RETRY_DELAY_MIN = 2
RETRY_DELAY_MAX = 5
T = TypeVar("T")

# Thread-safe retry stats
_retry_lock = threading.Lock()
_retry_active: Dict[str, int] = {}
_retry_total = 0

# Dimension keys
VISUAL_DIMS = ["subject_and_action", "scene_and_atmosphere", "cinematography"]
AUDIO_DIMS = ["transcription_accuracy", "tone_and_emotion"]

VISUAL_DIM_LABELS = {
    "subject_and_action": "Subject+Action",
    "scene_and_atmosphere": "Scene+Atmos",
    "cinematography": "Cinematography",
}
AUDIO_DIM_LABELS = {
    "transcription_accuracy": "Transcription",
    "tone_and_emotion": "Tone+Emotion",
}


# ---------------------------------------------------------------------------
# File I/O helpers
# ---------------------------------------------------------------------------

def load_json(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def load_captions(path: Path) -> List[Dict]:
    """Load captions from JSON array or JSONL, normalising key names.

    Accepts:
      - Standard JSON array: [{"id": ..., "caption": ...}, ...]
      - JSONL (one JSON object per line)
      - 'video_id' as alias for 'id'
      - Strips .mp4 / other video extensions from id values
    """
    text = path.read_text(encoding="utf-8").strip()
    items: List[Dict] = []

    # Try standard JSON first
    try:
        parsed = json.loads(text)
        if isinstance(parsed, list):
            items = parsed
        elif isinstance(parsed, dict):
            items = [parsed]
        else:
            raise ValueError(f"Unexpected top-level type: {type(parsed)}")
    except json.JSONDecodeError:
        # Fall back to JSONL
        for lineno, line in enumerate(text.splitlines(), 1):
            line = line.strip()
            if not line:
                continue
            try:
                obj = json.loads(line)
                items.append(obj)
            except json.JSONDecodeError as e:
                console.print(f"[yellow]⚠ Skipping line {lineno}: {e}[/yellow]")

    # Normalise keys: video_id -> id
    normalised: List[Dict] = []
    for item in items:
        if not isinstance(item, dict):
            continue
        vid = item.get("id") or item.get("video_id", "")
        caption = item.get("caption", "")
        if not vid:
            continue
        normalised.append({"id": _normalize_id(str(vid)), "caption": caption})

    return normalised


def save_json(path: Path, data: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def save_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def extract_json_block(text: str) -> str:
    """Strip markdown code fences from LLM JSON output."""
    t = text.strip()
    if t.startswith("```json"):
        t = t[7:]
    elif t.startswith("```"):
        t = t[3:]
    if t.endswith("```"):
        t = t[:-3]
    return t.strip()


# ---------------------------------------------------------------------------
# OpenAI-compatible API client
# ---------------------------------------------------------------------------

def _build_client(base_url: str, api_key: str):
    """Build an OpenAI-compatible client."""
    try:
        from openai import OpenAI
    except ImportError:
        console.print("[bold red]✗[/bold red] openai package not installed. "
                      "Run: pip install openai")
        sys.exit(1)
    return OpenAI(base_url=base_url, api_key=api_key)


def call_llm(
    client,
    model: str,
    prompt: str,
    *,
    temperature: float = 1.0,
    max_retries: int = MAX_RETRIES,
) -> str:
    """Call LLM via OpenAI-compatible API with retry. Returns text response."""
    global _retry_total
    tid = str(threading.current_thread().ident)
    last_err: Optional[Exception] = None

    for attempt in range(max_retries):
        try:
            # Original
            resp = client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                temperature=temperature,
            )

            # My Co-worker
            # messages = [{"role": "user", "content": prompt}]
            # payload  = create_gemini_payload(model, messages, temperature)
            # resp     = requests.post(client.url, headers=client.headers, json=payload, timeout=240)

            text = resp.choices[0].message.content
            if text:
                with _retry_lock:
                    _retry_active.pop(tid, None)
                return text
            raise RuntimeError("Empty response from LLM")
        except Exception as e:
            last_err = e
            if attempt < max_retries - 1:
                delay = random.uniform(RETRY_DELAY_MIN, RETRY_DELAY_MAX)
                with _retry_lock:
                    _retry_active[tid] = attempt + 1
                    _retry_total += 1
                time.sleep(delay)

    with _retry_lock:
        _retry_active.pop(tid, None)
    raise RuntimeError(f"LLM call failed after {max_retries} retries: {last_err}")


# ---------------------------------------------------------------------------
# Prompt loading with explain toggle
# ---------------------------------------------------------------------------

def _load_local_prompt(name: str) -> str:
    """Load a prompt from scripts/prompts/."""
    p = PROMPTS_DIR / name
    if not p.exists():
        raise FileNotFoundError(f"Prompt not found: {p}")
    return p.read_text(encoding="utf-8")


def get_prompt(stage: str, *, explain: bool) -> str:
    """Return the appropriate prompt template for a stage."""
    suffix = "" if explain else "-score-only"
    mapping = {
        "1v": f"stage-1-visual-eval{suffix}.txt",
        "1a": f"stage-1-audio-eval{suffix}.txt",
        "2":  f"stage-2-eval{suffix}.txt",
        "3":  f"stage-3-eval{suffix}.txt",
    }
    return _load_local_prompt(mapping[stage])


# ---------------------------------------------------------------------------
# Rich concurrent runner
# ---------------------------------------------------------------------------

def run_concurrent_rich(
    tasks: List[Tuple[str, Callable]],
    *,
    max_workers: int = DEFAULT_CONCURRENCY,
    label: str = "Evaluating",
) -> Dict[str, Any]:
    """Run named tasks concurrently with a rich progress bar."""
    total = len(tasks)
    results: Dict[str, Any] = {}
    failed: List[Tuple[str, Exception]] = []

    with Progress(
        SpinnerColumn(spinner_name="dots", style="bold cyan"),
        TextColumn("[bold cyan]{task.description}"),
        BarColumn(bar_width=28, style="cyan", complete_style="green",
                  finished_style="bright_green"),
        MofNCompleteColumn(),
        TaskProgressColumn(),
        TimeElapsedColumn(),
        TimeRemainingColumn(),
        TextColumn("{task.fields[status]}"),
        console=console,
        refresh_per_second=10,
        transient=False,
    ) as progress:
        task_id = progress.add_task(label, total=total, status="")

        def _status_text(last_name: str, ok: bool):
            short = last_name.split("__")[-1] if "__" in last_name else last_name[-30:]
            icon = "[green]✓[/green]" if ok else "[red]✗[/red]"
            with _retry_lock:
                active = len(_retry_active)
                total_r = _retry_total
            retry_part = f"  [yellow]⟳ {active} retrying ({total_r} total)[/yellow]" if active else ""
            return f"{icon} [dim]{short}[/dim]{retry_part}"

        with ThreadPoolExecutor(max_workers=max_workers) as pool:
            future_map = {pool.submit(fn): name for name, fn in tasks}
            for future in as_completed(future_map):
                name = future_map[future]
                try:
                    results[name] = future.result()
                    progress.update(task_id, advance=1, status=_status_text(name, True))
                except Exception as exc:
                    failed.append((name, exc))
                    results[name] = {"_error": str(exc)}
                    progress.update(task_id, advance=1, status=_status_text(name, False))

    if failed:
        console.print(f"\n[bold red]⚠ {len(failed)} task(s) failed:[/bold red]")
        for name, exc in failed:
            console.print(f"  [red]•[/red] {name}: {exc}")

    return results


# ---------------------------------------------------------------------------
# Score parsing
# ---------------------------------------------------------------------------

def parse_visual_json(text: str, *, explain: bool) -> Dict[str, Any]:
    fallback = {dim: {"score": None, "reason": "parse error"} for dim in VISUAL_DIMS}
    fallback["overall_average"] = None
    try:
        data = json.loads(extract_json_block(text))
    except (json.JSONDecodeError, ValueError):
        return fallback

    result: Dict[str, Any] = {}
    for dim in VISUAL_DIMS:
        entry = data.get(dim, {})
        if isinstance(entry, dict):
            score = entry.get("score")
            reason = entry.get("reason", "")
            score = int(score) if isinstance(score, (int, float)) else None
        elif isinstance(entry, (int, float)):
            score = int(entry)
            reason = ""
        else:
            score, reason = None, "missing"
        result[dim] = {"score": score, "reason": reason}

    valid = [result[d]["score"] for d in VISUAL_DIMS if result[d]["score"] is not None]
    oa = data.get("overall_average")
    if isinstance(oa, (int, float)):
        result["overall_average"] = round(float(oa), 2)
    elif valid:
        result["overall_average"] = round(sum(valid) / len(valid), 2)
    else:
        result["overall_average"] = None

    return result


def parse_audio_json(text: str, *, explain: bool) -> Dict[str, Any]:
    fallback = {dim: {"score": None, "reason": "parse error"} for dim in AUDIO_DIMS}
    fallback["overall_average"] = None
    try:
        data = json.loads(extract_json_block(text))
    except (json.JSONDecodeError, ValueError):
        return fallback

    result: Dict[str, Any] = {}
    for dim in AUDIO_DIMS:
        entry = data.get(dim, {})
        if isinstance(entry, dict):
            score = entry.get("score")
            reason = entry.get("reason", "")
            score = int(score) if isinstance(score, (int, float)) else None
        elif isinstance(entry, (int, float)):
            score = int(entry)
            reason = ""
        else:
            score, reason = None, "missing"
        result[dim] = {"score": score, "reason": reason}

    valid = [result[d]["score"] for d in AUDIO_DIMS if result[d]["score"] is not None]
    result["overall_average"] = round(sum(valid) / len(valid), 2) if valid else None
    return result


def parse_stage2_json(text: str, *, explain: bool) -> Tuple[Optional[int], Optional[int], str, List[Dict[str, Any]]]:
    """Parse Stage-2 JSON response with 3-way verdict support.

    Supports both old ("correct": bool) and new ("verdict": str) formats.
    Score = correct / (correct + incorrect).  Skipped items excluded from denominator.
    Returns (correct, evaluated, summary, results_list).
    """
    try:
        data = json.loads(extract_json_block(text))
    except (json.JSONDecodeError, ValueError):
        return None, None, "parse error", []

    results = data.get("results") if isinstance(data, dict) else None
    if not isinstance(results, list):
        return None, None, "missing results", []

    correct = 0
    incorrect_indices: List[int] = []
    skipped = 0
    parsed_items: List[Dict[str, Any]] = []
    for item in results:
        if not isinstance(item, dict):
            continue
        # Support both old ("correct": bool) and new ("verdict": str) formats
        verdict_raw = item.get("verdict")
        if verdict_raw is not None:
            verdict = str(verdict_raw).strip().lower()
        elif "correct" in item:
            verdict = "correct" if item["correct"] else "incorrect"
        else:
            continue

        idx = item.get("index")

        if verdict == "skipped":
            skipped += 1
            parsed_items.append({
                "index": idx,
                "verdict": "skipped",
                "correct": False,
                "reason": item.get("reason", ""),
            })
        elif verdict == "correct":
            correct += 1
            parsed_items.append({
                "index": idx,
                "verdict": "correct",
                "correct": True,
                "reason": item.get("reason", ""),
            })
        else:  # incorrect
            if isinstance(idx, int):
                incorrect_indices.append(idx)
            parsed_items.append({
                "index": idx,
                "verdict": "incorrect",
                "correct": False,
                "reason": item.get("reason", ""),
            })

    incorrect_count = sum(1 for p in parsed_items if p["verdict"] == "incorrect")
    evaluated = correct + incorrect_count

    if evaluated == 0 and skipped == 0:
        return None, None, "empty results", []

    parts = [f"{correct}/{evaluated}"]
    if incorrect_indices:
        parts.append(f"incorrect: {', '.join(map(str, incorrect_indices))}")
    if skipped:
        parts.append(f"skipped: {skipped}")
    summary = "; ".join(parts)
    return correct, evaluated, summary, parsed_items


def parse_ratio(text: str) -> Tuple[Optional[int], Optional[int], str]:
    m = re.search(r"(\d+)\s*/\s*(\d+)", text)
    if m:
        return int(m.group(1)), int(m.group(2)), text.strip().split("\n")[0]
    return None, None, text.strip().split("\n")[0]


def parse_stage3_json(text: str) -> Tuple[Optional[int], Optional[int], str, List[Dict[str, Any]]]:
    """Parse structured Stage-3 JSON response (explain mode).

    Supports 3-way verdicts: correct / incorrect / skipped.
    Score = correct / (correct + incorrect).  Skipped items are excluded from the denominator.
    Returns (correct, evaluated, summary, results_list).
    """
    try:
        data = json.loads(extract_json_block(text))
    except (json.JSONDecodeError, ValueError):
        return None, None, "parse error", []

    results = data.get("results") if isinstance(data, dict) else None
    if not isinstance(results, list):
        return None, None, "missing results", []

    correct = 0
    incorrect_indices: List[int] = []
    skipped = 0
    parsed_items: List[Dict[str, Any]] = []
    for item in results:
        if not isinstance(item, dict):
            continue
        # Support both old ("correct": bool) and new ("verdict": str) formats
        verdict_raw = item.get("verdict")
        if verdict_raw is not None:
            verdict = str(verdict_raw).strip().lower()
        elif "correct" in item:
            verdict = "correct" if bool(item["correct"]) else "incorrect"
        else:
            continue

        idx = item.get("index")

        if verdict == "skipped":
            skipped += 1
            parsed_items.append({
                "index": idx,
                "correct": None,
                "verdict": "skipped",
                "reason": item.get("reason", ""),
            })
        elif verdict == "correct":
            correct += 1
            parsed_items.append({
                "index": idx,
                "correct": True,
                "verdict": "correct",
                "reason": item.get("reason", ""),
            })
        else:  # incorrect
            if isinstance(idx, int):
                incorrect_indices.append(idx)
            parsed_items.append({
                "index": idx,
                "correct": False,
                "verdict": "incorrect",
                "reason": item.get("reason", ""),
            })

    evaluated = correct + len(incorrect_indices) + sum(
        1 for p in parsed_items if p["verdict"] == "incorrect" and not isinstance(p["index"], int)
    )
    # Simpler: evaluated = correct + incorrect_count
    incorrect_count = sum(1 for p in parsed_items if p["verdict"] == "incorrect")
    evaluated = correct + incorrect_count

    if evaluated == 0 and skipped == 0:
        return None, None, "empty results", []

    parts = [f"{correct}/{evaluated}"]
    if incorrect_indices:
        parts.append(f"incorrect: {', '.join(map(str, incorrect_indices))}")
    if skipped:
        parts.append(f"skipped: {skipped}")
    summary = "; ".join(parts)
    return correct, evaluated, summary, parsed_items


# ---------------------------------------------------------------------------
# Single-video evaluation
# ---------------------------------------------------------------------------

def evaluate_one_video(
    vid: str,
    caption: str,
    client,
    model: str,
    *,
    stages: List[str],
    explain: bool,
    gt_captions: Dict[str, str],
    gt_stage2: Dict[str, str],
    gt_stage3: Dict[str, str],
    details_dir: Path,
    save_raw: bool = False,
) -> Dict[str, Any]:
    """Run requested eval stages for one video. Saves detail JSON immediately."""
    result: Dict[str, Any] = {"id": vid}

    gt0 = gt_captions.get(vid, "")
    gt2 = gt_stage2.get(vid, "")
    gt3 = gt_stage3.get(vid, "")

    calls: Dict[str, str] = {}
    if "1v" in stages:
        p = get_prompt("1v", explain=explain)
        calls["1v"] = p.replace("{{Ground_Truth}}", gt0).replace("{{Candidate}}", caption)
    if "1a" in stages:
        p = get_prompt("1a", explain=explain)
        calls["1a"] = p.replace("{{Ground_Truth}}", gt0).replace("{{Candidate}}", caption)
    if "2" in stages:
        p = get_prompt("2", explain=explain)
        calls["2"] = p.replace("{{Candidate}}", caption).replace("{{Ground_Truth}}", gt2)
    if "3" in stages:
        # Stage 3 always uses the structured (explain) prompt because the F1
        # metric requires per-relation verdicts (correct/incorrect/skipped).
        p = get_prompt("3", explain=True)
        calls["3"] = p.replace("{{Ground_Truth_Relations}}", gt3).replace("{{Candidate}}", caption)

    raw_responses: Dict[str, str] = {}
    with ThreadPoolExecutor(max_workers=len(calls)) as pool:
        futs = {
            pool.submit(call_llm, client, model, prompt): stage
            for stage, prompt in calls.items()
        }
        for fut in as_completed(futs):
            stage = futs[fut]
            try:
                raw_responses[stage] = fut.result()
            except Exception as e:
                raw_responses[stage] = f"ERROR: {e}"

    # Parse
    if "1v" in raw_responses:
        vis = parse_visual_json(raw_responses["1v"], explain=explain)
        s1v_entry: Dict[str, Any] = {
            "dimensions": {d: vis[d] for d in VISUAL_DIMS},
            "overall_average": vis["overall_average"],
        }
        if save_raw:
            s1v_entry["raw"] = raw_responses["1v"].strip()
        result["stage1_visual"] = s1v_entry
    if "1a" in raw_responses:
        aud = parse_audio_json(raw_responses["1a"], explain=explain)
        s1a_entry: Dict[str, Any] = {
            "dimensions": {d: aud[d] for d in AUDIO_DIMS},
            "overall_average": aud["overall_average"],
        }
        if save_raw:
            s1a_entry["raw"] = raw_responses["1a"].strip()
        result["stage1_audio"] = s1a_entry
    if "2" in raw_responses:
        s2_num, s2_den, s2_summary, s2_items = parse_stage2_json(raw_responses["2"], explain=explain)
        s2_entry: Dict[str, Any] = {
            "numerator": s2_num, "denominator": s2_den,
            "ratio": f"{s2_num}/{s2_den}" if s2_num is not None else "N/A",
            "summary": s2_summary,
            "results": s2_items,
        }
        if save_raw:
            s2_entry["raw"] = raw_responses["2"].strip()
        result["stage2"] = s2_entry
    if "3" in raw_responses:
        # Always parse as structured JSON (explain prompt is always used for S3)
        s3_num, s3_den, s3_summary, s3_items = parse_stage3_json(raw_responses["3"])
        if not explain:
            # Strip verbose reason strings when not in explain mode
            s3_items = [{k: v for k, v in it.items() if k != "reason"} for it in s3_items]
        s3_entry: Dict[str, Any] = {
            "numerator": s3_num, "denominator": s3_den,
            "ratio": f"{s3_num}/{s3_den}" if s3_num is not None else "N/A",
            "summary": s3_summary,
            "results": s3_items,
        }
        if save_raw:
            s3_entry["raw"] = raw_responses["3"].strip()
        result["stage3"] = s3_entry

    save_json(details_dir / f"{vid}.json", result)
    return result


# ---------------------------------------------------------------------------
# Load GT data (consolidated files)
# ---------------------------------------------------------------------------

def _normalize_id(vid: str) -> str:
    """Strip .mp4 (or other video extensions) so IDs match regardless of suffix."""
    for ext in (".mp4", ".mkv", ".webm", ".avi", ".mov"):
        if vid.endswith(ext):
            return vid[: -len(ext)]
    return vid


def load_gt_map(path: Path, caption_key: str = "caption") -> Dict[str, str]:
    if not path.exists():
        return {}
    data = load_json(path)
    out: Dict[str, str] = {}
    for item in data:
        if isinstance(item, dict) and "id" in item:
            val = item.get(caption_key, "")
            if isinstance(val, dict) or isinstance(val, list):
                val = json.dumps(val, ensure_ascii=False)
            out[_normalize_id(item["id"])] = str(val)
    return out


def load_gt_map_full(path: Path) -> Dict[str, str]:
    if not path.exists():
        return {}
    data = load_json(path)
    out: Dict[str, str] = {}
    for item in data:
        if isinstance(item, dict) and "id" in item:
            entry = {k: v for k, v in item.items() if k != "id"}
            out[_normalize_id(item["id"])] = json.dumps(entry, ensure_ascii=False)
    return out


def load_gt_raw(path: Path) -> Dict[str, Dict[str, Any]]:
    """Load GT as raw dicts (not stringified) keyed by normalised ID."""
    if not path.exists():
        return {}
    data = load_json(path)
    out: Dict[str, Dict[str, Any]] = {}
    for item in data:
        if isinstance(item, dict) and "id" in item:
            out[_normalize_id(item["id"])] = {k: v for k, v in item.items() if k != "id"}
    return out


# ---------------------------------------------------------------------------
# Aggregate summary
# ---------------------------------------------------------------------------

def compute_summary(
    video_results: List[Dict[str, Any]],
    stages: List[str],
    *,
    gt_stage2_raw: Optional[Dict[str, Any]] = None,
    gt_stage3_raw: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    n = len(video_results)
    if n == 0:
        return {"num_videos": 0}

    def safe_avg(vals):
        return round(sum(vals) / len(vals), 3) if vals else None

    def ratio_avg(pairs):
        ratios = [n / d for n, d in pairs if d and d > 0]
        return round(sum(ratios) / len(ratios), 3) if ratios else None

    def _f1(prec: float, cov: float) -> float:
        return round(2 * prec * cov / (prec + cov), 3) if (prec + cov) > 0 else 0.0

    summary: Dict[str, Any] = {"num_videos": n}

    if "1v" in stages:
        vis_dim_scores: Dict[str, List[int]] = {d: [] for d in VISUAL_DIMS}
        vis_overall: List[float] = []
        for r in video_results:
            sv = r.get("stage1_visual", {})
            for d in VISUAL_DIMS:
                s = sv.get("dimensions", {}).get(d, {}).get("score")
                if s is not None:
                    vis_dim_scores[d].append(s)
            oa = sv.get("overall_average")
            if oa is not None:
                vis_overall.append(oa)
        summary["stage1_visual"] = {
            "overall_mean": safe_avg(vis_overall),
            "dimensions": {
                d: {"mean": safe_avg(vis_dim_scores[d]), "valid_count": len(vis_dim_scores[d])}
                for d in VISUAL_DIMS
            },
            "valid_count": len(vis_overall),
            "max_possible": 10,
        }

    if "1a" in stages:
        aud_scores = [
            r.get("stage1_audio", {}).get("overall_average")
            for r in video_results
        ]
        aud_scores = [s for s in aud_scores if s is not None]
        aud_dim_scores: Dict[str, List[int]] = {d: [] for d in AUDIO_DIMS}
        for r in video_results:
            sa = r.get("stage1_audio", {})
            for d in AUDIO_DIMS:
                s = sa.get("dimensions", {}).get(d, {}).get("score")
                if s is not None:
                    aud_dim_scores[d].append(s)
        summary["stage1_audio"] = {
            "overall_mean": safe_avg(aud_scores),
            "dimensions": {
                d: {"mean": safe_avg(aud_dim_scores[d]), "valid_count": len(aud_dim_scores[d])}
                for d in AUDIO_DIMS
            },
            "valid_count": len(aud_scores),
            "max_possible": 10,
        }

    # ------------------------------------------------------------------
    # Stage 2: Binding — Accuracy (correct / total_gt)
    #   Overall + character / non-character sub-dimensions
    # ------------------------------------------------------------------
    if "2" in stages:
        # Sub-dimension counters: character vs non-character
        sub: Dict[str, Dict[str, int]] = {
            "character": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0},
            "non_character": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0},
        }
        for r in video_results:
            vid = r["id"]
            items = r.get("stage2", {}).get("results", [])
            gt_raw = (gt_stage2_raw or {}).get(vid)
            if gt_raw is None or not items:
                continue
            gt_sounds = gt_raw.get("sounds", [])
            for item in items:
                idx = item.get("index")
                if idx is None or idx >= len(gt_sounds):
                    continue
                src = gt_sounds[idx].get("source", "")
                is_char = src.startswith("Foreground character")
                cat = "character" if is_char else "non_character"
                sub[cat]["total_gt"] += 1
                verdict = item.get("verdict", "correct" if item.get("correct") else "incorrect")
                if verdict == "correct":
                    sub[cat]["correct"] += 1
                elif verdict == "incorrect":
                    sub[cat]["incorrect"] += 1
                else:
                    sub[cat]["skipped"] += 1

        # Compute accuracy = correct / total_gt for each sub-dimension
        sub_summary: Dict[str, Any] = {}
        for cat in ("character", "non_character"):
            c = sub[cat]["correct"]
            i = sub[cat]["incorrect"]
            s = sub[cat]["skipped"]
            t = sub[cat]["total_gt"]
            accuracy = round(c / t, 3) if t > 0 else None
            sub_summary[cat] = {
                "correct": c, "incorrect": i, "skipped": s, "total_gt": t,
                "accuracy": accuracy,
            }

        # Overall accuracy = pooled correct / total_gt
        total_c = sum(sub[cat]["correct"] for cat in ("character", "non_character"))
        total_gt = sum(sub[cat]["total_gt"] for cat in ("character", "non_character"))
        overall_acc = round(total_c / total_gt, 3) if total_gt > 0 else None

        summary["stage2_binding"] = {
            "accuracy": overall_acc,
            "correct": total_c,
            "total_gt": total_gt,
            "valid_count": sum(1 for r in video_results if r.get("stage2", {}).get("numerator") is not None),
            "character": sub_summary["character"],
            "non_character": sub_summary["non_character"],
        }

    # ------------------------------------------------------------------
    # Stage 3: Temporal — overall + sequential / simultaneous F1
    # ------------------------------------------------------------------
    if "3" in stages:
        s3_ratios = [
            (r["stage3"]["numerator"], r["stage3"]["denominator"])
            for r in video_results if r.get("stage3", {}).get("numerator") is not None
        ]
        # Sub-dimension: sequential vs simultaneous
        SEQUENTIAL_TYPES = {"A_triggers_V", "V_triggers_A", "A_triggers_A", "V_triggers_V"}
        SIMULTANEOUS_TYPES = {"AV_simultaneous"}
        sub: Dict[str, Dict[str, int]] = {
            "sequential": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0},
            "simultaneous": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0},
        }
        for r in video_results:
            vid = r["id"]
            items = r.get("stage3", {}).get("results", [])
            gt_raw = (gt_stage3_raw or {}).get(vid)
            if gt_raw is None or not items:
                continue
            gt_rels = gt_raw.get("sequential_relations", gt_raw.get("relations", []))
            for item in items:
                idx = item.get("index")
                if idx is None or idx >= len(gt_rels):
                    continue
                rtype = gt_rels[idx].get("type", "")
                if rtype in SEQUENTIAL_TYPES:
                    cat = "sequential"
                elif rtype in SIMULTANEOUS_TYPES:
                    cat = "simultaneous"
                else:
                    continue
                sub[cat]["total_gt"] += 1
                verdict = item.get("verdict", "correct" if item.get("correct") else "incorrect")
                if verdict == "correct":
                    sub[cat]["correct"] += 1
                elif verdict == "incorrect":
                    sub[cat]["incorrect"] += 1
                else:
                    sub[cat]["skipped"] += 1
        # Compute precision, coverage, F1 for each sub-dimension
        sub_summary: Dict[str, Any] = {}
        for cat in ("sequential", "simultaneous"):
            c = sub[cat]["correct"]
            i = sub[cat]["incorrect"]
            s = sub[cat]["skipped"]
            t = sub[cat]["total_gt"]
            evaluated = c + i
            precision = round(c / evaluated, 3) if evaluated > 0 else None
            coverage = round(evaluated / t, 3) if t > 0 else None
            f1 = _f1(precision, coverage) if (precision is not None and coverage is not None) else None
            sub_summary[cat] = {
                "correct": c, "incorrect": i, "skipped": s, "total_gt": t,
                "precision": precision, "coverage": coverage, "f1": f1,
            }
        # Overall F1 = pooled from all items (naturally weighted by category size)
        total_c = sum(sub[cat]["correct"] for cat in ("sequential", "simultaneous"))
        total_i = sum(sub[cat]["incorrect"] for cat in ("sequential", "simultaneous"))
        total_gt = sum(sub[cat]["total_gt"] for cat in ("sequential", "simultaneous"))
        total_eval = total_c + total_i
        overall_prec = round(total_c / total_eval, 3) if total_eval > 0 else None
        overall_cov = round(total_eval / total_gt, 3) if total_gt > 0 else None
        overall_f1 = _f1(overall_prec, overall_cov) if (overall_prec is not None and overall_cov is not None) else None
        summary["stage3_temporal"] = {
            "f1": overall_f1,
            "precision": overall_prec,
            "coverage": overall_cov,
            "valid_count": len(s3_ratios),
            "sequential": sub_summary["sequential"],
            "simultaneous": sub_summary["simultaneous"],
        }

    return summary


# ---------------------------------------------------------------------------
# Markdown report
# ---------------------------------------------------------------------------

def _render_score_table_md(
    summary: Dict[str, Any],
    stages: List[str],
    *,
    title: str = "Aggregate Scores",
) -> List[str]:
    """Render a Markdown score table for one summary dict."""
    lines: List[str] = []
    lines.append(f"## {title}\n")
    lines.append("| Metric | Score |")
    lines.append("|--------|-------|")

    def fmt_mean(val, mx=None):
        if val is None:
            return "N/A"
        return f"{val:.2f} / {mx}" if mx else f"{val:.3f}"

    if "1v" in stages:
        s1v = summary.get("stage1_visual", {})
        lines.append(f"| **Stage 1 Visual Overall (0-10)** | {fmt_mean(s1v.get('overall_mean'), 10)} |")
        for d in VISUAL_DIMS:
            dm = s1v.get("dimensions", {}).get(d, {}).get("mean")
            lines.append(f"|   ↳ {VISUAL_DIM_LABELS[d]} | {fmt_mean(dm, 10)} |")

    if "1a" in stages:
        s1a = summary.get("stage1_audio", {})
        lines.append(f"| **Stage 1 Audio Overall (0-10)** | {fmt_mean(s1a.get('overall_mean'), 10)} |")
        for d in AUDIO_DIMS:
            dm = s1a.get("dimensions", {}).get(d, {}).get("mean")
            lines.append(f"|   ↳ {AUDIO_DIM_LABELS[d]} | {fmt_mean(dm, 10)} |")

    if "2" in stages:
        s2 = summary.get("stage2_binding", {})
        lines.append(f"| **Stage 2 AV-Binding Accuracy** | {fmt_mean(s2.get('accuracy'))} |")
        char = s2.get("character", {})
        nchar = s2.get("non_character", {})
        lines.append(f"|   ↳ Character Acc | {fmt_mean(char.get('accuracy'))} "
                      f"({char.get('correct', 0)}/{char.get('total_gt', 0)}) |")
        lines.append(f"|   ↳ Non-Character Acc | {fmt_mean(nchar.get('accuracy'))} "
                      f"({nchar.get('correct', 0)}/{nchar.get('total_gt', 0)}) |")
    if "3" in stages:
        s3 = summary.get("stage3_temporal", {})
        lines.append(f"| **Stage 3 Temporal F1** | {fmt_mean(s3.get('f1'))} |")
        seq = s3.get("sequential", {})
        sim = s3.get("simultaneous", {})
        lines.append(f"|   ↳ Sequential F1 | {fmt_mean(seq.get('f1'))} "
                      f"(P={fmt_mean(seq.get('precision'))} C={fmt_mean(seq.get('coverage'))}) |")
        lines.append(f"|   ↳ Simultaneous F1 | {fmt_mean(sim.get('f1'))} "
                      f"(P={fmt_mean(sim.get('precision'))} C={fmt_mean(sim.get('coverage'))}) |")

    lines.append("")
    return lines


def generate_report_md(
    summary: Dict[str, Any],
    video_results: List[Dict[str, Any]],
    meta: Dict[str, Any],
    stages: List[str],
) -> str:
    lines: List[str] = []
    lines.append("# TCA-Bench Evaluation Report\n")
    lines.append(f"- **Run name**: `{meta.get('run_name', 'N/A')}`")
    lines.append(f"- **Timestamp**: {meta.get('timestamp', 'N/A')}")
    lines.append(f"- **Judge model**: {meta.get('judge_model', 'N/A')}")
    lines.append(f"- **Videos evaluated**: {summary.get('num_videos', 0)}")
    lines.append(f"- **Stages**: {', '.join(stages)}")
    lines.append(f"- **Explain mode**: {meta.get('explain', False)}\n")

    lines += _render_score_table_md(summary, stages, title="Aggregate Scores (All)")

    lines.append("## Per-Video Results\n")
    header = ["ID"]
    if "1v" in stages:
        header += [VISUAL_DIM_LABELS[d] for d in VISUAL_DIMS] + ["Vis Avg"]
    if "1a" in stages:
        header += ["S1-Aud"]
    if "2" in stages:
        header += ["S2"]
    if "3" in stages:
        header += ["S3"]

    lines.append("| " + " | ".join(header) + " |")
    lines.append("|" + "|".join(["----"] * len(header)) + "|")

    for r in sorted(video_results, key=lambda x: x["id"]):
        cols = [r["id"]]
        if "1v" in stages:
            sv = r.get("stage1_visual", {})
            for d in VISUAL_DIMS:
                s = sv.get("dimensions", {}).get(d, {}).get("score")
                cols.append(str(s) if s is not None else "N/A")
            oa = sv.get("overall_average")
            cols.append(f"{oa:.1f}" if oa is not None else "N/A")
        if "1a" in stages:
            aud = r.get("stage1_audio", {}).get("overall_average")
            cols.append(f"{aud:.1f}" if aud is not None else "N/A")
        if "2" in stages:
            cols.append(r.get("stage2", {}).get("ratio", "N/A"))
        if "3" in stages:
            cols.append(r.get("stage3", {}).get("ratio", "N/A"))
        lines.append("| " + " | ".join(cols) + " |")

    lines.append("")

    if meta.get("explain"):
        lines.append("## Details\n")
        for r in sorted(video_results, key=lambda x: x["id"]):
            vid = r["id"]
            lines.append(f"### {vid}\n")
            if "1v" in stages:
                sv = r.get("stage1_visual", {})
                lines.append(f"- **S1-Visual** (avg {sv.get('overall_average', 'N/A')}):")
                for d in VISUAL_DIMS:
                    dd = sv.get("dimensions", {}).get(d, {})
                    lines.append(f"  - {VISUAL_DIM_LABELS[d]} ({dd.get('score', 'N/A')}): {dd.get('reason', '')}")
            if "1a" in stages:
                sa = r.get("stage1_audio", {})
                lines.append(f"- **S1-Audio** (avg {sa.get('overall_average', 'N/A')}):")
                for d in AUDIO_DIMS:
                    dd = sa.get("dimensions", {}).get(d, {})
                    lines.append(f"  - {AUDIO_DIM_LABELS[d]} ({dd.get('score', 'N/A')}): {dd.get('reason', '')}")
            if "2" in stages:
                lines.append(f"- **S2-Binding**: {r.get('stage2', {}).get('summary', 'N/A')}")
            if "3" in stages:
                lines.append(f"- **S3-Temporal**: {r.get('stage3', {}).get('summary', 'N/A')}")
            lines.append("")

    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Incremental: load already-evaluated IDs
# ---------------------------------------------------------------------------

def load_existing_details(run_dir: Path) -> Dict[str, Dict]:
    existing: Dict[str, Dict] = {}

    merged = run_dir / "details.json"
    if merged.exists():
        try:
            data = load_json(merged)
            if isinstance(data, list):
                for item in data:
                    if isinstance(item, dict) and "id" in item:
                        existing[item["id"]] = item
            return existing
        except Exception:
            pass

    details_dir = run_dir / "details"
    if details_dir.exists():
        for p in details_dir.glob("*.json"):
            try:
                data = load_json(p)
                if isinstance(data, dict) and "id" in data:
                    existing[data["id"]] = data
            except Exception:
                pass

    return existing


def detail_has_stages(detail: Dict, stages: List[str]) -> bool:
    stage_keys = {
        "1v": "stage1_visual",
        "1a": "stage1_audio",
        "2": "stage2",
        "3": "stage3",
    }
    return all(stage_keys[s] in detail for s in stages)


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(
        description="Evaluate candidate captions against TCA-Bench GT",
    )
    parser.add_argument("--input", "-i", required=True,
                        help="Folder name under captions/ (reads captions.json), or a direct path")
    parser.add_argument("--name", "-n", default=None,
                        help="Result folder name under results/ (default: same as input)")
    parser.add_argument("--model", default=None,
                        help=f"Judge model name (default: {MODEL})")
    parser.add_argument("--base-url", default=None,
                        help=f"OpenAI-compatible API base URL (default: {BASE_URL})")
    parser.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY,
                        help=f"Max concurrent evaluations (default: {DEFAULT_CONCURRENCY})")
    parser.add_argument("--stage", nargs="+", choices=ALL_STAGES, default=ALL_STAGES,
                        help="Which eval stages to run (default: all). E.g. --stage 1v 1a")
    parser.add_argument("--explain", action="store_true",
                        help="Include per-dimension explanations (default: scores only)")
    parser.add_argument("--save-raw", action="store_true",
                        help="Save raw LLM responses in detail results (default: omitted)")
    parser.add_argument("--force", action="store_true",
                        help="Re-evaluate even if detail results already exist")
    parser.add_argument("--dry-run", action="store_true",
                        help="Show plan without calling API")
    parser.add_argument("--limit", type=int, default=None,
                        help="Randomly sample N captions for a quick test run (output folder suffixed with --test)")
    parser.add_argument("--seed", type=int, default=42,
                        help="Random seed for --limit sampling (default: 42)")
    args = parser.parse_args()

    model = args.model or MODEL
    base_url = args.base_url or BASE_URL

    # Validate configuration
    if not args.dry_run and not API_KEY:
        console.print("[bold red]✗[/bold red] API_KEY is empty. "
                      "Set TCA_EVAL_API_KEY, OPENROUTER_API_KEY, or OPENAI_API_KEY.")
        sys.exit(1)

    # Resolve input
    input_arg = Path(args.input)
    if input_arg.is_file():
        input_path = input_arg.resolve()
        input_folder_name = input_path.parent.name
    elif (CAPTIONS_DIR / args.input / "captions.json").exists():
        input_path = CAPTIONS_DIR / args.input / "captions.json"
        input_folder_name = args.input
    else:
        console.print(f"[bold red]✗[/bold red] Cannot find input: tried "
                       f"{CAPTIONS_DIR / args.input / 'captions.json'} and {input_arg}")
        sys.exit(1)

    candidates_raw: List[Dict] = load_captions(input_path)
    candidates: Dict[str, str] = {item["id"]: item["caption"] for item in candidates_raw}

    # --limit: randomly sample a subset for quick testing
    if args.limit is not None and args.limit < len(candidates):
        random.seed(args.seed)
        sampled_ids = sorted(random.sample(sorted(candidates.keys()), args.limit))
        candidates = {vid: candidates[vid] for vid in sampled_ids}

    result_name = args.name or input_folder_name
    if args.limit is not None:
        result_name += "--test"
    stages = sorted(set(args.stage), key=ALL_STAGES.index)
    stages_label = " + ".join(stages)

    tz = timezone(timedelta(hours=8))
    ts = datetime.now(tz).strftime("%Y-%m-%d-%H-%M-%S")
    run_dir = RESULTS_DIR / result_name / ts
    details_dir = run_dir / "details"

    console.print(Panel(
        f"[bold cyan]evaluate[/bold cyan]  [dim]·[/dim]  "
        f"[white]{len(candidates)}[/white] captions  [dim]·[/dim]  "
        f"[green]{stages_label}[/green]\n"
        f"[dim]model=[/dim][yellow]{model}[/yellow]  "
        f"[dim]concurrency=[/dim][yellow]{args.concurrency}[/yellow]\n"
        f"[dim]explain=[/dim][yellow]{args.explain}[/yellow]  "
        f"[dim]save_raw=[/dim][yellow]{args.save_raw}[/yellow]  "
        f"[dim]force=[/dim][yellow]{args.force}[/yellow]  "
        f"[dim]limit=[/dim][yellow]{args.limit or 'all'}[/yellow]\n"
        f"[dim]output=[/dim][yellow]{result_name}/{ts}[/yellow]",
        expand=False,
        border_style="cyan",
    ))

    # Load GT
    gt_captions = load_gt_map(GT_DIR / "captions.json")
    gt_stage2 = load_gt_map_full(GT_DIR / "stage-2.json") if "2" in stages else {}
    gt_stage3 = load_gt_map_full(GT_DIR / "stage-3.json") if "3" in stages else {}
    gt_stage2_raw = load_gt_raw(GT_DIR / "stage-2.json") if "2" in stages else {}
    gt_stage3_raw = load_gt_raw(GT_DIR / "stage-3.json") if "3" in stages else {}

    eval_ids: List[str] = []
    missing_gt: List[str] = []
    for vid in sorted(candidates.keys()):
        has = True
        if vid not in gt_captions:
            has = False
        if "2" in stages and vid not in gt_stage2:
            has = False
        if "3" in stages and vid not in gt_stage3:
            has = False
        if has:
            eval_ids.append(vid)
        else:
            missing_gt.append(vid)

    if missing_gt:
        console.print(f"[yellow]⚠ {len(missing_gt)} caption(s) have no matching GT, skipping[/yellow]")

    existing_details = load_existing_details(run_dir) if not args.force else {}
    tasks_to_run: List[str] = []
    for vid in eval_ids:
        if vid in existing_details and detail_has_stages(existing_details[vid], stages):
            continue
        tasks_to_run.append(vid)

    skip_count = len(eval_ids) - len(tasks_to_run)
    console.print(
        f"[bold white]{len(tasks_to_run)}[/bold white] to evaluate  "
        f"[dim]·[/dim]  [dim]{skip_count} already done[/dim]  "
        f"[dim]·[/dim]  [dim]{len(missing_gt)} no GT[/dim]"
    )

    if not tasks_to_run and not existing_details:
        console.print("\n[bold green]✓ Nothing to do.[/bold green]")
        return

    if args.dry_run:
        table = Table(title="[bold]Dry-run plan[/bold]", show_header=True,
                      header_style="bold magenta", border_style="dim")
        table.add_column("#", style="dim", width=5)
        table.add_column("ID", style="cyan", no_wrap=False)
        table.add_column("Stages", style="yellow", width=14)
        for i, vid in enumerate(tasks_to_run[:20], 1):
            table.add_row(str(i), vid, stages_label)
        if len(tasks_to_run) > 20:
            table.add_row("…", f"… and {len(tasks_to_run) - 20} more", "")
        console.print(table)
        console.print(f"\n[bold green]✓ Dry run complete.[/bold green]")
        return

    if not tasks_to_run:
        video_results = [existing_details[vid] for vid in eval_ids if vid in existing_details]
    else:
        console.print(f"\n[dim]Connecting to {base_url} …[/dim]")
        client = _build_client(base_url, API_KEY)
        console.print(f"[dim]Model:[/dim] [yellow]{model}[/yellow]\n")

        details_dir.mkdir(parents=True, exist_ok=True)

        task_pairs = [
            (vid, (lambda v=vid: evaluate_one_video(
                v, candidates[v], client, model,
                stages=stages, explain=args.explain,
                gt_captions=gt_captions, gt_stage2=gt_stage2, gt_stage3=gt_stage3,
                details_dir=details_dir, save_raw=args.save_raw,
            )))
            for vid in tasks_to_run
        ]

        new_results = run_concurrent_rich(task_pairs, max_workers=args.concurrency, label="Evaluating")

        all_details = {**existing_details}
        for vid, res in new_results.items():
            if isinstance(res, dict) and "_error" not in res:
                all_details[vid] = res

        video_results = [all_details[vid] for vid in eval_ids if vid in all_details]

    # Compute & save
    summary = compute_summary(video_results, stages,
                              gt_stage2_raw=gt_stage2_raw, gt_stage3_raw=gt_stage3_raw)

    meta = {
        "run_name": result_name,
        "timestamp": ts,
        "judge_model": model,
        "input_file": str(input_path),
        "stages": stages,
        "explain": args.explain,
        "save_raw": args.save_raw,
        "concurrency": args.concurrency,
        "num_evaluated": len(video_results),
    }

    run_dir.mkdir(parents=True, exist_ok=True)
    summary_data: Dict[str, Any] = {"meta": meta, "summary": summary}
    save_json(run_dir / "summary.json", summary_data)

    details_list = sorted(video_results, key=lambda r: r["id"])
    save_json(run_dir / "details.json", details_list)
    if details_dir.exists():
        shutil.rmtree(details_dir)

    report = generate_report_md(summary, video_results, meta, stages)
    save_text(run_dir / "report.md", report)

    # Terminal summary
    tbl = Table(title="\n[bold]Evaluation Summary[/bold]", show_header=True,
                border_style="dim", padding=(0, 2), header_style="bold")
    tbl.add_column("Metric", style="dim")
    tbl.add_column(f"All ({summary['num_videos']})", style="bold white")

    def fmt(val, mx=None):
        if val is None:
            return "[dim]N/A[/dim]"
        if mx:
            return f"[green]{val:.2f}[/green] / {mx}"
        return f"[green]{val:.3f}[/green]"

    def add_row(label, get_val, mx=None):
        vals = [fmt(get_val(summary), mx)]
        tbl.add_row(label, *vals)

    if "1v" in stages:
        add_row("S1 Visual Overall",
                lambda s: s.get("stage1_visual", {}).get("overall_mean"), 10)
        for d in VISUAL_DIMS:
            add_row(f"  ↳ {VISUAL_DIM_LABELS[d]}",
                    lambda s, _d=d: s.get("stage1_visual", {}).get("dimensions", {}).get(_d, {}).get("mean"), 10)

    if "1a" in stages:
        add_row("S1 Audio Overall",
                lambda s: s.get("stage1_audio", {}).get("overall_mean"), 10)
        for d in AUDIO_DIMS:
            add_row(f"  ↳ {AUDIO_DIM_LABELS[d]}",
                    lambda s, _d=d: s.get("stage1_audio", {}).get("dimensions", {}).get(_d, {}).get("mean"), 10)

    if "2" in stages:
        add_row("S2 AV-Binding Acc",
                lambda s: s.get("stage2_binding", {}).get("accuracy"))
        add_row("  ↳ Character Acc",
                lambda s: s.get("stage2_binding", {}).get("character", {}).get("accuracy"))
        add_row("  ↳ Non-Char Acc",
                lambda s: s.get("stage2_binding", {}).get("non_character", {}).get("accuracy"))

    if "3" in stages:
        add_row("S3 Temporal F1",
                lambda s: s.get("stage3_temporal", {}).get("f1"))
        add_row("  ↳ Sequential F1",
                lambda s: s.get("stage3_temporal", {}).get("sequential", {}).get("f1"))
        add_row("  ↳ Simultaneous F1",
                lambda s: s.get("stage3_temporal", {}).get("simultaneous", {}).get("f1"))

    tbl.add_row("Videos evaluated", f"[cyan]{len(video_results)}[/cyan]")
    tbl.add_row("Output", f"[dim]{run_dir.relative_to(MAIN_DIR)}[/dim]")
    console.print(tbl)

    error_count = sum(
        1 for r in video_results
        if any(r.get(k, {}).get("ratio") == "N/A" for k in ["stage2", "stage3"]
               if k.replace("stage", "") in stages)
    )
    if error_count:
        console.print(f"\n[yellow]⚠ {error_count} video(s) had parse failures in some stages[/yellow]")

    console.print("\n[bold green]✓ Done![/bold green]")


if __name__ == "__main__":
    main()