File size: 42,322 Bytes
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
8c10cf2
 
 
 
 
c4e7970
 
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
f080257
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
8c10cf2
 
 
c4e7970
 
 
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
8c10cf2
 
 
c4e7970
 
 
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
8c10cf2
c4e7970
8c10cf2
 
 
 
 
 
c4e7970
 
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
c4e7970
 
8c10cf2
 
 
 
c4e7970
8c10cf2
 
 
 
 
c4e7970
 
 
 
 
 
 
 
8c10cf2
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
c4e7970
 
8c10cf2
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
c4e7970
8c10cf2
c4e7970
8c10cf2
 
 
 
c4e7970
8c10cf2
 
c4e7970
 
8c10cf2
 
c4e7970
 
8c10cf2
 
 
c4e7970
8c10cf2
 
c4e7970
 
8c10cf2
 
 
c4e7970
 
8c10cf2
 
c4e7970
8c10cf2
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

import csv
from collections import defaultdict
from pathlib import Path
from typing import Dict, List

import matplotlib.pyplot as plt
import numpy as np

# Use Times New Roman for all text to match other figures
plt.rcParams["font.family"] = "Times New Roman"

# Fixed model order (must match the names used in the CSV files)
MODEL_ORDER: List[str] = [
    "GPT-5",
    "GPT-4o-mini",
    "DeepSeek-V3-1",
    "DeepSeek-R1",
    "Gemini-2.5-flash",
    "Gemini-2.5-flash-nothinking",
    "Qwen3-235b",
]

# Display labels (can be slightly pretty-printed)
MODEL_LABELS: Dict[str, str] = {
    "GPT-5": "GPT-5",
    "GPT-4o-mini": "GPT-4o-mini",
    "DeepSeek-V3-1": "DeepSeek-V3.1",
    "DeepSeek-R1": "DeepSeek-R1",
    "Gemini-2.5-flash": "Gemini-2.5",
    "Gemini-2.5-flash-nothinking": "Gemini-2.5-NT",
    "Qwen3-235b": "Qwen3-235b",
}

# Color palette for different models - professional academic colors (Tableau 10 style)
MODEL_COLORS: Dict[str, str] = {
    "GPT-5": "#1f77b4",  # Blue
    "GPT-4o-mini": "#ff7f0e",  # Orange
    "DeepSeek-V3-1": "#2ca02c",  # Green
    "DeepSeek-R1": "#d62728",  # Red
    "Gemini-2.5-flash": "#9467bd",  # Purple
    "Gemini-2.5-flash-nothinking": "#8c564b",  # Brown
    "Qwen3-235b": "#e377c2",  # Pink
}


def load_total_classified(csv_path: Path) -> Dict[str, List[float]]:
    """Load total_classified values per model from a CSV file.

    Returns:
        data[model] = sorted list of total_classified values (floats).
    """

    by_model: Dict[str, List[float]] = defaultdict(list)

    with csv_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        for row in reader:
            model = (row.get("model") or "").strip()
            if not model:
                continue
            if model not in MODEL_ORDER:
                # Ignore unknown models so that colors/order stay consistent
                continue
            val_raw = row.get("total_classified")
            if val_raw is None or val_raw == "":
                continue
            try:
                # total_classified is in milliseconds in existing CSVs
                val = float(val_raw)
            except ValueError:
                continue
            by_model[model].append(val)

    # Sort values for ECDF computation
    for m in list(by_model.keys()):
        by_model[m].sort()

    return by_model


def compute_ecdf(values: List[float]):
    """Return x, y for the empirical CDF of a 1D sample.

    x: sorted values
    y: ECDF in [0, 1]
    """

    if not values:
        return np.array([]), np.array([])

    x = np.asarray(values, dtype=float)
    n = x.size
    # Standard ECDF: y_i = i / n for sorted x_i
    y = np.arange(1, n + 1, dtype=float) / float(n)
    return x, y


def compute_weighted_ecdf(values: List[float], weights: List[float]):
    if not values or not weights or len(values) != len(weights):
        return np.array([]), np.array([])

    x = np.asarray(values, dtype=float)
    w = np.asarray(weights, dtype=float)

    if np.all(w <= 0.0):
        return np.array([]), np.array([])

    order = np.argsort(x)
    x_sorted = x[order]
    w_sorted = w[order]

    cum_w = np.cumsum(w_sorted)
    total_w = cum_w[-1]
    if total_w <= 0.0:
        return np.array([]), np.array([])

    y = cum_w / float(total_w)
    return x_sorted, y


def create_legend_pdf_horizontal(output_path: Path) -> None:
    fig, ax = plt.subplots(figsize=(12, 1.0))
    ax.axis("off")

    handles = []
    labels = []
    for model in MODEL_ORDER:
        color = MODEL_COLORS.get(model, "black")
        (handle,) = ax.plot([], [], "-", linewidth=2, color=color)
        handles.append(handle)
        labels.append(MODEL_LABELS.get(model, model))

    ax.legend(
        handles,
        labels,
        loc="center",
        ncol=len(handles),
        frameon=False,
        fancybox=False,
        shadow=False,
        borderaxespad=0.1,
        borderpad=0.3,
        handletextpad=0.4,
        labelspacing=0.2,
        prop={"size": 14},
    )

    fig.tight_layout(pad=0.0)
    fig.savefig(
        output_path,
        format="pdf",
        dpi=300,
        bbox_inches="tight",
        pad_inches=0.0,
    )
    plt.close(fig)
    print(f"saved horizontal legend: {output_path}")


def plot_overall_ecdf(
    overall_values_by_model: Dict[str, List[float]],
    overall_weights_by_model: Dict[str, List[float]],
    out_dir: Path,
) -> None:
    fig, ax = plt.subplots(figsize=(6, 4))

    any_line = False
    for model in MODEL_ORDER:
        values = overall_values_by_model.get(model)
        weights = overall_weights_by_model.get(model)
        if not values or not weights or len(values) != len(weights):
            continue
        x, y = compute_weighted_ecdf(values, weights)
        if x.size == 0:
            continue
        x_plot = x / 1_000_000.0
        color = MODEL_COLORS.get(model, "black")
        label = MODEL_LABELS.get(model, model)
        ax.plot(x_plot, y, label=label, color=color, linewidth=2.0)
        any_line = True

    if not any_line:
        plt.close(fig)
        print("no ECDF lines drawn for overall, skip figure")
        return

    ax.set_xlabel(r"$\mathbf{Trace\ duration\ [10^3\ s]}$", fontsize=22)
    ax.set_ylabel("", fontsize=22)

    ax.set_ylim(0.0, 1.0)

    ax.grid(True, which="both", axis="both", linestyle="-", linewidth=0.5, alpha=0.4)

    ax.tick_params(axis="both", labelsize=22)
    plt.setp(ax.get_xticklabels(), fontweight="bold")
    plt.setp(ax.get_yticklabels(), fontweight="bold")

    ax.margins(x=0.01)
    fig.tight_layout(pad=0.0)

    out_dir.mkdir(parents=True, exist_ok=True)
    out_file = out_dir / "ecdf_overall_time_weighted.pdf"
    fig.savefig(out_file, dpi=200, bbox_inches="tight", pad_inches=0.02)
    plt.close(fig)
    print(f"saved ECDF figure: {out_file}")


def compute_time_statistics(values: List[float]) -> Dict[str, float]:
    """Compute time statistics for a list of values (in milliseconds).

    Returns:
        Dictionary with mean, median, and total in seconds.
    """
    if not values:
        return {"mean": 0.0, "median": 0.0, "total": 0.0, "count": 0}

    # Convert from milliseconds to seconds
    values_sec = [v / 1000.0 for v in values]
    return {
        "mean": np.mean(values_sec),
        "median": np.median(values_sec),
        "total": np.sum(values_sec),
        "count": len(values),
    }


def generate_mcp_vs_hardcoded_comparison(
    base_project: str, scenario_time_data: Dict[str, Dict[str, List[float]]]
) -> str:
    """Generate comparison between MCP and hardcoded versions for a project."""
    lines = []
    lines.append(f"# {base_project}: MCP vs Hardcoded\n\n")

    mcp_scenario = f"{base_project}-MCP"
    hardcoded_scenario = base_project

    if (
        mcp_scenario not in scenario_time_data
        or hardcoded_scenario not in scenario_time_data
    ):
        lines.append("_Data not available for comparison_\n\n")
        return "".join(lines)

    mcp_data = scenario_time_data[mcp_scenario]
    hardcoded_data = scenario_time_data[hardcoded_scenario]

    all_models = sorted(set(mcp_data.keys()) | set(hardcoded_data.keys()))

    # Calculate overall averages first
    overall_stats = {
        "mcp": {"total": 0.0, "count": 0},
        "hard": {"total": 0.0, "count": 0},
    }
    for model in all_models:
        mcp_stats = compute_time_statistics(mcp_data.get(model, []))
        hard_stats = compute_time_statistics(hardcoded_data.get(model, []))
        overall_stats["mcp"]["total"] += mcp_stats["total"]
        overall_stats["mcp"]["count"] += mcp_stats["count"]
        overall_stats["hard"]["total"] += hard_stats["total"]
        overall_stats["hard"]["count"] += hard_stats["count"]

    # Add overall summary section
    lines.append("## Overall Summary (Averaged Across All Models)\n\n")
    lines.append("| MCP Mean (s) | Hardcoded Mean (s) | Diff (MCP-Hard) |\n")
    lines.append("| --- | --- | --- |\n")

    if overall_stats["mcp"]["count"] > 0 and overall_stats["hard"]["count"] > 0:
        avg_mcp = overall_stats["mcp"]["total"] / overall_stats["mcp"]["count"]
        avg_hard = overall_stats["hard"]["total"] / overall_stats["hard"]["count"]
        diff = avg_mcp - avg_hard
        pct = (diff / avg_hard * 100) if avg_hard > 0 else 0
        lines.append(
            f"| {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n"
        )

    lines.append("\n---\n\n")

    # Per-model comparison
    lines.append("## Per-Model Comparison\n\n")
    lines.append("| Model | MCP Mean (s) | Hardcoded Mean (s) | Diff (MCP-Hard) |\n")
    lines.append("| --- | --- | --- | --- |\n")

    for model in all_models:
        mcp_stats = compute_time_statistics(mcp_data.get(model, []))
        hard_stats = compute_time_statistics(hardcoded_data.get(model, []))

        mean_diff = mcp_stats["mean"] - hard_stats["mean"]
        mean_pct = (
            (mean_diff / hard_stats["mean"] * 100) if hard_stats["mean"] > 0 else 0
        )

        lines.append(
            f"| {model} | {mcp_stats['mean']:.2f} | {hard_stats['mean']:.2f} | "
            f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n"
        )
    lines.append("\n")

    return "".join(lines)


def generate_mcp_vs_hardcoded_overall_comparison(
    projects: List[str], scenario_time_data: Dict[str, Dict[str, List[float]]]
) -> str:
    """Generate overall comparison across all MCP vs hardcoded projects."""
    lines = []
    lines.append("# Overall MCP vs Hardcoded Comparison\n\n")
    lines.append(f"Averaged across all projects: {', '.join(projects)}\n\n")

    # Collect data from all projects
    overall_data = {}
    framework_stats = {
        "mcp": {"total": 0.0, "count": 0},
        "hard": {"total": 0.0, "count": 0},
    }

    for project in projects:
        mcp_scenario = f"{project}-MCP"
        hardcoded_scenario = project

        if (
            mcp_scenario not in scenario_time_data
            or hardcoded_scenario not in scenario_time_data
        ):
            continue

        mcp_data = scenario_time_data[mcp_scenario]
        hardcoded_data = scenario_time_data[hardcoded_scenario]

        all_models = set(mcp_data.keys()) | set(hardcoded_data.keys())

        for model in all_models:
            if model not in overall_data:
                overall_data[model] = {"mcp": [], "hard": []}

            mcp_vals = mcp_data.get(model, [])
            hard_vals = hardcoded_data.get(model, [])

            overall_data[model]["mcp"].extend(mcp_vals)
            overall_data[model]["hard"].extend(hard_vals)

            # Add to framework-level stats
            mcp_stats = compute_time_statistics(mcp_vals)
            hard_stats = compute_time_statistics(hard_vals)
            framework_stats["mcp"]["total"] += mcp_stats["total"]
            framework_stats["mcp"]["count"] += mcp_stats["count"]
            framework_stats["hard"]["total"] += hard_stats["total"]
            framework_stats["hard"]["count"] += hard_stats["count"]

    # Add framework-level comparison
    lines.append("## Framework-Level Comparison (All Models Averaged)\n\n")
    lines.append("| MCP Mean (s) | Hardcoded Mean (s) | Diff (MCP-Hard) |\n")
    lines.append("| --- | --- | --- |\n")

    if framework_stats["mcp"]["count"] > 0 and framework_stats["hard"]["count"] > 0:
        avg_mcp = framework_stats["mcp"]["total"] / framework_stats["mcp"]["count"]
        avg_hard = framework_stats["hard"]["total"] / framework_stats["hard"]["count"]
        diff = avg_mcp - avg_hard
        pct = (diff / avg_hard * 100) if avg_hard > 0 else 0
        lines.append(
            f"| {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n"
        )

    lines.append("\n---\n\n")

    # Per-model summary
    lines.append("## Per-Model Summary\n\n")
    lines.append("| Model | MCP Mean (s) | Hard Mean (s) | Diff (MCP-Hard) |\n")
    lines.append("| --- | --- | --- | --- |\n")

    for model in sorted(overall_data.keys()):
        mcp_stats = compute_time_statistics(overall_data[model]["mcp"])
        hard_stats = compute_time_statistics(overall_data[model]["hard"])

        mean_diff = mcp_stats["mean"] - hard_stats["mean"]
        mean_pct = (
            (mean_diff / hard_stats["mean"] * 100) if hard_stats["mean"] > 0 else 0
        )

        lines.append(
            f"| {model} | {mcp_stats['mean']:.2f} | {hard_stats['mean']:.2f} | "
            f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n"
        )
    lines.append("\n---\n\n")

    return "".join(lines)


def generate_version_comparison(
    base_project: str,
    version_a_suffix: str,
    version_b_suffix: str,
    scenario_time_data: Dict[str, Dict[str, List[float]]],
    version_a_name: str,
    version_b_name: str,
) -> str:
    """Generate comparison between two versions of a project."""
    lines = []
    lines.append(f"# {base_project}: {version_a_name} vs {version_b_name}\n\n")

    scenario_a = f"{base_project}{version_a_suffix}"
    scenario_b = f"{base_project}{version_b_suffix}"

    if scenario_a not in scenario_time_data or scenario_b not in scenario_time_data:
        lines.append("_Data not available for comparison_\n\n")
        return "".join(lines)

    data_a = scenario_time_data[scenario_a]
    data_b = scenario_time_data[scenario_b]

    all_models = sorted(set(data_a.keys()) | set(data_b.keys()))

    # Calculate overall averages first
    overall_stats = {"a": {"total": 0.0, "count": 0}, "b": {"total": 0.0, "count": 0}}
    for model in all_models:
        stats_a = compute_time_statistics(data_a.get(model, []))
        stats_b = compute_time_statistics(data_b.get(model, []))
        overall_stats["a"]["total"] += stats_a["total"]
        overall_stats["a"]["count"] += stats_a["count"]
        overall_stats["b"]["total"] += stats_b["total"]
        overall_stats["b"]["count"] += stats_b["count"]

    # Add overall summary section
    lines.append("## Overall Summary (Averaged Across All Models)\n\n")
    lines.append(
        f"| {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n"
    )
    lines.append("| --- | --- | --- |\n")

    if overall_stats["a"]["count"] > 0 and overall_stats["b"]["count"] > 0:
        avg_a = overall_stats["a"]["total"] / overall_stats["a"]["count"]
        avg_b = overall_stats["b"]["total"] / overall_stats["b"]["count"]
        diff = avg_a - avg_b
        pct = (diff / avg_b * 100) if avg_b > 0 else 0
        lines.append(f"| {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n")

    lines.append("\n---\n\n")

    # Per-model comparison
    lines.append("## Per-Model Comparison\n\n")
    lines.append(
        f"| Model | {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n"
    )
    lines.append("| --- | --- | --- | --- |\n")

    for model in all_models:
        stats_a = compute_time_statistics(data_a.get(model, []))
        stats_b = compute_time_statistics(data_b.get(model, []))

        mean_diff = stats_a["mean"] - stats_b["mean"]
        mean_pct = (mean_diff / stats_b["mean"] * 100) if stats_b["mean"] > 0 else 0

        lines.append(
            f"| {model} | {stats_a['mean']:.2f} | {stats_b['mean']:.2f} | "
            f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n"
        )
    lines.append("\n")

    return "".join(lines)


def generate_version_overall_comparison(
    projects: List[str],
    version_a_suffix: str,
    version_b_suffix: str,
    scenario_time_data: Dict[str, Dict[str, List[float]]],
    version_a_name: str,
    version_b_name: str,
    comparison_title: str,
) -> str:
    """Generate overall comparison across all projects for two versions."""
    lines = []
    lines.append(f"# Overall {comparison_title}\n\n")
    lines.append(f"Averaged across all projects: {', '.join(projects)}\n\n")

    # Collect data from all projects
    overall_data = {}
    framework_stats = {"a": {"total": 0.0, "count": 0}, "b": {"total": 0.0, "count": 0}}

    for project in projects:
        scenario_a = f"{project}{version_a_suffix}"
        scenario_b = f"{project}{version_b_suffix}"

        if scenario_a not in scenario_time_data or scenario_b not in scenario_time_data:
            continue

        data_a = scenario_time_data[scenario_a]
        data_b = scenario_time_data[scenario_b]

        all_models = set(data_a.keys()) | set(data_b.keys())

        for model in all_models:
            if model not in overall_data:
                overall_data[model] = {"a": [], "b": []}

            vals_a = data_a.get(model, [])
            vals_b = data_b.get(model, [])

            overall_data[model]["a"].extend(vals_a)
            overall_data[model]["b"].extend(vals_b)

            # Add to framework-level stats
            stats_a = compute_time_statistics(vals_a)
            stats_b = compute_time_statistics(vals_b)
            framework_stats["a"]["total"] += stats_a["total"]
            framework_stats["a"]["count"] += stats_a["count"]
            framework_stats["b"]["total"] += stats_b["total"]
            framework_stats["b"]["count"] += stats_b["count"]

    # Add framework-level comparison
    lines.append("## Framework-Level Comparison (All Models Averaged)\n\n")
    lines.append(
        f"| {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n"
    )
    lines.append("| --- | --- | --- |\n")

    if framework_stats["a"]["count"] > 0 and framework_stats["b"]["count"] > 0:
        avg_a = framework_stats["a"]["total"] / framework_stats["a"]["count"]
        avg_b = framework_stats["b"]["total"] / framework_stats["b"]["count"]
        diff = avg_a - avg_b
        pct = (diff / avg_b * 100) if avg_b > 0 else 0
        lines.append(f"| {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n")

    lines.append("\n---\n\n")

    # Per-model summary
    lines.append("## Per-Model Summary\n\n")
    lines.append(
        f"| Model | {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n"
    )
    lines.append("| --- | --- | --- | --- |\n")

    for model in sorted(overall_data.keys()):
        stats_a = compute_time_statistics(overall_data[model]["a"])
        stats_b = compute_time_statistics(overall_data[model]["b"])

        mean_diff = stats_a["mean"] - stats_b["mean"]
        mean_pct = (mean_diff / stats_b["mean"] * 100) if stats_b["mean"] > 0 else 0

        lines.append(
            f"| {model} | {stats_a['mean']:.2f} | {stats_b['mean']:.2f} | "
            f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n"
        )
    lines.append("\n---\n\n")

    return "".join(lines)


def get_base_project_name(scenario: str) -> str:
    if scenario.endswith("-A2A_mix"):
        return scenario[: -len("-A2A_mix")]
    if scenario.endswith("-H_A2A"):
        return scenario[: -len("-H_A2A")]
    if scenario.endswith("-A2A"):
        return scenario[: -len("-A2A")]
    if scenario.endswith("-MCP"):
        return scenario[: -len("-MCP")]
    return scenario


def generate_overall_model_comparison(
    scenario_time_data: Dict[str, Dict[str, List[float]]],
) -> str:
    """Generate an all-projects summary comparing models across every scenario."""

    lines: List[str] = []
    lines.append("## All Projects Combined (Summary Across All Projects, by Model)\n\n")

    # Aggregate all total_classified samples per model across every project scenario
    aggregated: Dict[str, List[float]] = defaultdict(list)
    for project_data in scenario_time_data.values():
        for model, vals in project_data.items():
            aggregated[model].extend(vals)

    if not aggregated:
        lines.append("_No data available across projects_\n\n")
        return "".join(lines)

    # Respect fixed display order, then any remaining models alphabetically
    ordered_models: List[str] = [
        m for m in MODEL_ORDER if m in aggregated and aggregated[m]
    ]
    remaining_models = sorted(
        m for m in aggregated.keys() if m not in ordered_models and aggregated[m]
    )
    all_models = ordered_models + remaining_models

    # Compute statistics for each model
    model_stats: Dict[str, Dict[str, float]] = {}
    for model in all_models:
        model_stats[model] = compute_time_statistics(aggregated[model])

    # Summary table
    lines.append("### Model Statistics Summary\n\n")
    lines.append("| Model | Mean (s) | Median (s) | Count | Total (s) |\n")
    lines.append("| --- | --- | --- | --- | --- |\n")

    for model in all_models:
        stats = model_stats[model]
        lines.append(
            f"| {model} | {stats['mean']:.2f} | {stats['median']:.2f} | "
            f"{stats['count']} | {stats['total']:.2f} |\n"
        )

    # Relative performance vs fastest (only if at least two models with data)
    positive_models = [m for m in all_models if model_stats[m]["mean"] > 0]
    if len(positive_models) > 1:
        fastest_model = min(positive_models, key=lambda m: model_stats[m]["mean"])
        fastest_mean = model_stats[fastest_model]["mean"]

        lines.append("\n### Relative Performance (vs. Fastest Model)\n\n")
        lines.append(
            f"Baseline (fastest): **{fastest_model}** ({fastest_mean:.2f}s mean)\n\n"
        )
        lines.append("| Model | Mean (s) | Slowdown vs Baseline |\n")
        lines.append("| --- | --- | --- |\n")

        for model in all_models:
            stats = model_stats[model]
            if stats["mean"] > 0 and fastest_mean > 0:
                slowdown = (stats["mean"] - fastest_mean) / fastest_mean * 100
                lines.append(f"| {model} | {stats['mean']:.2f} | {slowdown:+.1f}% |\n")
            else:
                lines.append(f"| {model} | {stats['mean']:.2f} | N/A |\n")

        # Add slowest model summary
        slowest_model = max(
            positive_models,
            key=lambda m: model_stats[m]["mean"] if model_stats[m]["mean"] > 0 else 0,
        )
        slowest_mean = model_stats[slowest_model]["mean"]
        if fastest_mean > 0 and slowest_mean > 0:
            slowest_slowdown = (slowest_mean - fastest_mean) / fastest_mean * 100
            lines.append(
                f"\n**Slowest model:** {slowest_model} ({slowest_mean:.2f}s mean, "
                f"{slowest_slowdown:+.1f}% slower than baseline)\n"
            )

    lines.append("\n")
    return "".join(lines)


def generate_project_model_comparison(
    project_name: str, scenario_time_data: Dict[str, Dict[str, List[float]]]
) -> str:
    """Generate model-to-model comparison for a single project.

    Compares all models within the same project scenario.
    """
    lines = []
    lines.append(f"# {project_name}: Model Comparison\n\n")

    if project_name not in scenario_time_data:
        lines.append("_Data not available for this project_\n\n")
        return "".join(lines)

    project_data = scenario_time_data[project_name]
    all_models = sorted(project_data.keys())

    if not all_models:
        lines.append("_No model data available_\n\n")
        return "".join(lines)

    # Compute statistics for each model
    model_stats = {}
    for model in all_models:
        vals = project_data.get(model, [])
        model_stats[model] = compute_time_statistics(vals)

    # Summary table
    lines.append("## Model Statistics Summary\n\n")
    lines.append("| Model | Mean (s) | Median (s) | Count | Total (s) |\n")
    lines.append("| --- | --- | --- | --- | --- |\n")

    for model in all_models:
        stats = model_stats[model]
        lines.append(
            f"| {model} | {stats['mean']:.2f} | {stats['median']:.2f} | "
            f"{stats['count']} | {stats['total']:.2f} |\n"
        )

    # Pairwise comparison: compare each model against the fastest one
    if len(all_models) > 1:
        lines.append("\n## Relative Performance (vs. Fastest Model)\n\n")

        # Find fastest model by mean
        fastest_model = min(
            all_models,
            key=lambda m: (
                model_stats[m]["mean"] if model_stats[m]["mean"] > 0 else float("inf")
            ),
        )
        fastest_mean = model_stats[fastest_model]["mean"]

        # Find slowest model by mean
        slowest_model = max(
            all_models,
            key=lambda m: model_stats[m]["mean"] if model_stats[m]["mean"] > 0 else 0,
        )
        slowest_mean = model_stats[slowest_model]["mean"]

        lines.append(
            f"Baseline (fastest): **{fastest_model}** ({fastest_mean:.2f}s mean)\n\n"
        )
        lines.append("| Model | Mean (s) | Slowdown vs Baseline |\n")
        lines.append("| --- | --- | --- |\n")

        for model in all_models:
            stats = model_stats[model]
            if stats["mean"] > 0 and fastest_mean > 0:
                slowdown = (stats["mean"] - fastest_mean) / fastest_mean * 100
                lines.append(f"| {model} | {stats['mean']:.2f} | {slowdown:+.1f}% |\n")
            else:
                lines.append(f"| {model} | {stats['mean']:.2f} | N/A |\n")

        # Add slowest model summary
        if fastest_mean > 0 and slowest_mean > 0:
            slowest_slowdown = (slowest_mean - fastest_mean) / fastest_mean * 100
            lines.append(
                f"\n**Slowest model:** {slowest_model} ({slowest_mean:.2f}s mean, "
                f"{slowest_slowdown:+.1f}% slower than baseline)\n"
            )

    lines.append("\n")
    return "".join(lines)


def plot_ecdf_for_project(
    project_dir: Path, csv_path: Path, out_dir: Path, x_max_ms: float
) -> None:
    """Plot ECDF of total_classified for all models in one project.

    One figure per project, up to 7 lines (one per model present in the CSV).
    """

    data_by_model = load_total_classified(csv_path)
    if not data_by_model:
        print(f"no total_classified data in {csv_path}, skip")
        return

    # If no global series maximum was provided, fall back to this project's
    # own maximum so that the function remains usable in isolation.
    if x_max_ms <= 0.0:
        local_max = 0.0
        for vals in data_by_model.values():
            if vals:
                v_max = max(vals)
                if v_max > local_max:
                    local_max = v_max
        x_max_ms = local_max

    fig, ax = plt.subplots(figsize=(6, 4))

    # For a consistent legend order, iterate in fixed MODEL_ORDER
    any_line = False
    for model in MODEL_ORDER:
        values = data_by_model.get(model)
        if not values:
            continue
        x, y = compute_ecdf(values)
        if x.size == 0:
            continue
        # Plot in units of 10^3 s so that the 1e3 scaling factor is
        # explicitly captured in the axis label rather than as a separate
        # offset text.
        x_plot = x / 1_000_000.0
        color = MODEL_COLORS.get(model, "black")
        label = MODEL_LABELS.get(model, model)
        ax.plot(x_plot, y, label=label, color=color, linewidth=2.0)
        any_line = True

    if not any_line:
        plt.close(fig)
        print(f"no ECDF lines drawn for {csv_path}, skip figure")
        return

    # Use a shared x-axis upper bound (in milliseconds) for all scenarios in
    # the same project series so that their ECDFs are directly comparable.
    x_max_plot = x_max_ms / 1_000_000.0
    if x_max_plot > 0.0:
        ax.set_xlim(0.0, x_max_plot)

    # Show axis units directly in terms of 10^3 s using LaTeX bold.
    ax.set_xlabel(r"$\mathbf{Trace\ duration\ [10^3\ s]}$", fontsize=22)
    # No explicit y-axis label (ECDF) to keep the figure clean.
    ax.set_ylabel("", fontsize=22)

    ax.set_ylim(0.0, 1.0)

    # Add light grid similar to typical ECDF examples
    ax.grid(True, which="both", axis="both", linestyle="-", linewidth=0.5, alpha=0.4)

    ax.tick_params(axis="both", labelsize=22)
    plt.setp(ax.get_xticklabels(), fontweight="bold")
    plt.setp(ax.get_yticklabels(), fontweight="bold")

    # Slightly reduce margins so curves fill the axes area; no in-figure legend or title
    ax.margins(x=0.01)
    fig.tight_layout(pad=0.0)

    out_dir.mkdir(parents=True, exist_ok=True)
    out_file = out_dir / f"ecdf_{project_dir.name}.pdf"
    # Use a tiny padding so the right axis spine is fully preserved while
    # keeping extra whitespace visually negligible.
    fig.savefig(out_file, dpi=200, bbox_inches="tight", pad_inches=0.02)
    plt.close(fig)
    print(f"saved ECDF figure: {out_file}")


def main() -> None:
    # Assume this script is placed in Part2 directory
    part2_dir = Path(__file__).resolve().parent

    # Output directory for ECDF figures
    out_dir = part2_dir / "ECDFs"

    overall_values_by_model: Dict[str, List[float]] = defaultdict(list)
    overall_weights_by_model: Dict[str, List[float]] = defaultdict(list)

    # Dictionary to store time data per scenario for comparisons
    scenario_time_data: Dict[str, Dict[str, List[float]]] = {}

    # Per-series maximum of total_classified (in milliseconds) so that
    # scenarios sharing the same base project name use a common x-axis range.
    series_x_max_ms: Dict[str, float] = {}

    # First pass: load data, build overall ECDF inputs, and compute per-series maxima.
    for sub in sorted(p for p in part2_dir.iterdir() if p.is_dir()):
        if sub.name.startswith("z_"):
            # Skip output directories
            continue
        csv_path = sub / "performance_breakdown_summary.csv"
        if not csv_path.exists():
            continue
        data_by_model = load_total_classified(csv_path)

        # Store scenario data for comparisons
        scenario_time_data[sub.name] = data_by_model

        # Update weights used for the overall ECDF
        for model, vals in data_by_model.items():
            if not vals:
                continue
            total_time = float(sum(vals))
            count = len(vals)
            if total_time <= 0.0 or count <= 0:
                continue
            weight_per_sample = total_time / float(count)
            for v in vals:
                overall_values_by_model[model].append(v)
                overall_weights_by_model[model].append(weight_per_sample)

        # Track the maximum total_classified for this scenario and propagate it
        # to the corresponding project series.
        scenario_max = 0.0
        for vals in data_by_model.values():
            if vals:
                v_max = max(vals)
                if v_max > scenario_max:
                    scenario_max = v_max
        if scenario_max > 0.0:
            base_name = get_base_project_name(sub.name)
            prev_max = series_x_max_ms.get(base_name, 0.0)
            if scenario_max > prev_max:
                series_x_max_ms[base_name] = scenario_max

    # Second pass: draw ECDF for each scenario using the shared x-axis maximum
    # per project series.
    for sub in sorted(p for p in part2_dir.iterdir() if p.is_dir()):
        if sub.name.startswith("z_"):
            continue
        csv_path = sub / "performance_breakdown_summary.csv"
        if not csv_path.exists():
            continue
        base_name = get_base_project_name(sub.name)
        x_max_ms = series_x_max_ms.get(base_name, 0.0)
        print(f"processing {csv_path}")
        try:
            plot_ecdf_for_project(sub, csv_path, out_dir, x_max_ms)
        except Exception as exc:  # pragma: no cover - defensive
            print(f"  error while plotting {csv_path}: {exc}")

    if overall_values_by_model:
        plot_overall_ecdf(overall_values_by_model, overall_weights_by_model, out_dir)

    # Also create a standalone horizontal legend PDF (one per script run)
    legend_path = out_dir / "ECDF_Model_Legend_horizontal.pdf"
    create_legend_pdf_horizontal(legend_path)

    # Generate time comparison markdown files
    print("\n" + "=" * 60)
    print("Generating time comparison summaries...")
    print("=" * 60)

    # 1. MCP vs Hardcoded comparisons
    mcp_hardcoded_projects = [
        "MarkdownValidator",
        "GameBuilder",
        "EmailResponder",
    ]

    comparison_lines = []
    # Add overall summary first
    comparison_lines.append(
        generate_mcp_vs_hardcoded_overall_comparison(
            mcp_hardcoded_projects, scenario_time_data
        )
    )

    # Then add per-project comparisons
    for project in mcp_hardcoded_projects:
        comparison_lines.append(
            generate_mcp_vs_hardcoded_comparison(project, scenario_time_data)
        )

    comparison_md_path = out_dir / "Time_Comparison_MCP_vs_Hardcoded.md"
    comparison_md_path.write_text("".join(comparison_lines), encoding="utf-8")
    print(f"Created: {comparison_md_path}")

    # 2. MCP vs A2A comparisons
    version_projects = [
        "SQL_assistant",
        "intelligent_recruitment_platform",
        "landing_page_generator",
        "self_evaluation_loop_flow",
        "write_a_book_with_flows",
    ]

    comparison_lines = []
    # Add overall summary first
    comparison_lines.append(
        generate_version_overall_comparison(
            version_projects,
            "-MCP",
            "-A2A",
            scenario_time_data,
            "MCP",
            "A2A",
            "MCP vs A2A Time Comparison",
        )
    )

    # Then add per-project comparisons
    for project in version_projects:
        comparison_lines.append(
            generate_version_comparison(
                project, "-MCP", "-A2A", scenario_time_data, "MCP", "A2A"
            )
        )

    comparison_md_path = out_dir / "Time_Comparison_MCP_vs_A2A.md"
    comparison_md_path.write_text("".join(comparison_lines), encoding="utf-8")
    print(f"Created: {comparison_md_path}")

    # 3. A2A vs A2A_mix comparisons
    comparison_lines = []
    # Add overall summary first
    comparison_lines.append(
        generate_version_overall_comparison(
            version_projects,
            "-A2A",
            "-A2A_mix",
            scenario_time_data,
            "A2A",
            "A2A_mix",
            "A2A vs A2A_mix Time Comparison",
        )
    )

    # Then add per-project comparisons
    for project in version_projects:
        comparison_lines.append(
            generate_version_comparison(
                project, "-A2A", "-A2A_mix", scenario_time_data, "A2A", "A2A_mix"
            )
        )

    comparison_md_path = out_dir / "Time_Comparison_A2A_vs_A2A_mix.md"
    comparison_md_path.write_text("".join(comparison_lines), encoding="utf-8")
    print(f"Created: {comparison_md_path}")

    # 4. Generate detailed A2A vs A2A_mix comparison for each project
    print("\nGenerating detailed A2A vs A2A_mix per-project comparisons...")
    a2a_mix_comparison_lines = []
    a2a_mix_comparison_lines.append(
        "# A2A vs A2A_mix: Detailed Per-Project Comparison\n\n"
    )
    a2a_mix_comparison_lines.append(
        "This document compares A2A and A2A_mix architectures for each project, "
    )
    a2a_mix_comparison_lines.append(
        "showing both per-model and overall statistics.\n\n"
    )
    a2a_mix_comparison_lines.append("---\n\n")

    # Aggregators for cross-project summary
    global_all_models = sorted(
        set().union(*[set(d.keys()) for d in scenario_time_data.values()])
    )
    overall_deltas: List[Dict[str, float]] = []
    per_model_global: Dict[str, Dict[str, float]] = defaultdict(
        lambda: {"a2a_sum": 0.0, "a2a_cnt": 0, "mix_sum": 0.0, "mix_cnt": 0}
    )

    for project in version_projects:
        scenario_a2a = f"{project}-A2A"
        scenario_a2a_mix = f"{project}-A2A_mix"

        if (
            scenario_a2a not in scenario_time_data
            or scenario_a2a_mix not in scenario_time_data
        ):
            continue

        a2a_mix_comparison_lines.append(f"## {project}\n\n")
        a2a_mix_comparison_lines.append("### Project-Level Summary\n\n")

        data_a2a = scenario_time_data[scenario_a2a]
        data_a2a_mix = scenario_time_data[scenario_a2a_mix]
        all_models = sorted(set(data_a2a.keys()) | set(data_a2a_mix.keys()))

        # Overall comparison
        overall_a2a_total = 0.0
        overall_a2a_count = 0
        overall_a2a_mix_total = 0.0
        overall_a2a_mix_count = 0

        for model in all_models:
            stats_a2a = compute_time_statistics(data_a2a.get(model, []))
            stats_a2a_mix = compute_time_statistics(data_a2a_mix.get(model, []))
            overall_a2a_total += stats_a2a["total"]
            overall_a2a_count += stats_a2a["count"]
            overall_a2a_mix_total += stats_a2a_mix["total"]
            overall_a2a_mix_count += stats_a2a_mix["count"]
            # accumulate for global per-model summary
            per_model_global[model]["a2a_sum"] += stats_a2a["total"]
            per_model_global[model]["a2a_cnt"] += stats_a2a["count"]
            per_model_global[model]["mix_sum"] += stats_a2a_mix["total"]
            per_model_global[model]["mix_cnt"] += stats_a2a_mix["count"]

        if overall_a2a_count > 0 and overall_a2a_mix_count > 0:
            avg_a2a = overall_a2a_total / overall_a2a_count
            avg_a2a_mix = overall_a2a_mix_total / overall_a2a_mix_count
            diff = avg_a2a_mix - avg_a2a
            pct = (diff / avg_a2a * 100) if avg_a2a > 0 else 0
            a2a_mix_comparison_lines.append("### Overall Summary\n\n")
            a2a_mix_comparison_lines.append(
                "| A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n"
            )
            a2a_mix_comparison_lines.append("| --- | --- | --- |\n")
            a2a_mix_comparison_lines.append(
                f"| {avg_a2a:.2f} | {avg_a2a_mix:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n\n"
            )
            overall_deltas.append(
                {
                    "project": project,
                    "a2a": avg_a2a,
                    "mix": avg_a2a_mix,
                    "diff": diff,
                    "pct": pct,
                }
            )

        # Per-model comparison
        a2a_mix_comparison_lines.append("### Per-Model Comparison\n\n")
        a2a_mix_comparison_lines.append(
            "| Model | A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n"
        )
        a2a_mix_comparison_lines.append("| --- | --- | --- | --- |\n")

        for model in all_models:
            stats_a2a = compute_time_statistics(data_a2a.get(model, []))
            stats_a2a_mix = compute_time_statistics(data_a2a_mix.get(model, []))
            mean_diff = stats_a2a_mix["mean"] - stats_a2a["mean"]
            mean_pct = (
                (mean_diff / stats_a2a["mean"] * 100) if stats_a2a["mean"] > 0 else 0
            )
            a2a_mix_comparison_lines.append(
                f"| {model} | {stats_a2a['mean']:.2f} | {stats_a2a_mix['mean']:.2f} | "
                f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n"
            )

        a2a_mix_comparison_lines.append("\n---\n\n")

    # Global cross-project summaries (coarse)
    if overall_deltas:
        a2a_mix_comparison_lines.insert(
            4,
            "## Overall (All Projects)\n\n"
            "| Project | A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n"
            "| --- | --- | --- | --- |\n"
            + "".join(
                f"| {d['project']} | {d['a2a']:.2f} | {d['mix']:.2f} | {d['diff']:+.2f}s ({d['pct']:+.1f}%) |\n"
                for d in overall_deltas
            )
            + "\n",
        )

    if per_model_global:
        per_model_lines = []
        per_model_lines.append("## All Projects Combined (Per-Model)\n\n")
        per_model_lines.append(
            "| Model | A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n"
        )
        per_model_lines.append("| --- | --- | --- | --- |\n")
        for model in MODEL_ORDER:
            stats = per_model_global.get(model)
            if not stats:
                continue
            a2a_cnt = stats["a2a_cnt"]
            mix_cnt = stats["mix_cnt"]
            if a2a_cnt <= 0 or mix_cnt <= 0:
                continue
            avg_a2a = stats["a2a_sum"] / a2a_cnt
            avg_mix = stats["mix_sum"] / mix_cnt
            diff = avg_mix - avg_a2a
            pct = (diff / avg_a2a * 100) if avg_a2a > 0 else 0
            per_model_lines.append(
                f"| {model} | {avg_a2a:.2f} | {avg_mix:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n"
            )
        per_model_lines.append("\n---\n\n")
        # insert after top intro (after first 4 elements added earlier)
        a2a_mix_comparison_lines[5:5] = per_model_lines

    a2a_mix_md_path = out_dir / "A2A_vs_A2A_mix_Detailed_Comparison.md"
    a2a_mix_md_path.write_text("".join(a2a_mix_comparison_lines), encoding="utf-8")
    print(f"Created: {a2a_mix_md_path}")

    # 5. Generate per-project model comparison for all 21 projects
    print("\nGenerating per-project model comparisons (21 projects)...")
    all_project_names = sorted(scenario_time_data.keys())

    model_comparison_lines = []
    model_comparison_lines.append("# Per-Project Model Performance Comparison\n\n")
    model_comparison_lines.append(
        f"This document compares model performance within each of the {len(all_project_names)} projects.\n\n"
    )
    model_comparison_lines.append("Each project shows:\n")
    model_comparison_lines.append(
        "- Model statistics (mean, median, count, total time)\n"
    )
    model_comparison_lines.append(
        "- Relative performance compared to the fastest model\n\n"
    )

    # Add global summary across all projects first
    model_comparison_lines.append("---\n\n")
    model_comparison_lines.append(generate_overall_model_comparison(scenario_time_data))
    model_comparison_lines.append("---\n\n")

    for project_name in all_project_names:
        model_comparison_lines.append(
            generate_project_model_comparison(project_name, scenario_time_data)
        )
        model_comparison_lines.append("---\n\n")

    model_comparison_md_path = out_dir / "Per_Project_Model_Comparison.md"
    model_comparison_md_path.write_text(
        "".join(model_comparison_lines), encoding="utf-8"
    )
    print(f"Created: {model_comparison_md_path}")

    print("\n" + "=" * 60)
    print("All time comparison summaries generated!")
    print("=" * 60)


if __name__ == "__main__":
    main()