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
 
 
 
 
 
 
c4e7970
8c10cf2
c4e7970
 
 
 
0998ed0
c4e7970
0998ed0
c4e7970
 
 
 
 
 
 
0998ed0
c4e7970
0998ed0
c4e7970
0998ed0
 
c4e7970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0998ed0
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
165e0b7
 
 
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
c4e7970
 
 
 
8c10cf2
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
c4e7970
165e0b7
c4e7970
 
165e0b7
c4e7970
8c10cf2
165e0b7
8c10cf2
 
 
 
 
165e0b7
 
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
#!/usr/bin/env python3

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

import numpy as np

try:
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter

    HAS_MATPLOTLIB = True
except ModuleNotFoundError:
    plt = None  # type: ignore[assignment]
    FuncFormatter = None  # type: ignore[assignment]
    HAS_MATPLOTLIB = False

if HAS_MATPLOTLIB:
    plt.rcParams["font.family"] = "Times New Roman"

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",
]

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",
}


ARCH_ORDER: List[str] = [
    "Unknown",
    "MCP",
    "A2A",
    "A2A_mix",
]

MODEL_COLORS: Dict[str, str] = {
    "GPT-5": "#1f77b4",
    "GPT-4o-mini": "#ff7f0e",
    "DeepSeek-V3-1": "#2ca02c",
    "DeepSeek-R1": "#d62728",
    "Gemini-2.5-flash": "#9467bd",
    "Gemini-2.5-flash-nothinking": "#8c564b",
    "Qwen3-235b": "#e377c2",
}

STATUS_ORDER: List[str] = [
    "success_no_retry",
    "success_with_retry",
    "failed",
]

STATUS_TITLES: Dict[str, str] = {
    "success_no_retry": "Pass (no retries)",
    "success_with_retry": "Pass (with retries)",
    "failed": "Failure",
}


def infer_project_dir(file_path: str) -> str:
    raw = (file_path or "").strip()
    if not raw:
        return ""
    try:
        p = Path(raw)
        return p.parents[2].name
    except Exception:
        return ""


def infer_architecture(project_dir: str) -> str:
    name = (project_dir or "").strip()
    if not name:
        return "Unknown"
    if name.endswith("-MCP"):
        return "MCP"
    if name.endswith("-H_A2A") or name.endswith("-H-A2A"):
        return "A2A_mix"
    if name.endswith("-A2A"):
        return "A2A"
    return "Unknown"


def infer_base_task(project_dir: str) -> str:
    name = (project_dir or "").strip()
    for suffix in ("-H_A2A", "-H-A2A", "-MCP", "-A2A"):
        if name.endswith(suffix):
            return name[: -len(suffix)]
    return name


def make_project_name(base_task: str, arch: str) -> str:
    task = (base_task or "").strip()
    if not task:
        return ""
    if arch == "Unknown":
        return task
    if arch == "MCP":
        return f"{task}-MCP"
    if arch == "A2A_mix":
        return f"{task}-H-A2A"
    if arch == "A2A":
        return f"{task}-A2A"
    return f"{task}-{arch}"


def infer_architecture_from_project_name(project_name: str) -> str:
    name = (project_name or "").strip()
    if not name:
        return "Unknown"
    if name.endswith("-MCP"):
        return "MCP"
    if name.endswith("-H-A2A") or name.endswith("-H_A2A"):
        return "A2A_mix"
    if name.endswith("-A2A"):
        return "A2A"
    return "Unknown"


def base_task_from_project_name(project_name: str) -> str:
    name = (project_name or "").strip()
    for suffix in ("-H-A2A", "-H_A2A", "-MCP", "-A2A"):
        if name.endswith(suffix):
            return name[: -len(suffix)]
    return name


def export_violin_input_summary(
    projects: List[Tuple[str, str, str]],
    project_data: Dict[str, Dict[str, Dict[str, List[float]]]],
    out_dir: Path,
) -> None:
    if (os.environ.get("EXPORT_VIOLIN_INPUT") or "").strip() not in {
        "1",
        "true",
        "True",
    }:
        return

    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / "violin_input_summary.csv"

    with out_path.open("w", encoding="utf-8", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(
            [
                "project",
                "base_task",
                "architecture",
                "status_group",
                "model",
                "n",
                "mean",
                "median",
                "min",
                "max",
            ]
        )

        for _, _, name in projects:
            pdata = project_data.get(name, {})
            base_task = base_task_from_project_name(name)
            arch = infer_architecture_from_project_name(name)
            for status in STATUS_ORDER:
                by_model = pdata.get(status, {})
                for model in MODEL_ORDER:
                    vals = by_model.get(model, [])
                    if not vals:
                        continue
                    arr = np.asarray(vals, dtype=float)
                    writer.writerow(
                        [
                            name,
                            base_task,
                            arch,
                            status,
                            model,
                            int(arr.size),
                            float(np.mean(arr)),
                            float(np.median(arr)),
                            float(np.min(arr)),
                            float(np.max(arr)),
                        ]
                    )

    print(f"saved violin input summary: {out_path}")


def _nice_step(max_val: float, target_ticks: int = 6) -> float:
    if max_val <= 0:
        return 1.0
    raw = max_val / float(target_ticks)
    magnitude = 10 ** int(np.floor(np.log10(raw)))
    residual = raw / magnitude
    if residual <= 1:
        nice = 1
    elif residual <= 2:
        nice = 2
    elif residual <= 5:
        nice = 5
    else:
        nice = 10
    return nice * magnitude


def _token_formatter(x, pos):
    if x >= 1_000_000:
        return f"{x / 1_000_000:.1f}M"
    if x >= 1000:
        return f"{int(x // 1000)}k"
    return str(int(x))


def load_projects(
    details_csv: Path,
) -> Tuple[List[Tuple[str, str, str]], Dict[Tuple[str, str], str]]:
    present: Dict[str, set] = defaultdict(set)

    with details_csv.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        for row in reader:
            project_dir = infer_project_dir(row.get("file_path") or "")
            if not project_dir:
                continue
            arch = infer_architecture(project_dir)
            base_task = infer_base_task(project_dir)
            if not base_task:
                continue

            model = (row.get("model") or "").strip()
            if model and model not in MODEL_ORDER:
                continue

            total_raw = row.get("total_tokens")
            if total_raw is None or total_raw == "":
                continue
            try:
                float(total_raw)
            except ValueError:
                continue

            present[base_task].add(arch)

    projects: List[Tuple[str, str, str]] = []
    project_map: Dict[Tuple[str, str], str] = {}
    for base_task in sorted(present.keys()):
        for arch in ARCH_ORDER:
            if arch not in present[base_task]:
                continue
            name = make_project_name(base_task, arch)
            project_map[(base_task, arch)] = name
            projects.append((base_task, arch, name))

    return projects, project_map


def classify_status(status_raw: str, with_retry_raw: str) -> str:
    s = (status_raw or "").strip().lower()
    w = (with_retry_raw or "").strip().lower()
    if s == "success" and w == "false":
        return "success_no_retry"
    if s == "success" and w == "true":
        return "success_with_retry"
    return "failed"


def load_total_tokens(
    details_csv: Path, project_map: Dict[Tuple[str, str], str]
) -> Dict[str, Dict[str, Dict[str, List[float]]]]:
    data: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict(
        lambda: defaultdict(lambda: defaultdict(list))
    )

    with details_csv.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        for row in reader:
            project_dir = infer_project_dir(row.get("file_path") or "")
            if not project_dir:
                continue
            task = infer_base_task(project_dir)
            arch = infer_architecture(project_dir)
            key = (task, arch)
            project_name = project_map.get(key) or make_project_name(task, arch)
            if not project_name:
                continue

            model = (row.get("model") or "").strip()
            if model not in MODEL_ORDER:
                continue

            status_group = classify_status(row.get("status"), row.get("with_retry"))

            total_raw = row.get("total_tokens")
            if total_raw is None or total_raw == "":
                continue
            try:
                total_val = float(total_raw)
            except ValueError:
                continue

            data[project_name][status_group][model].append(total_val)

    return data


def load_all_token_data(
    details_csv: Path, project_map: Dict[Tuple[str, str], str]
) -> Tuple[
    Dict[str, Dict[str, Dict[str, List[float]]]],
    Dict[str, Dict[str, Dict[str, List[float]]]],
    Dict[str, List[float]],
]:
    """
    Load token statistics with two views:
    - project_data: keyed by project name (task-architecture) -> status -> model -> list of totals
    - arch_model_data: keyed by task -> architecture -> model -> list of totals (across all statuses)
    - overall_status_values: keyed by status -> all token totals
    """
    project_data: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict(
        lambda: defaultdict(lambda: defaultdict(list))
    )
    arch_model_data: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict(
        lambda: defaultdict(lambda: defaultdict(list))
    )
    overall_status_values: Dict[str, List[float]] = defaultdict(list)

    with details_csv.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        for row in reader:
            project_dir = infer_project_dir(row.get("file_path") or "")
            if not project_dir:
                continue

            task = infer_base_task(project_dir)
            arch = infer_architecture(project_dir)
            key = (task, arch)
            project_name = project_map.get(key) or make_project_name(task, arch)
            if not project_name:
                continue

            model = (row.get("model") or "").strip()
            if model not in MODEL_ORDER:
                continue

            status_group = classify_status(row.get("status"), row.get("with_retry"))

            total_raw = row.get("total_tokens")
            if total_raw is None or total_raw == "":
                continue
            try:
                total_val = float(total_raw)
            except ValueError:
                continue

            project_data[project_name][status_group][model].append(total_val)
            arch_model_data[task][arch][model].append(total_val)
            overall_status_values[status_group].append(total_val)

    return project_data, arch_model_data, overall_status_values


def summarize_values(values: List[float]) -> Dict[str, float]:
    if not values:
        return {}
    arr = np.asarray(values, dtype=float)
    return {
        "count": int(arr.size),
        "mean": float(np.mean(arr)),
    }


def _fmt_number(val: float) -> str:
    return f"{val:,.0f}"


def _fmt_mean(stats: Dict[str, float]) -> str:
    if not stats:
        return "-"
    return _fmt_number(stats.get("mean", 0.0))


def _safe_mean(values: List[float]) -> float:
    if not values:
        return None  # type: ignore[return-value]
    return float(np.mean(np.asarray(values, dtype=float)))


def _fmt_mean_val(val: float) -> str:
    if val is None:
        return "-"
    return _fmt_number(val)


def _fmt_delta(new_val: float, old_val: float) -> str:
    if new_val is None or old_val is None:
        return "-"
    diff = new_val - old_val
    pct_str = "n/a" if old_val == 0 else f"{(diff / old_val) * 100:.1f}%"
    sign = "+" if diff >= 0 else ""
    return f"{sign}{_fmt_number(diff)} ({pct_str})"


def generate_project_stats_md(
    projects: List[Tuple[str, str, str]],
    project_data: Dict[str, Dict[str, Dict[str, List[float]]]],
    overall_status_values: Dict[str, List[float]],
    out_dir: Path,
) -> None:
    def _base_task_name(task: str) -> str:
        suffixes = ("-H_A2A", "-H-A2A", "-MCP", "-A2A")
        for suffix in suffixes:
            if task.endswith(suffix):
                return task[: -len(suffix)]
        return task

    def build_series_data() -> Dict[str, Dict[str, Dict[str, List[float]]]]:
        series: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict(
            lambda: defaultdict(lambda: defaultdict(list))
        )
        for task, arch, name in projects:
            base_task = _base_task_name(task)
            pdata = project_data.get(name, {})
            for status in STATUS_ORDER:
                by_model = pdata.get(status, {})
                for model, vals in by_model.items():
                    series[base_task][status][model].extend(vals)
        return series

    def append_status_table(
        lines: List[str],
        by_status: Dict[str, Dict[str, List[float]]],
        statuses: List[str],
    ) -> None:
        for status in statuses:
            by_model = by_status.get(status, {})
            if not by_model:
                continue
            lines.append("")
            lines.append(f"### {STATUS_TITLES.get(status, status)}")
            lines.append("")
            lines.append("| Model | n | Mean |")
            lines.append("| --- | --- | --- |")
            for model in MODEL_ORDER:
                vals = by_model.get(model, [])
                stats = summarize_values(vals)
                mean = _fmt_mean(stats)
                lines.append(
                    f"| {MODEL_LABELS.get(model, model)} | {stats.get('count', 0)} | {mean} |"
                )

    def append_status_comparison(
        lines: List[str],
        label: str,
        by_status: Dict[str, Dict[str, List[float]]],
        base_status: str,
        comp_status: str,
    ) -> None:
        lines.append("")
        lines.append(label)
        lines.append("")
        lines.append(
            f"| Model | {STATUS_TITLES[base_status]} mean | {STATUS_TITLES[comp_status]} mean | Δ vs {STATUS_TITLES[base_status]} |"
        )
        lines.append("| --- | --- | --- | --- |")
        for model in MODEL_ORDER:
            base_mean = _safe_mean(by_status.get(base_status, {}).get(model, []))
            comp_mean = _safe_mean(by_status.get(comp_status, {}).get(model, []))
            lines.append(
                "| "
                + " | ".join(
                    [
                        MODEL_LABELS.get(model, model),
                        _fmt_mean_val(base_mean),
                        _fmt_mean_val(comp_mean),
                        _fmt_delta(comp_mean, base_mean),
                    ]
                )
                + " |"
            )

    def build_report(
        title: str,
        base_status: str,
        comp_status: str,
        filename: str,
    ) -> None:
        statuses = [base_status, comp_status]
        series_data = build_series_data()
        lines: List[str] = []
        lines.append(f"# Project token statistics - {title}")
        lines.append("")
        lines.append("## Overall status token summary")
        lines.append("")
        lines.append("| Status | n | Mean |")
        lines.append("| --- | --- | --- |")
        for status in statuses:
            stats = summarize_values(overall_status_values.get(status, []))
            mean = _fmt_mean(stats)
            lines.append(
                f"| {STATUS_TITLES.get(status, status)} | {stats.get('count', 0)} | {mean} |"
            )

        for task, arch, name in projects:
            pdata = project_data.get(name, {})
            lines.append("")
            lines.append(f"## {name}")
            if not pdata:
                lines.append("")
                lines.append("> No token data found.")
                continue
            append_status_table(lines, pdata, statuses)
            append_status_comparison(
                lines,
                f"### {STATUS_TITLES[base_status]} vs {STATUS_TITLES[comp_status]} (mean, abs & %)",
                pdata,
                base_status,
                comp_status,
            )

        # Series-level aggregation by task prefix
        lines.append("")
        lines.append("## Series aggregates (by task prefix)")
        for task in sorted(series_data.keys()):
            sdata = series_data[task]
            lines.append("")
            lines.append(f"### {task} (aggregated across variants)")
            append_status_table(lines, sdata, statuses)
            append_status_comparison(
                lines,
                f"#### {STATUS_TITLES[base_status]} vs {STATUS_TITLES[comp_status]} (mean, abs & %)",
                sdata,
                base_status,
                comp_status,
            )

        out_path = out_dir / filename
        out_dir.mkdir(parents=True, exist_ok=True)
        out_path.write_text("\n".join(lines), encoding="utf-8")
        print(f"saved markdown: {out_path}")

    build_report(
        "Pass (no retry) vs Pass (with retry)",
        "success_no_retry",
        "success_with_retry",
        "project_token_stats_pass_vs_retry.md",
    )
    build_report(
        "Pass (no retry) vs Failure",
        "success_no_retry",
        "failed",
        "project_token_stats_pass_vs_failure.md",
    )


def generate_architecture_deltas_md(
    projects: List[Tuple[str, str, str]],
    arch_model_data: Dict[str, Dict[str, Dict[str, List[float]]]],
    out_dir: Path,
) -> None:
    def write_report(title: str, chain: List[str], filename: str) -> None:
        lines: List[str] = []
        lines.append("# Token shifts across architectures")
        lines.append("")
        lines.append(f"Series: **{title}**")
        lines.append("")
        lines.append(
            "Each table shows the absolute change (Δ) and the relative percentage change of the mean total tokens."
        )

        def render_pair(task_arch_data: Dict[str, Dict[str, List[float]]]) -> None:
            arch_display = {
                "Unknown": "Pure CrewAI",
                "MCP": "MCP",
                "A2A": "A2A",
                "A2A_mix": "H-A2A",
            }

            header = f"| Model | {arch_display[chain[0]]} | {arch_display[chain[1]]} | Δ {arch_display[chain[1]]}-{arch_display[chain[0]]} |"
            sep = "| --- | --- | --- | --- |"

            lines.append("")
            lines.append(header)
            lines.append(sep)

            for model in MODEL_ORDER:
                left_vals = task_arch_data.get(chain[0], {}).get(model, [])
                right_vals = task_arch_data.get(chain[1], {}).get(model, [])
                left_mean = float(np.mean(left_vals)) if left_vals else None
                right_mean = float(np.mean(right_vals)) if right_vals else None
                row = [
                    MODEL_LABELS.get(model, model),
                    "-" if left_mean is None else _fmt_number(left_mean),
                    "-" if right_mean is None else _fmt_number(right_mean),
                    _fmt_delta(right_mean, left_mean),
                ]
                lines.append("| " + " | ".join(row) + " |")

            lines.append("")
            lines.append("Project-level average (all models combined)")
            lines.append("")
            lines.append(
                f"| Metric | {arch_display[chain[0]]} | {arch_display[chain[1]]} | Δ {arch_display[chain[1]]}-{arch_display[chain[0]]} |"
            )
            lines.append("| --- | --- | --- | --- |")

            def _mean_all(arch: str) -> float:
                combined: List[float] = []
                for vals in task_arch_data.get(arch, {}).values():
                    combined.extend(vals)
                return float(np.mean(combined)) if combined else None

            left_all = _mean_all(chain[0])
            right_all = _mean_all(chain[1])
            lines.append(
                "| "
                + " | ".join(
                    [
                        "Avg tokens (all models)",
                        "-" if left_all is None else _fmt_number(left_all),
                        "-" if right_all is None else _fmt_number(right_all),
                        _fmt_delta(right_all, left_all),
                    ]
                )
                + " |"
            )

        task_set = {t for t, _, _ in projects}
        for task in sorted(task_set):
            task_arch_data = arch_model_data.get(task, {})
            arches = set(task_arch_data.keys())
            if not task_arch_data:
                continue
            if not set(chain).issubset(arches):
                continue

            lines.append("")
            lines.append(f"## {task}")
            render_pair(task_arch_data)

        out_path = out_dir / filename
        out_dir.mkdir(parents=True, exist_ok=True)
        out_path.write_text("\n".join(lines), encoding="utf-8")
        print(f"saved markdown: {out_path}")

    def write_a2a_to_h_a2a_report(filename: str) -> None:
        lines: List[str] = []
        lines.append("# Token shifts across architectures")
        lines.append("")
        lines.append("Series: **A2A → H-A2A**")
        lines.append("")
        lines.append(
            "Each table shows the absolute change (Δ) and the relative percentage change of the mean total tokens."
        )

        def render_pair(
            task_base: str,
            left_arch_data: Dict[str, Dict[str, List[float]]],
            right_arch_data: Dict[str, Dict[str, List[float]]],
        ) -> None:
            right_label = "H-A2A"
            header = f"| Model | A2A | {right_label} | Δ {right_label}-A2A |"
            sep = "| --- | --- | --- | --- |"
            lines.append("")
            lines.append(header)
            lines.append(sep)

            for model in MODEL_ORDER:
                left_vals = left_arch_data.get("A2A", {}).get(model, [])
                right_vals: List[float] = []
                for arch_vals in right_arch_data.values():
                    right_vals.extend(arch_vals.get(model, []))
                left_mean = float(np.mean(left_vals)) if left_vals else None
                right_mean = float(np.mean(right_vals)) if right_vals else None
                row = [
                    MODEL_LABELS.get(model, model),
                    "-" if left_mean is None else _fmt_number(left_mean),
                    "-" if right_mean is None else _fmt_number(right_mean),
                    _fmt_delta(right_mean, left_mean),
                ]
                lines.append("| " + " | ".join(row) + " |")

            lines.append("")
            lines.append("Project-level average (all models combined)")
            lines.append("")
            lines.append(f"| Metric | A2A | {right_label} | Δ {right_label}-A2A |")
            lines.append("| --- | --- | --- | --- |")

            def _mean_all(
                arch_data: Dict[str, Dict[str, List[float]]], arch: str
            ) -> float:
                combined: List[float] = []
                for vals in arch_data.get(arch, {}).values():
                    combined.extend(vals)
                return float(np.mean(combined)) if combined else None

            left_all = _mean_all(left_arch_data, "A2A")
            right_combined: List[float] = []
            for arch_vals in right_arch_data.values():
                for vals in arch_vals.values():
                    right_combined.extend(vals)
            right_all = float(np.mean(right_combined)) if right_combined else None
            lines.append(
                "| "
                + " | ".join(
                    [
                        "Avg tokens (all models)",
                        "-" if left_all is None else _fmt_number(left_all),
                        "-" if right_all is None else _fmt_number(right_all),
                        _fmt_delta(right_all, left_all),
                    ]
                )
                + " |"
            )

        task_set = sorted({t for t, _, _ in projects})
        for task in task_set:
            task_arch_data = arch_model_data.get(task, {})
            if not task_arch_data:
                continue
            if "A2A" not in task_arch_data or "A2A_mix" not in task_arch_data:
                continue

            left_arch_data = {"A2A": task_arch_data.get("A2A", {})}
            right_arch_data = {"A2A_mix": task_arch_data.get("A2A_mix", {})}

            lines.append("")
            lines.append(f"## {task}")

            render_pair(task, left_arch_data, right_arch_data)

        out_path = out_dir / filename
        out_dir.mkdir(parents=True, exist_ok=True)
        out_path.write_text("\n".join(lines), encoding="utf-8")
        print(f"saved markdown: {out_path}")

    write_report(
        "Pure CrewAI → MCP",
        ["Unknown", "MCP"],
        "architecture_token_deltas_crewai_to_mcp.md",
    )
    write_report("MCP → A2A", ["MCP", "A2A"], "architecture_token_deltas_mcp_to_a2a.md")
    write_a2a_to_h_a2a_report("architecture_token_deltas_a2a_to_h-a2a.md")


def generate_project_model_distribution_md(
    projects: List[Tuple[str, str, str]],
    project_data: Dict[str, Dict[str, Dict[str, List[float]]]],
    out_dir: Path,
) -> None:
    lines: List[str] = []
    lines.append("# Model token distribution per project")
    lines.append("")
    lines.append(
        "Per-project, per-model total token usage with breakdown by execution outcome. "
        "Only the mean total tokens are reported. Baseline vs maximum is computed from the overall mean aggregated across all three statuses."
    )

    def _base_task_name(task: str) -> str:
        suffixes = ("-H_A2A", "-H-A2A", "-MCP", "-A2A")
        for suffix in suffixes:
            if task.endswith(suffix):
                return task[: -len(suffix)]
        return task

    # Collect overall and series data
    overall_raw: Dict[str, List[float]] = defaultdict(list)
    series_raw: Dict[str, Dict[str, List[float]]] = defaultdict(
        lambda: defaultdict(list)
    )

    for task, arch, name in projects:
        pdata = project_data.get(name, {})
        base_task = _base_task_name(task)
        for model in MODEL_ORDER:
            for status in STATUS_ORDER:
                vals = pdata.get(status, {}).get(model, [])
                overall_raw[model].extend(vals)
                series_raw[base_task][model].extend(vals)

    def append_dist_section(
        lines: List[str],
        title: str,
        raw_data: Dict[str, List[float]],
        level_label: str = "###",
    ) -> Dict[str, float]:
        lines.append("")
        lines.append(f"{level_label} {title}")
        lines.append("| Model | n | Mean |")
        lines.append("| --- | --- | --- |")
        means: Dict[str, float] = {}
        for model in MODEL_ORDER:
            vals = raw_data.get(model, [])
            stats = summarize_values(vals)
            if stats:
                means[model] = stats["mean"]
            mean_str = _fmt_mean(stats)
            lines.append(
                f"| {MODEL_LABELS.get(model, model)} | {stats.get('count', 0)} | {mean_str} |"
            )

        lines.append("")
        lines.append(f"{level_label} Baseline vs maximum ({title})")
        if means:
            min_model = min(means.items(), key=lambda kv: kv[1])
            max_model = max(means.items(), key=lambda kv: kv[1])
            diff = max_model[1] - min_model[1]
            ratio = (
                "n/a" if min_model[1] == 0 else f"{(diff / min_model[1]) * 100:.1f}%"
            )
            lines.append(
                f"- Baseline (lowest mean): {MODEL_LABELS.get(min_model[0], min_model[0])} "
                f"= {_fmt_number(min_model[1])} tokens"
            )
            lines.append(
                f"- Maximum (highest mean): {MODEL_LABELS.get(max_model[0], max_model[0])} "
                f"= {_fmt_number(max_model[1])} tokens"
            )
            lines.append(f"- Delta: {_fmt_number(diff)} ({ratio})")
        else:
            lines.append("- No data to compare.")
        return means

    # 1. Global Overall Summary
    lines.append("")
    lines.append("## Global Summary (All Projects Combined)")
    append_dist_section(lines, "Overall per-model total tokens", overall_raw)

    # 2. Series Aggregates
    lines.append("")
    lines.append("## Series Aggregates (Aggregated by Base Task)")
    for base_task in sorted(series_raw.keys()):
        lines.append("")
        lines.append(f"### Series: {base_task}")
        append_dist_section(
            lines, f"Aggregated tokens for {base_task}", series_raw[base_task], "####"
        )

    # 3. Individual Projects
    lines.append("")
    lines.append("## Individual Project Details")
    for task, arch, name in projects:
        pdata = project_data.get(name, {})
        lines.append("")
        lines.append(f"### {name}")
        if not pdata:
            lines.append("")
            lines.append("> No token data found.")
            continue

        project_raw: Dict[str, List[float]] = {}
        for model in MODEL_ORDER:
            combined: List[float] = []
            for status in STATUS_ORDER:
                combined.extend(pdata.get(status, {}).get(model, []))
            project_raw[model] = combined

        append_dist_section(lines, "Per-model total tokens", project_raw, "####")

    out_path = out_dir / "project_model_distribution.md"
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path.write_text("\n".join(lines), encoding="utf-8")
    print(f"saved markdown: {out_path}")


def plot_violin_for_project(
    project_name: str,
    project_data: Dict[str, Dict[str, List[float]]],
    out_dir: Path,
    global_max: float,
) -> None:
    if not HAS_MATPLOTLIB:
        print("matplotlib not available; skip violin plots")
        return

    any_values = False
    for status in STATUS_ORDER:
        by_model = project_data.get(status, {})
        for m in MODEL_ORDER:
            vals = by_model.get(m)
            if vals:
                any_values = True

    if not any_values or global_max <= 0.0:
        print(f"no total_tokens for project {project_name}, skip")
        return

    fig, axes = plt.subplots(1, len(STATUS_ORDER), figsize=(10, 6), sharey=True)
    if len(STATUS_ORDER) == 1:
        axes = [axes]

    y_max = global_max * 1.02
    target_ticks = 6
    while True:
        step = _nice_step(y_max, target_ticks=target_ticks)
        y_max_rounded = float(np.ceil(y_max / step) * step)
        if y_max_rounded <= y_max * 1.08 or target_ticks >= 12:
            break
        target_ticks += 2

    for idx_status, status in enumerate(STATUS_ORDER):
        ax = axes[idx_status]
        by_model = project_data.get(status, {})

        for i, model in enumerate(MODEL_ORDER, start=1):
            vals = by_model.get(model)
            if not vals:
                continue
            v_max = float(max(vals))
            parts = ax.violinplot(
                vals,
                positions=[i],
                widths=0.8,
                showmeans=False,
                showextrema=False,
                showmedians=False,
            )
            for pc in parts["bodies"]:
                pc.set_facecolor(MODEL_COLORS.get(model, "black"))
                pc.set_edgecolor("black")
                pc.set_alpha(0.7)

            median_val = float(np.median(vals))
            ax.hlines(
                median_val,
                i - 0.3,
                i + 0.3,
                colors="black",
                linewidth=1.0,
            )

            if v_max > y_max_rounded:
                y_pos = y_max_rounded * 0.985
                ax.plot([i], [y_pos], marker="^", color="black", markersize=4)
                ax.text(
                    i,
                    y_pos,
                    f">{_token_formatter(v_max, 0)}",
                    ha="center",
                    va="top",
                    fontsize=10,
                )

        ax.set_title(STATUS_TITLES.get(status, status), fontsize=24, fontweight="bold")
        ax.set_xticks(range(1, len(MODEL_ORDER) + 1))
        ax.set_xticklabels([])
        ax.set_xlim(0.5, len(MODEL_ORDER) + 0.5)
        ax.set_ylim(0, y_max_rounded)
        yticks = np.arange(0, y_max_rounded + step * 0.5, step)
        ax.set_yticks(yticks)
        ax.yaxis.set_major_formatter(FuncFormatter(_token_formatter))
        ax.grid(axis="y", linestyle="-", linewidth=0.5, alpha=0.3)
        ax.tick_params(axis="y", labelsize=22)
        ax.tick_params(axis="x", labelsize=16)
        for lbl in ax.get_yticklabels():
            lbl.set_fontweight("bold")

        if idx_status == 0:
            ax.set_ylabel("")

    fig.subplots_adjust(left=0.07, right=0.98, bottom=0.10, top=0.98, wspace=0.03)

    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / f"{project_name}_total_tokens_violin.pdf"
    fig.savefig(out_path, format="pdf", dpi=300, bbox_inches="tight", pad_inches=0.02)
    plt.close(fig)
    print(f"saved violin figure: {out_path}")


def main() -> None:
    part1_dir = Path(__file__).resolve().parent
    details_csv = part1_dir / "task_token_statistics-DETAILS.csv"
    if not details_csv.exists():
        details_csv = (
            part1_dir / "performance_reports" / "task_token_statistics-DETAILS.csv"
        )
    out_dir = part1_dir / "Violin"

    projects, project_map = load_projects(details_csv)

    project_data, arch_model_data, overall_status_values = load_all_token_data(
        details_csv, project_map
    )

    export_violin_input_summary(projects, project_data, out_dir)

    # Compute a shared y-axis maximum per task so that all architectures
    # of the same task use the same vertical scale in their violin plots.
    task_max_values: Dict[str, float] = {}
    task_values: Dict[str, List[float]] = defaultdict(list)
    for task, arch, name in projects:
        pdata = project_data.get(name, {})
        for status in STATUS_ORDER:
            by_model = pdata.get(status, {})
            for m in MODEL_ORDER:
                vals = by_model.get(m)
                if vals:
                    task_values[task].extend(vals)

    for task, vals in task_values.items():
        if not vals:
            continue
        arr = np.asarray(vals, dtype=float)
        abs_max = float(np.max(arr))
        if abs_max <= 0.0:
            continue
        task_max_values[task] = abs_max

    for task, arch, name in projects:
        pdata = project_data.get(name, {})
        global_max = task_max_values.get(task, 0.0)
        try:
            plot_violin_for_project(name, pdata, out_dir, global_max)
        except Exception as exc:
            print(f"error plotting project {name}: {exc}")

    # Generate markdown summaries
    generate_project_stats_md(projects, project_data, overall_status_values, out_dir)
    generate_architecture_deltas_md(projects, arch_model_data, out_dir)
    generate_project_model_distribution_md(projects, project_data, out_dir)


if __name__ == "__main__":
    main()