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
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
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
#!/usr/bin/env python3
"""
Generate radar charts for evaluation results across different scenarios.
Creates one PDF radar chart per subfolder showing all models' performance.
"""

import pandas as pd
import numpy as np
from pathlib import Path
import math

try:
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from matplotlib.patches import Circle

    mpl.rcParams["font.family"] = "Times New Roman"
except ImportError:
    plt = None
    mpl = None
    Circle = None

# Metrics to plot
METRICS = [
    "exact_match",
    "any_order_match",
    "precision",
    "recall",
    "retry_rate",
    "pass_rate",
]

# Color palette for different models - professional academic colors (Tableau 10 style)
MODEL_COLORS = {
    "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
}

MODEL_CATEGORY = {
    "GPT-5": "closed",
    "GPT-4o-mini": "closed",
    "DeepSeek-V3-1": "open",
    "DeepSeek-R1": "open",
    "Gemini-2.5-flash": "closed",
    "Gemini-2.5-flash-nothinking": "closed",
    "Qwen3-235b": "open",
}


def df_to_markdown(df):
    """Convert a DataFrame to a simple markdown table without external deps."""
    headers = list(df.columns)
    lines = []
    lines.append("| " + " | ".join(headers) + " |")
    lines.append("| " + " | ".join(["---"] * len(headers)) + " |")
    for _, row in df.iterrows():
        values = []
        for val in row:
            if isinstance(val, float):
                values.append(f"{val:.2f}")
            else:
                values.append(str(val))
        lines.append("| " + " | ".join(values) + " |")
    return "\n".join(lines)


def metric_display_name(metric, base_project, gt_projects):
    if metric == "pass_rate" and gt_projects and base_project in gt_projects:
        return "average_score"
    return metric


def series_metric_headers(series_name, gt_projects):
    rate_label = (
        "average_score" if gt_projects and series_name in gt_projects else "pass_rate"
    )
    return [(rate_label if m == "pass_rate" else m) for m in METRICS]


def generate_model_pair_comparison(
    model_a, model_b, data_dict, comparison_name, gt_projects=None
):
    """Generate comparison table between two models across all scenarios."""
    lines = []
    lines.append(f"# {comparison_name}\n\n")

    # Group scenarios by base project name (remove -A2A, -A2A_mix, -MCP suffixes)
    project_series = {}
    for scenario_name in data_dict.keys():
        # Extract base project name
        base_name = scenario_name
        for suffix in ["-A2A_mix", "-A2A", "-MCP"]:
            if scenario_name.endswith(suffix):
                base_name = scenario_name[: -len(suffix)]
                break

        if base_name not in project_series:
            project_series[base_name] = []
        project_series[base_name].append(scenario_name)

    # Calculate averaged metrics for each project series
    series_data = {}
    for base_name, scenarios in project_series.items():
        series_data[base_name] = {model_a: {}, model_b: {}}

        for metric in METRICS:
            vals_a = []
            vals_b = []
            for scenario_name in scenarios:
                scenario_data = data_dict[scenario_name]
                if model_a in scenario_data and model_b in scenario_data:
                    vals_a.append(scenario_data[model_a].get(metric, 0))
                    vals_b.append(scenario_data[model_b].get(metric, 0))

            if vals_a and vals_b:
                series_data[base_name][model_a][metric] = np.mean(vals_a)
                series_data[base_name][model_b][metric] = np.mean(vals_b)

    # Calculate overall averages
    overall_avgs = {
        metric: {"a": [], "b": []} for metric in METRICS if metric != "pass_rate"
    }
    overall_rate_avgs = {
        "gt": {"a": [], "b": []},
        "non_gt": {"a": [], "b": []},
    }
    for base_name in series_data.keys():
        for metric in METRICS:
            if (
                metric not in series_data[base_name][model_a]
                or metric not in series_data[base_name][model_b]
            ):
                continue

            if metric == "pass_rate":
                bucket = "gt" if gt_projects and base_name in gt_projects else "non_gt"
                overall_rate_avgs[bucket]["a"].append(
                    series_data[base_name][model_a][metric]
                )
                overall_rate_avgs[bucket]["b"].append(
                    series_data[base_name][model_b][metric]
                )
                continue

            overall_avgs[metric]["a"].append(series_data[base_name][model_a][metric])
            overall_avgs[metric]["b"].append(series_data[base_name][model_b][metric])

    # Add overall summary section
    lines.append("## Overall Summary (Averaged Across All Project Series)\n\n")
    lines.append(f"| Metric | {model_a} | {model_b} | Diff (A-B) |\n")
    lines.append("| --- | --- | --- | --- |\n")
    for metric in METRICS:
        if metric == "pass_rate":
            if overall_rate_avgs["gt"]["a"]:
                avg_a = np.mean(overall_rate_avgs["gt"]["a"])
                avg_b = np.mean(overall_rate_avgs["gt"]["b"])
                diff = avg_a - avg_b
                lines.append(
                    f"| average_score | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n"
                )
            if overall_rate_avgs["non_gt"]["a"]:
                avg_a = np.mean(overall_rate_avgs["non_gt"]["a"])
                avg_b = np.mean(overall_rate_avgs["non_gt"]["b"])
                diff = avg_a - avg_b
                lines.append(
                    f"| pass_rate | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n"
                )
            continue

        if overall_avgs[metric]["a"]:
            avg_a = np.mean(overall_avgs[metric]["a"])
            avg_b = np.mean(overall_avgs[metric]["b"])
            diff = avg_a - avg_b
            lines.append(f"| {metric} | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n")
    lines.append("\n---\n\n")

    # Add per-series comparisons
    headers = ["Project Series", f"{model_a}", f"{model_b}", "Diff (A-B)"]

    for metric in METRICS:
        if metric != "pass_rate":
            lines.append(f"## {metric}\n\n")
            lines.append("| " + " | ".join(headers) + " |\n")
            lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")

            for base_name in sorted(series_data.keys()):
                if (
                    metric in series_data[base_name][model_a]
                    and metric in series_data[base_name][model_b]
                ):
                    val_a = series_data[base_name][model_a][metric]
                    val_b = series_data[base_name][model_b][metric]
                    diff = val_a - val_b
                    lines.append(
                        f"| {base_name} | {val_a:.2f} | {val_b:.2f} | {diff:+.2f} |\n"
                    )
            lines.append("\n")
            continue

        lines.append("## average_score\n\n")
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")
        for base_name in sorted(series_data.keys()):
            if gt_projects and base_name not in gt_projects:
                continue
            if (
                metric in series_data[base_name][model_a]
                and metric in series_data[base_name][model_b]
            ):
                val_a = series_data[base_name][model_a][metric]
                val_b = series_data[base_name][model_b][metric]
                diff = val_a - val_b
                lines.append(
                    f"| {base_name} | {val_a:.2f} | {val_b:.2f} | {diff:+.2f} |\n"
                )
        lines.append("\n")

        lines.append("## pass_rate\n\n")
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")
        for base_name in sorted(series_data.keys()):
            if gt_projects and base_name in gt_projects:
                continue
            if (
                metric in series_data[base_name][model_a]
                and metric in series_data[base_name][model_b]
            ):
                val_a = series_data[base_name][model_a][metric]
                val_b = series_data[base_name][model_b][metric]
                diff = val_a - val_b
                lines.append(
                    f"| {base_name} | {val_a:.2f} | {val_b:.2f} | {diff:+.2f} |\n"
                )
        lines.append("\n")

    return "".join(lines)


def generate_mcp_comparison(base_project, scenario_data_dict, gt_projects=None):
    """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_data_dict
        or hardcoded_scenario not in scenario_data_dict
    ):
        lines.append(f"_Data not available for comparison_\n\n")
        return "".join(lines)

    mcp_data = scenario_data_dict[mcp_scenario]
    hardcoded_data = scenario_data_dict[hardcoded_scenario]

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

    # Calculate overall averages first
    overall_avgs = {metric: {"mcp": [], "hard": []} for metric in METRICS}
    for model in all_models:
        for metric in METRICS:
            mcp_val = mcp_data.get(model, {}).get(metric, 0)
            hard_val = hardcoded_data.get(model, {}).get(metric, 0)
            overall_avgs[metric]["mcp"].append(mcp_val)
            overall_avgs[metric]["hard"].append(hard_val)

    # Add overall summary section
    lines.append("## Overall Summary (Averaged Across All Models)\n\n")
    lines.append("| Metric | MCP | Hardcoded | Diff (MCP-Hardcoded) |\n")
    lines.append("| --- | --- | --- | --- |\n")
    for metric in METRICS:
        if overall_avgs[metric]["mcp"]:
            avg_mcp = np.mean(overall_avgs[metric]["mcp"])
            avg_hard = np.mean(overall_avgs[metric]["hard"])
            diff = avg_mcp - avg_hard
            display_metric = metric_display_name(metric, base_project, gt_projects)
            lines.append(
                f"| {display_metric} | {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f} |\n"
            )
    lines.append("\n---\n\n")

    for metric in METRICS:
        display_metric = metric_display_name(metric, base_project, gt_projects)
        lines.append(f"## {display_metric}\n\n")
        headers = ["Model", "MCP", "Hardcoded", "Diff (MCP-Hardcoded)"]
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")

        for model in sorted(all_models):
            mcp_val = mcp_data.get(model, {}).get(metric, 0)
            hard_val = hardcoded_data.get(model, {}).get(metric, 0)
            diff = mcp_val - hard_val
            lines.append(
                f"| {model} | {mcp_val:.2f} | {hard_val:.2f} | {diff:+.2f} |\n"
            )
        lines.append("\n")

    return "".join(lines)


def generate_mcp_overall_comparison(projects, scenario_data_dict, gt_projects=None):
    """Generate overall comparison across all MCP vs hardcoded projects."""
    lines = []
    lines.append("# Overall MCP vs Hardcoded Comparison\n\n")
    lines.append(
        "Averaged across all projects: MarkdownValidator, GameBuilder, EmailResponder\n\n"
    )

    # Collect data from all projects
    overall_data = {}
    framework_data = {
        metric: {"mcp": [], "hard": []} for metric in METRICS if metric != "pass_rate"
    }
    framework_rate_data = {
        "gt": {"mcp": [], "hard": []},
        "non_gt": {"mcp": [], "hard": []},
    }
    overall_rate_data = {}

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

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

        mcp_data = scenario_data_dict[mcp_scenario]
        hardcoded_data = scenario_data_dict[hardcoded_scenario]

        all_models = set(mcp_data.keys()) | set(hardcoded_data.keys())
        project_bucket = "gt" if gt_projects and project in gt_projects else "non_gt"

        for model in all_models:
            if model not in overall_data:
                overall_data[model] = {
                    metric: {"mcp": [], "hard": []}
                    for metric in METRICS
                    if metric != "pass_rate"
                }
            if model not in overall_rate_data:
                overall_rate_data[model] = {
                    "gt": {"mcp": [], "hard": []},
                    "non_gt": {"mcp": [], "hard": []},
                }

            for metric in METRICS:
                mcp_val = mcp_data.get(model, {}).get(metric, 0)
                hard_val = hardcoded_data.get(model, {}).get(metric, 0)
                if metric == "pass_rate":
                    overall_rate_data[model][project_bucket]["mcp"].append(mcp_val)
                    overall_rate_data[model][project_bucket]["hard"].append(hard_val)
                    framework_rate_data[project_bucket]["mcp"].append(mcp_val)
                    framework_rate_data[project_bucket]["hard"].append(hard_val)
                else:
                    overall_data[model][metric]["mcp"].append(mcp_val)
                    overall_data[model][metric]["hard"].append(hard_val)
                    framework_data[metric]["mcp"].append(mcp_val)
                    framework_data[metric]["hard"].append(hard_val)

    # Add framework-level comparison (all models averaged)
    lines.append("## Framework-Level Comparison (All Models Averaged)\n\n")
    lines.append("| Metric | MCP | Hardcoded | Diff (MCP-Hardcoded) |\n")
    lines.append("| --- | --- | --- | --- |\n")
    for metric in METRICS:
        if metric == "pass_rate":
            if framework_rate_data["gt"]["mcp"]:
                avg_mcp = np.mean(framework_rate_data["gt"]["mcp"])
                avg_hard = np.mean(framework_rate_data["gt"]["hard"])
                diff = avg_mcp - avg_hard
                lines.append(
                    f"| average_score | {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f} |\n"
                )
            if framework_rate_data["non_gt"]["mcp"]:
                avg_mcp = np.mean(framework_rate_data["non_gt"]["mcp"])
                avg_hard = np.mean(framework_rate_data["non_gt"]["hard"])
                diff = avg_mcp - avg_hard
                lines.append(
                    f"| pass_rate | {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f} |\n"
                )
            continue

        if framework_data[metric]["mcp"]:
            avg_mcp = np.mean(framework_data[metric]["mcp"])
            avg_hard = np.mean(framework_data[metric]["hard"])
            diff = avg_mcp - avg_hard
            lines.append(
                f"| {metric} | {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f} |\n"
            )
    lines.append("\n---\n\n")

    # Generate per-model summary tables
    for metric in METRICS:
        if metric != "pass_rate":
            lines.append(f"## {metric}\n\n")
            headers = [
                "Model",
                "MCP (Avg)",
                "Hardcoded (Avg)",
                "Diff (MCP-Hardcoded)",
            ]
            lines.append("| " + " | ".join(headers) + " |\n")
            lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")

            for model in sorted(overall_data.keys()):
                if overall_data[model][metric]["mcp"]:
                    avg_mcp = np.mean(overall_data[model][metric]["mcp"])
                    avg_hard = np.mean(overall_data[model][metric]["hard"])
                    diff = avg_mcp - avg_hard
                    lines.append(
                        f"| {model} | {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f} |\n"
                    )
            lines.append("\n")
            continue

        lines.append("## average_score\n\n")
        headers = ["Model", "MCP (Avg)", "Hardcoded (Avg)", "Diff (MCP-Hardcoded)"]
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")
        for model in sorted(overall_rate_data.keys()):
            if overall_rate_data[model]["gt"]["mcp"]:
                avg_mcp = np.mean(overall_rate_data[model]["gt"]["mcp"])
                avg_hard = np.mean(overall_rate_data[model]["gt"]["hard"])
                diff = avg_mcp - avg_hard
                lines.append(
                    f"| {model} | {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f} |\n"
                )
        lines.append("\n")

        lines.append("## pass_rate\n\n")
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")
        for model in sorted(overall_rate_data.keys()):
            if overall_rate_data[model]["non_gt"]["mcp"]:
                avg_mcp = np.mean(overall_rate_data[model]["non_gt"]["mcp"])
                avg_hard = np.mean(overall_rate_data[model]["non_gt"]["hard"])
                diff = avg_mcp - avg_hard
                lines.append(
                    f"| {model} | {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f} |\n"
                )
        lines.append("\n")

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


def generate_version_comparison(
    base_project,
    version_a_suffix,
    version_b_suffix,
    scenario_data_dict,
    version_a_name,
    version_b_name,
    gt_projects=None,
):
    """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_data_dict or scenario_b not in scenario_data_dict:
        lines.append(f"_Data not available for comparison_\n\n")
        return "".join(lines)

    data_a = scenario_data_dict[scenario_a]
    data_b = scenario_data_dict[scenario_b]

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

    # Calculate overall averages first
    overall_avgs = {metric: {"a": [], "b": []} for metric in METRICS}
    for model in all_models:
        for metric in METRICS:
            val_a = data_a.get(model, {}).get(metric, 0)
            val_b = data_b.get(model, {}).get(metric, 0)
            overall_avgs[metric]["a"].append(val_a)
            overall_avgs[metric]["b"].append(val_b)

    # Add overall summary section
    lines.append("## Overall Summary (Averaged Across All Models)\n\n")
    lines.append(
        f"| Metric | {version_a_name} | {version_b_name} | Diff ({version_a_name}-{version_b_name}) |\n"
    )
    lines.append("| --- | --- | --- | --- |\n")
    for metric in METRICS:
        if overall_avgs[metric]["a"]:
            avg_a = np.mean(overall_avgs[metric]["a"])
            avg_b = np.mean(overall_avgs[metric]["b"])
            diff = avg_a - avg_b
            display_metric = metric_display_name(metric, base_project, gt_projects)
            lines.append(
                f"| {display_metric} | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n"
            )
    lines.append("\n---\n\n")

    for metric in METRICS:
        display_metric = metric_display_name(metric, base_project, gt_projects)
        lines.append(f"## {display_metric}\n\n")
        headers = [
            "Model",
            version_a_name,
            version_b_name,
            f"Diff ({version_a_name}-{version_b_name})",
        ]
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")

        for model in sorted(all_models):
            val_a = data_a.get(model, {}).get(metric, 0)
            val_b = data_b.get(model, {}).get(metric, 0)
            diff = val_a - val_b
            lines.append(f"| {model} | {val_a:.2f} | {val_b:.2f} | {diff:+.2f} |\n")
        lines.append("\n")

    return "".join(lines)


def generate_version_overall_comparison(
    projects,
    version_a_suffix,
    version_b_suffix,
    scenario_data_dict,
    version_a_name,
    version_b_name,
    comparison_title,
    gt_projects=None,
):
    """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_data = {
        metric: {"a": [], "b": []} for metric in METRICS if metric != "pass_rate"
    }
    framework_rate_data = {
        "gt": {"a": [], "b": []},
        "non_gt": {"a": [], "b": []},
    }
    overall_rate_data = {}

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

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

        data_a = scenario_data_dict[scenario_a]
        data_b = scenario_data_dict[scenario_b]

        all_models = set(data_a.keys()) | set(data_b.keys())
        project_bucket = "gt" if gt_projects and project in gt_projects else "non_gt"

        for model in all_models:
            if model not in overall_data:
                overall_data[model] = {
                    metric: {"a": [], "b": []}
                    for metric in METRICS
                    if metric != "pass_rate"
                }
            if model not in overall_rate_data:
                overall_rate_data[model] = {
                    "gt": {"a": [], "b": []},
                    "non_gt": {"a": [], "b": []},
                }

            for metric in METRICS:
                val_a = data_a.get(model, {}).get(metric, 0)
                val_b = data_b.get(model, {}).get(metric, 0)
                if metric == "pass_rate":
                    overall_rate_data[model][project_bucket]["a"].append(val_a)
                    overall_rate_data[model][project_bucket]["b"].append(val_b)
                    framework_rate_data[project_bucket]["a"].append(val_a)
                    framework_rate_data[project_bucket]["b"].append(val_b)
                else:
                    overall_data[model][metric]["a"].append(val_a)
                    overall_data[model][metric]["b"].append(val_b)
                    framework_data[metric]["a"].append(val_a)
                    framework_data[metric]["b"].append(val_b)

    # Add framework-level comparison (all models averaged)
    lines.append("## Framework-Level Comparison (All Models Averaged)\n\n")
    lines.append(
        f"| Metric | {version_a_name} | {version_b_name} | Diff ({version_a_name}-{version_b_name}) |\n"
    )
    lines.append("| --- | --- | --- | --- |\n")
    for metric in METRICS:
        if metric == "pass_rate":
            if framework_rate_data["gt"]["a"]:
                avg_a = np.mean(framework_rate_data["gt"]["a"])
                avg_b = np.mean(framework_rate_data["gt"]["b"])
                diff = avg_a - avg_b
                lines.append(
                    f"| average_score | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n"
                )
            if framework_rate_data["non_gt"]["a"]:
                avg_a = np.mean(framework_rate_data["non_gt"]["a"])
                avg_b = np.mean(framework_rate_data["non_gt"]["b"])
                diff = avg_a - avg_b
                lines.append(
                    f"| pass_rate | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n"
                )
            continue

        if framework_data[metric]["a"]:
            avg_a = np.mean(framework_data[metric]["a"])
            avg_b = np.mean(framework_data[metric]["b"])
            diff = avg_a - avg_b
            lines.append(f"| {metric} | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n")
    lines.append("\n---\n\n")

    # Generate per-model summary tables
    for metric in METRICS:
        headers = [
            "Model",
            f"{version_a_name} (Avg)",
            f"{version_b_name} (Avg)",
            f"Diff ({version_a_name}-{version_b_name})",
        ]

        if metric != "pass_rate":
            lines.append(f"## {metric}\n\n")
            lines.append("| " + " | ".join(headers) + " |\n")
            lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")

            for model in sorted(overall_data.keys()):
                if overall_data[model][metric]["a"]:
                    avg_a = np.mean(overall_data[model][metric]["a"])
                    avg_b = np.mean(overall_data[model][metric]["b"])
                    diff = avg_a - avg_b
                    lines.append(
                        f"| {model} | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n"
                    )
            lines.append("\n")
            continue

        lines.append("## average_score\n\n")
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")
        for model in sorted(overall_rate_data.keys()):
            if overall_rate_data[model]["gt"]["a"]:
                avg_a = np.mean(overall_rate_data[model]["gt"]["a"])
                avg_b = np.mean(overall_rate_data[model]["gt"]["b"])
                diff = avg_a - avg_b
                lines.append(f"| {model} | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n")
        lines.append("\n")

        lines.append("## pass_rate\n\n")
        lines.append("| " + " | ".join(headers) + " |\n")
        lines.append("| " + " | ".join(["---"] * len(headers)) + " |\n")
        for model in sorted(overall_rate_data.keys()):
            if overall_rate_data[model]["non_gt"]["a"]:
                avg_a = np.mean(overall_rate_data[model]["non_gt"]["a"])
                avg_b = np.mean(overall_rate_data[model]["non_gt"]["b"])
                diff = avg_a - avg_b
                lines.append(f"| {model} | {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f} |\n")
        lines.append("\n")

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


def create_radar_chart(df, scenario_name, output_path, pass_rate_label="pass_rate"):
    """
    Create a radar chart for a single scenario with all models.

    Args:
        df: DataFrame containing evaluation results
        scenario_name: Name of the scenario (subfolder name)
        output_path: Path to save the PDF file
    """
    if plt is None:
        print(
            f" Warning: matplotlib not installed, skipping radar chart: {output_path}"
        )
        return
    # Number of metrics
    num_vars = len(METRICS)

    # Compute angle for each axis
    angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
    angles += angles[:1]  # Complete the circle

    # Create figure with polar projection - increase size to avoid overlap
    fig, ax = plt.subplots(figsize=(12, 12), subplot_kw=dict(projection="polar"))

    # Set background color to light blue/grey similar to reference
    ax.set_facecolor("#cedbea")  # slightly lighter blue background
    fig.patch.set_facecolor("white")

    # Plot data for each model
    for idx, row in df.iterrows():
        model_name = row["model"]
        values = [row[metric] for metric in METRICS]
        values += values[:1]  # Complete the circle

        color = MODEL_COLORS.get(model_name, f"C{idx}")

        # Plot the line and fill
        ax.plot(
            angles,
            values,
            "o-",
            linewidth=2,
            label=model_name,
            color=color,
            markersize=6,
        )
        ax.fill(angles, values, alpha=0.15, color=color)

    # Set the labels for each axis so they sit just outside the outer circle
    metric_labels = [
        (pass_rate_label if metric == "pass_rate" else metric) for metric in METRICS
    ]
    ax.set_xticks(angles[:-1])
    # Remove default tick labels; we'll draw them manually at a fixed radius
    ax.set_xticklabels([])

    label_radius = 1.3  # Place labels on the outer grid circle (radius=1.25)
    for angle, label in zip(angles[:-1], metric_labels):
        # Choose horizontal alignment based on angle for better spacing
        if 0 <= angle < np.pi / 2 or 3 * np.pi / 2 <= angle <= 2 * np.pi:
            ha = "left"
        elif np.pi / 2 < angle < 3 * np.pi / 2:
            ha = "right"
        else:
            ha = "center"
        ax.text(
            angle,
            label_radius,
            label,
            ha=ha,
            va="center",
            fontsize=30,
            fontweight="bold",
        )

    # Set radial limits to 1.25; keep labels only up to 1.0
    ax.set_ylim(0, 1.25)
    ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0, 1.25])
    ax.set_yticklabels(
        ["0", "0.25", "0.5", "0.75", "1.0", ""],
        size=30,
        color="black",
        weight="bold",
    )

    # Remove the outer spine (circular border)
    ax.spines["polar"].set_visible(False)

    # Add gridlines
    ax.xaxis.grid(True, linestyle="--", linewidth=3.0, alpha=1.0, color="white")
    ax.yaxis.grid(True, linestyle="-", linewidth=3.0, color="white", alpha=1.0)

    # Title removed per user request
    # Adjust layout
    plt.tight_layout()

    # Save the figure
    plt.savefig(output_path, format="pdf", dpi=300, bbox_inches="tight")
    plt.close()

    print(f" Created: {output_path}")


def create_legend_pdf(output_path):
    if plt is None:
        print(f" Warning: matplotlib not installed, skipping legend PDF: {output_path}")
        return
    fig, ax = plt.subplots(figsize=(4, 3))
    ax.axis("off")

    handles = []
    labels = []
    for model_name, color in MODEL_COLORS.items():
        (handle,) = ax.plot(
            [],
            [],
            "o-",
            linewidth=2,
            markersize=8,
            color=color,
        )
        handles.append(handle)
        labels.append(model_name)

    ax.legend(
        handles,
        labels,
        loc="center",
        frameon=True,
        fancybox=True,
        shadow=False,
        prop={"size": 12, "weight": "bold"},
    )

    plt.tight_layout()
    plt.savefig(output_path, format="pdf", dpi=300, bbox_inches="tight")
    plt.close(fig)

    print(f" Legend PDF created: {output_path}")


def create_legend_pdf_horizontal(output_path):
    if plt is None:
        print(
            f" Warning: matplotlib not installed, skipping horizontal legend PDF: {output_path}"
        )
        return
    # Wide and very low-height figure to make the legend strip as "flat" as possible
    fig, ax = plt.subplots(figsize=(12, 1.0))
    ax.axis("off")

    handles = []
    labels = []
    for model_name, color in MODEL_COLORS.items():
        (handle,) = ax.plot(
            [],
            [],
            "o-",
            linewidth=2,
            markersize=8,
            color=color,
        )
        handles.append(handle)
        labels.append(model_name)

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

    plt.tight_layout(pad=0.0)
    plt.savefig(output_path, format="pdf", dpi=300, bbox_inches="tight", pad_inches=0.0)
    plt.close(fig)

    print(f" Horizontal legend PDF created: {output_path}")


def main():
    """Main function to process all subfolders and generate radar charts."""
    base_dir = Path("/Users/wzr/TOSEM-2025/RESULTS/RQ1")
    output_dir = base_dir / "RadarCharts"
    output_dir.mkdir(exist_ok=True)

    # Find all evaluation_results.csv files
    csv_files = list(base_dir.glob("*/evaluation_results.csv"))

    print(f"Found {len(csv_files)} evaluation_results.csv files")
    print("=" * 60)

    # Dictionary to accumulate data for overall average
    all_data = {
        model: {metric: [] for metric in METRICS} for model in MODEL_COLORS.keys()
    }

    series_data = {}
    combined_open_closed_lines = []
    combined_series_avg_lines = []
    scenario_data = {}
    gt_projects = set()

    # Process each subfolder
    for csv_file in sorted(csv_files):
        scenario_name = csv_file.parent.name
        series_name = scenario_name.split("-")[0]

        try:
            # Read the main evaluation results CSV file
            df = pd.read_csv(csv_file)

            # Read retry_summary.csv for error_rate
            retry_file = csv_file.parent / "retry_summary.csv"
            if retry_file.exists():
                retry_df = pd.read_csv(retry_file)
                retry_rate_col = "Retry_Rate(%)"
                if (
                    retry_rate_col not in retry_df.columns
                    and "Error_Rate(%)" in retry_df.columns
                ):
                    retry_rate_col = "Error_Rate(%)"
                retry_df["retry_rate"] = retry_df[retry_rate_col] / 100.0
                # Merge with main dataframe
                df = df.merge(
                    retry_df[["Model", "retry_rate"]],
                    left_on="model",
                    right_on="Model",
                    how="left",
                )
                df = df.drop(columns=["Model"])
                df["retry_rate"] = df["retry_rate"].fillna(0.0)
            else:
                print(f" Warning: retry_summary.csv not found for {scenario_name}")
                df["retry_rate"] = 0.0

            # Read success_rate.csv for success_rate
            success_file = csv_file.parent / "success_rate.csv"
            if success_file.exists():
                success_df = pd.read_csv(success_file)
                # Convert Success_Rate(%) to decimal pass_rate
                success_df["pass_rate"] = success_df["Success_Rate(%)"] / 100.0
                # Merge with main dataframe
                df = df.merge(
                    success_df[["Model", "pass_rate"]],
                    left_on="model",
                    right_on="Model",
                    how="left",
                )
                df = df.drop(columns=["Model"])
                df["pass_rate"] = df["pass_rate"].fillna(0.0)
            else:
                print(f" Warning: success_rate.csv not found for {scenario_name}")
                df["pass_rate"] = 0.0

            df["pass_rate_agg"] = df["pass_rate"]

            pass_rate_label = "pass_rate"
            score_file = csv_file.parent / "score_summary.csv"
            if score_file.exists():
                score_df = pd.read_csv(score_file)
                score_df["average_score"] = score_df["Mean_Score"] / 100.0
                df = df.merge(
                    score_df[["Model", "average_score"]],
                    left_on="model",
                    right_on="Model",
                    how="left",
                )
                df["pass_rate"] = df["average_score"].fillna(df["pass_rate"])
                df = df.drop(columns=["Model", "average_score"])
                pass_rate_label = "average_score"
                gt_projects.add(series_name)

            # Check if all required metrics are present
            missing_metrics = [m for m in METRICS if m not in df.columns]
            if missing_metrics:
                print(f" Skipping {scenario_name}: missing metrics {missing_metrics}")
                continue

            # Store per-scenario data for comparisons
            scenario_data[scenario_name] = {}
            for idx, row in df.iterrows():
                model_name = row["model"]
                scenario_data[scenario_name][model_name] = {
                    metric: row[metric] for metric in METRICS
                }

            # Accumulate data for overall and series-level charts
            for idx, row in df.iterrows():
                model_name = row["model"]
                if model_name in all_data:
                    for metric in METRICS:
                        value = row[metric]
                        all_data[model_name][metric].append(value)
                        series_models = series_data.setdefault(series_name, {})
                        if model_name not in series_models:
                            series_models[model_name] = {m: [] for m in METRICS}
                        series_models[model_name][metric].append(value)

            # Create output path (all PDFs go to RadarCharts, filenames unchanged)
            output_path = output_dir / f"{scenario_name}_radar.pdf"

            # Generate radar chart
            create_radar_chart(
                df,
                scenario_name,
                output_path,
                pass_rate_label=pass_rate_label,
            )

        except Exception as e:
            print(f" Error processing {scenario_name}: {e}")

    print("=" * 60)
    print("All individual radar charts generated successfully!")
    print("=" * 60)

    # Generate overall average chart
    try:
        print("Generating overall average chart...")

        # Calculate averages for each model
        avg_data = []
        for model_name, metrics_data in all_data.items():
            row_data = {"model": model_name}
            for metric in METRICS:
                if metrics_data[metric]:  # Check if there's data
                    row_data[metric] = np.mean(metrics_data[metric])
                else:
                    row_data[metric] = 0
            avg_data.append(row_data)

        # Create DataFrame
        avg_df = pd.DataFrame(avg_data)

        group_rows = []
        for group_name in ["open", "closed"]:
            group_models = [
                m for m, category in MODEL_CATEGORY.items() if category == group_name
            ]
            if not group_models:
                continue
            group_df = avg_df[avg_df["model"].isin(group_models)]
            if group_df.empty:
                continue
            row = {"group": group_name, "model_count": len(group_df)}
            for metric in METRICS:
                row[metric] = float(group_df[metric].mean())
            group_rows.append(row)
        if group_rows:
            header_cols = ["Group", "Model Count"] + METRICS
            header_line = "| " + " | ".join(header_cols) + " |\n"
            separator_line = "| " + " | ".join(["---"] * len(header_cols)) + " |\n"
            md_lines = []
            md_lines.append("# Overall Open vs Closed Models\n\n")
            md_lines.append(header_line)
            md_lines.append(separator_line)
            for row in group_rows:
                row_vals = [
                    row["group"],
                    str(row["model_count"]),
                ]
                for metric in METRICS:
                    val = row[metric]
                    row_vals.append(f"{val:.2f}")
                md_lines.append("| " + " | ".join(row_vals) + " |\n")
            combined_open_closed_lines.extend(md_lines)
            combined_open_closed_lines.append("\n")

        # First, calculate overall summary across all projects
        overall_models_data = {}
        for series_name, models_data in series_data.items():
            for model_name, metrics_data in models_data.items():
                if model_name not in overall_models_data:
                    overall_models_data[model_name] = {m: [] for m in METRICS}
                for metric in METRICS:
                    values = metrics_data.get(metric, [])
                    overall_models_data[model_name][metric].extend(values)

        # Generate overall summary table
        if overall_models_data:
            overall_rows = []
            for model_name, metrics_data in overall_models_data.items():
                row_data = {"model": model_name}
                for metric in METRICS:
                    values = metrics_data.get(metric, [])
                    if values:
                        row_data[metric] = float(np.mean(values))
                    else:
                        row_data[metric] = 0
                overall_rows.append(row_data)

            if overall_rows:
                overall_df = pd.DataFrame(overall_rows)
                combined_series_avg_lines.append("# Overall Summary (All Projects)\n\n")
                combined_series_avg_lines.append(df_to_markdown(overall_df) + "\n\n")

        for series_name, models_data in sorted(series_data.items()):
            series_avg_rows = []
            for model_name, metrics_data in models_data.items():
                row_data = {"model": model_name}
                for metric in METRICS:
                    values = metrics_data.get(metric, [])
                    if values:
                        row_data[metric] = float(np.mean(values))
                    else:
                        row_data[metric] = 0
                series_avg_rows.append(row_data)
            if not series_avg_rows:
                continue
            series_df = pd.DataFrame(series_avg_rows)
            series_pdf_output = output_dir / f"{series_name}_Series_Average_radar.pdf"
            series_pass_rate_label = (
                "average_score" if series_name in gt_projects else "pass_rate"
            )
            create_radar_chart(
                series_df,
                f"{series_name} Series Average",
                series_pdf_output,
                pass_rate_label=series_pass_rate_label,
            )

            combined_series_avg_lines.append(f"# {series_name} Series Average\n\n")
            if series_pass_rate_label != "pass_rate":
                combined_series_avg_lines.append(
                    df_to_markdown(
                        series_df.rename(columns={"pass_rate": series_pass_rate_label})
                    )
                    + "\n\n"
                )
            else:
                combined_series_avg_lines.append(df_to_markdown(series_df) + "\n\n")

            group_rows = []
            for group_name in ["open", "closed"]:
                group_models = [
                    m
                    for m, category in MODEL_CATEGORY.items()
                    if category == group_name
                ]
                if not group_models:
                    continue
                group_df = series_df[series_df["model"].isin(group_models)]
                if group_df.empty:
                    continue
                row = {
                    "series": series_name,
                    "group": group_name,
                    "model_count": len(group_df),
                }
                for metric in METRICS:
                    row[metric] = float(group_df[metric].mean())
                group_rows.append(row)
            if group_rows:
                header_cols = [
                    "Series",
                    "Group",
                    "Model Count",
                ] + series_metric_headers(series_name, gt_projects)
                header_line = "| " + " | ".join(header_cols) + " |\n"
                separator_line = "| " + " | ".join(["---"] * len(header_cols)) + " |\n"
                md_lines = []
                md_lines.append(f"# {series_name} Open vs Closed Models\n\n")
                md_lines.append(header_line)
                md_lines.append(separator_line)
                for row in group_rows:
                    row_vals = [
                        row["series"],
                        row["group"],
                        str(row["model_count"]),
                    ]
                    for metric in METRICS:
                        val = row[metric]
                        row_vals.append(f"{val:.2f}")
                    md_lines.append("| " + " | ".join(row_vals) + " |\n")
                combined_open_closed_lines.extend(md_lines)
                combined_open_closed_lines.append("\n")

        # Combine generated markdown files into a single markdown with titles
        if combined_open_closed_lines:
            combined_md_path = output_dir / "All_Open_vs_Closed_summaries.md"
            combined_md_path.write_text(
                "".join(combined_open_closed_lines),
                encoding="utf-8",
            )
            print(f" Combined markdown created: {combined_md_path}")

        # Combine all Series_Average_radar.csv into a single markdown with titles
        if combined_series_avg_lines:
            combined_csv_md_path = output_dir / "All_Series_Average_tables.md"
            combined_csv_md_path.write_text(
                "".join(combined_series_avg_lines),
                encoding="utf-8",
            )
            print(f" Combined Series Average markdown created: {combined_csv_md_path}")

        # Generate overall chart
        overall_output = output_dir / "Overall_Average_radar.pdf"
        create_radar_chart(avg_df, "Overall Average (All Scenarios)", overall_output)

        legend_output = output_dir / "Model_Legend.pdf"
        create_legend_pdf(legend_output)

        legend_horizontal_output = output_dir / "Model_Legend_horizontal.pdf"
        create_legend_pdf_horizontal(legend_horizontal_output)

        # Generate model comparison markdowns - split into 3 separate files

        # File 1: GPT-5 vs GPT-4o-mini (powerful vs lightweight)
        comparison1_lines = []
        comparison1_lines.append(
            generate_model_pair_comparison(
                "GPT-5",
                "GPT-4o-mini",
                scenario_data,
                "GPT-5 vs GPT-4o-mini (Powerful vs Lightweight)",
                gt_projects=gt_projects,
            )
        )
        comparison1_md_path = output_dir / "Comparison_Powerful_vs_Lightweight.md"
        comparison1_md_path.write_text("".join(comparison1_lines), encoding="utf-8")
        print(f" Powerful vs Lightweight comparison created: {comparison1_md_path}")

        # File 2: Reasoning vs Non-Reasoning models
        comparison2_lines = []
        comparison2_lines.append(
            generate_model_pair_comparison(
                "DeepSeek-R1",
                "DeepSeek-V3-1",
                scenario_data,
                "DeepSeek-R1 vs DeepSeek-V3-1 (Reasoning vs Non-Reasoning)",
                gt_projects=gt_projects,
            )
        )
        comparison2_lines.append("\n---\n\n")
        comparison2_lines.append(
            generate_model_pair_comparison(
                "Gemini-2.5-flash",
                "Gemini-2.5-flash-nothinking",
                scenario_data,
                "Gemini-2.5-flash vs Gemini-2.5-flash-nothinking (Reasoning vs Non-Reasoning)",
                gt_projects=gt_projects,
            )
        )
        comparison2_md_path = output_dir / "Comparison_Reasoning_vs_NonReasoning.md"
        comparison2_md_path.write_text("".join(comparison2_lines), encoding="utf-8")
        print(f" Reasoning vs Non-Reasoning comparison created: {comparison2_md_path}")

        # File 3: MCP vs Hardcoded comparisons
        comparison3_lines = []
        projects = ["MarkdownValidator", "GameBuilder", "EmailResponder"]

        # Add overall summary first
        comparison3_lines.append(
            generate_mcp_overall_comparison(
                projects, scenario_data, gt_projects=gt_projects
            )
        )

        # Then add per-project comparisons
        for project in projects:
            comparison3_lines.append(
                generate_mcp_comparison(project, scenario_data, gt_projects=gt_projects)
            )

        comparison3_md_path = output_dir / "Comparison_MCP_vs_Hardcoded.md"
        comparison3_md_path.write_text("".join(comparison3_lines), encoding="utf-8")
        print(f" MCP vs Hardcoded comparison created: {comparison3_md_path}")

        # File 4: MCP vs A2A comparisons
        comparison4_lines = []
        version_projects = [
            "SQL_assistant",
            "intelligent_recruitment_platform",
            "landing_page_generator",
            "self_evaluation_loop_flow",
            "write_a_book_with_flows",
        ]

        # Add overall summary first
        comparison4_lines.append(
            generate_version_overall_comparison(
                version_projects,
                "-MCP",
                "-A2A",
                scenario_data,
                "MCP",
                "A2A",
                "MCP vs A2A Comparison",
                gt_projects=gt_projects,
            )
        )

        # Then add per-project comparisons
        for project in version_projects:
            comparison4_lines.append(
                generate_version_comparison(
                    project,
                    "-MCP",
                    "-A2A",
                    scenario_data,
                    "MCP",
                    "A2A",
                    gt_projects=gt_projects,
                )
            )

        comparison4_md_path = output_dir / "Comparison_MCP_vs_A2A.md"
        comparison4_md_path.write_text("".join(comparison4_lines), encoding="utf-8")
        print(f" MCP vs A2A comparison created: {comparison4_md_path}")

        # File 5: A2A vs A2A_mix comparisons
        comparison5_lines = []

        # Add overall summary first
        comparison5_lines.append(
            generate_version_overall_comparison(
                version_projects,
                "-A2A",
                "-A2A_mix",
                scenario_data,
                "A2A",
                "A2A_mix",
                "A2A vs A2A_mix Comparison",
                gt_projects=gt_projects,
            )
        )

        # Then add per-project comparisons
        for project in version_projects:
            comparison5_lines.append(
                generate_version_comparison(
                    project,
                    "-A2A",
                    "-A2A_mix",
                    scenario_data,
                    "A2A",
                    "A2A_mix",
                    gt_projects=gt_projects,
                )
            )

        comparison5_md_path = output_dir / "Comparison_A2A_vs_A2A_mix.md"
        comparison5_md_path.write_text("".join(comparison5_lines), encoding="utf-8")
        print(f" A2A vs A2A_mix comparison created: {comparison5_md_path}")

        print("=" * 60)
        print(f" Overall average chart created: {overall_output}")
        print(f" Legend PDF created: {legend_output}")
        print(f" Horizontal legend PDF created: {legend_horizontal_output}")

    except Exception as e:
        print(f" Error generating overall chart: {e}")

    print("=" * 60)
    print("All radar charts completed!")


if __name__ == "__main__":
    main()