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
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
# -*- coding: utf-8 -*-
"""
Plot evaluation result charts
1. Joint success rate by difficulty (LaTeX table)
2. Joint success rate by scenario (bar chart)
3. Error reason donut charts (by model and by scenario)
4. Average tokens per trajectory vs joint success rate
5. Average conversation rounds per trajectory vs joint success rate
6. Average tool calls per trajectory vs joint success rate
"""

import os
import re
import json
import math
from collections import defaultdict

import matplotlib
matplotlib.use("Agg")

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from matplotlib.offsetbox import OffsetImage, AnnotationBbox


# =========================
# Path Configuration
# =========================
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(CURRENT_DIR)

EVAL_RESULT_DIR = os.path.join(PROJECT_ROOT, "eval_result")
LOGO_DIR = os.path.join(CURRENT_DIR, "logo")
ERROR_ANALYSIS_DIR = os.path.join(PROJECT_ROOT, "error_analysis")
FIGURES_DIR = os.path.join(EVAL_RESULT_DIR, "figures")

os.makedirs(FIGURES_DIR, exist_ok=True)


def save_figure_pair(png_path, *, dpi=200, bbox_inches="tight"):
    """Save the current Matplotlib figure as both PNG and vector PDF."""
    stem, extension = os.path.splitext(png_path)
    if extension.lower() != ".png":
        raise ValueError(f"Expected a .png output path, got: {png_path}")
    plt.savefig(png_path, dpi=dpi, bbox_inches=bbox_inches)
    plt.savefig(f"{stem}.pdf", bbox_inches=bbox_inches)

# =========================
# Global Plot Configuration
# =========================
plt.rcParams["font.sans-serif"] = [
    "SimHei", "Microsoft YaHei", "Arial Unicode MS", "DejaVu Sans"
]
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams["font.size"] = 12

# =========================
# Model Configuration
# =========================
MODEL_NAMES = {
    "glm-5v-turbo": "GLM-5V-Turbo",
    "qwen3-vl-235b": "Qwen3-VL-235B",
    "qwen3.6-plus": "Qwen3.6-Plus",
    "Qwen3.5-397B-A17B": "Qwen3.5-397B",
    "gemini-3.1-pro-preview": "Gemini-3.1-Pro",
    "kimi-k2.6": "Kimi-K2.6",
    "mimo-v2.5-omni": "MiMo-V2.5-Omni",
    "doubao-seed-2-0-pro-260215": "Doubao"
}

LOGO_FILES = {
    "glm-5v-turbo": "chatglm-color.png",
    "qwen3-vl-235b": "qwen-color.png",
    "qwen3.6-plus": "qwen-color.png",
    "Qwen3.5-397B-A17B": "qwen-color.png",
    "gemini-3.1-pro-preview": "gemini-color.png",
    "kimi-k2.6": "kimi.png",
    "mimo-v2.5-omni": "xiaomimimo.png",
    "doubao-seed-2-0-pro-260215": "doubao-color.png"
}

MODEL_COLORS = {
    "glm-5v-turbo": "#A23B72",
    "qwen3-vl-235b": "#F18F01",
    "qwen3.6-plus": "#C73E1D",
    "Qwen3.5-397B-A17B": "#3B1F2B",
    "gemini-3.1-pro-preview": "#0F4C5C",
    "kimi-k2.6": "#9BC53D",
    "mimo-v2.5-omni": "#E55934",
    "doubao-seed-2-0-pro-260215": "#5BC0EB"
}

LIGHT_COLORS = {
    "glm-5v-turbo": "#E6A8D7",
    "qwen3-vl-235b": "#F9C74F",
    "qwen3.6-plus": "#FFB4A2",
    "Qwen3.5-397B-A17B": "#A89F91",
    "gemini-3.1-pro-preview": "#8DCAE0",
    "kimi-k2.6": "#C7E9B4",
    "mimo-v2.5-omni": "#FFC8A2",
    "doubao-seed-2-0-pro-260215": "#B5E2F0"
}

MODEL_ORDER = list(MODEL_NAMES.keys())

SCENARIOS = ["retail", "restaurant", "kitchen", "warehouse", "household"]
DIFFICULTIES = ["easy", "hard", "static"]


# =========================
# Utility Functions
# =========================
def safe_read_json(path):
    if not os.path.exists(path):
        return None
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception as e:
        print(f"[WARN] Failed to read JSON: {path}, error={e}")
        return None


def list_model_dirs():
    """List model directories under eval_result that contain summary.json"""
    models = []
    if not os.path.exists(EVAL_RESULT_DIR):
        return models

    for name in os.listdir(EVAL_RESULT_DIR):
        model_dir = os.path.join(EVAL_RESULT_DIR, name)
        if os.path.isdir(model_dir) and os.path.exists(os.path.join(model_dir, "summary.json")):
            models.append(name)

    # Keep only models defined in MODEL_NAMES, sorted by predefined order, extras at the end
    models = [m for m in models if m in MODEL_NAMES]
    ordered = [m for m in MODEL_ORDER if m in models]
    extras = [m for m in models if m not in ordered]
    return ordered + sorted(extras)


def get_model_summary(model_dir):
    path = os.path.join(EVAL_RESULT_DIR, model_dir, "summary.json")
    return safe_read_json(path)


def get_model_eval_files(model_dir):
    model_path = os.path.join(EVAL_RESULT_DIR, model_dir)
    if not os.path.exists(model_path):
        return []
    files = []
    for fn in os.listdir(model_path):
        if fn.endswith("_eval.json"):
            files.append(os.path.join(model_path, fn))
    return sorted(files)


def mean_or_zero(values):
    values = [v for v in values if v is not None]
    return float(np.mean(values)) if values else 0.0


def normalize_rate(x):
    """
    Some fields may be 0~1 or already 0~100.
    Normalize to percentage values.
    """
    if x is None:
        return 0.0
    try:
        x = float(x)
    except Exception:
        return 0.0

    if x <= 1.0:
        return x * 100
    return x


def is_complete_summary_item(item):
    """Exclude partial result files from every reported accuracy aggregate."""
    if item.get("error"):
        return False
    if "included_in_summary" in item:
        return bool(item["included_in_summary"])
    total = item.get("total_scenarios", 0)
    valid = item.get("valid_scenarios", 0)
    return total > 0 and valid == total


def load_logo_image(model, zoom=0.12):
    logo_file = LOGO_FILES.get(model)
    if not logo_file:
        return None
    logo_path = os.path.join(LOGO_DIR, logo_file)
    if not os.path.exists(logo_path):
        return None
    try:
        img = Image.open(logo_path).convert("RGBA")
        return OffsetImage(img, zoom=zoom)
    except Exception as e:
        print(f"[WARN] Failed to load logo: model={model}, error={e}")
        return None


# =========================
# Metric Extraction
# =========================
def get_four_rates_by_difficulty(summary):
    """
    Extract four metrics by difficulty: micro_accuracy, tool_based_success_rate, result_based_success_rate, joint_success_rate
    Only complete files are included and each file is weighted by its valid task count.
    Returns: {difficulty: {"micro": x, "tool": x, "result": x, "joint": x}}
    """
    result = {d: {"micro": 0.0, "tool": 0.0, "result": 0.0, "joint": 0.0} for d in DIFFICULTIES}
    if not summary:
        return result

    all_results = summary.get("all_results", [])
    buckets = {
        d: {"micro": [], "tool": [], "result": [], "joint": [], "weights": []}
        for d in DIFFICULTIES
    }

    for item in all_results:
        if not is_complete_summary_item(item):
            continue
        mode = item.get("mode")
        if mode in DIFFICULTIES:
            buckets[mode]["weights"].append(item.get("valid_scenarios", 0))
            buckets[mode]["micro"].append(normalize_rate(item.get("micro_accuracy", 0)))
            buckets[mode]["tool"].append(normalize_rate(item.get("tool_based_success_rate", 0)))
            buckets[mode]["result"].append(normalize_rate(item.get("result_based_success_rate", 0)))
            buckets[mode]["joint"].append(normalize_rate(item.get("joint_success_rate", 0)))

    for d in DIFFICULTIES:
        total_weight = sum(buckets[d]["weights"])
        for key in ["micro", "tool", "result", "joint"]:
            if total_weight > 0:
                result[d][key] = sum(
                    rate * weight
                    for rate, weight in zip(
                        buckets[d][key], buckets[d]["weights"]
                    )
                ) / total_weight
            else:
                result[d][key] = mean_or_zero(buckets[d][key])
    return result


def get_joint_success_rate_by_difficulty(summary):
    result = {d: 0.0 for d in DIFFICULTIES}
    if not summary:
        return result

    rates = get_four_rates_by_difficulty(summary)
    for d in DIFFICULTIES:
        result[d] = rates[d]["joint"]
    return result


def get_joint_success_rate_by_scenario(summary):
    result = {s: 0.0 for s in SCENARIOS}
    if not summary:
        return result

    all_results = summary.get("all_results", [])
    bucket = defaultdict(list)

    for item in all_results:
        if not is_complete_summary_item(item):
            continue
        scenario = item.get("scenario")
        if scenario in SCENARIOS:
            bucket[scenario].append((
                normalize_rate(item.get("joint_success_rate", 0)),
                item.get("valid_scenarios", 0),
            ))

    for s in SCENARIOS:
        total_weight = sum(weight for _, weight in bucket[s])
        if total_weight > 0:
            result[s] = sum(
                rate * weight for rate, weight in bucket[s]
            ) / total_weight
        else:
            result[s] = mean_or_zero([rate for rate, _ in bucket[s]])
    return result


def get_overall_joint_success_rate(summary):
    if not summary:
        return 0.0
    complete_items = [
        item for item in summary.get("all_results", [])
        if is_complete_summary_item(item)
    ]
    total = sum(item.get("valid_scenarios", 0) for item in complete_items)
    if total <= 0:
        return 0.0
    return sum(
        normalize_rate(item.get("joint_success_rate", 0))
        * item.get("valid_scenarios", 0)
        for item in complete_items
    ) / total


def get_metrics_from_summary(summary):
    """
    Extract metrics from summary.json summary field
    Returns: avg_tokens, avg_rounds, avg_tool_calls
    """
    if not summary:
        return {"avg_tokens": 0.0, "avg_rounds": 0.0, "avg_tool_calls": 0.0}

    complete_items = [
        item for item in summary.get("all_results", [])
        if is_complete_summary_item(item)
    ]
    if summary.get("all_results"):
        total = sum(item.get("valid_scenarios", 0) for item in complete_items)
        if total <= 0:
            return {"avg_tokens": 0.0, "avg_rounds": 0.0, "avg_tool_calls": 0.0}

        def weighted(key):
            return sum(
                (item.get(key, 0) or 0) * item.get("valid_scenarios", 0)
                for item in complete_items
            ) / total

        return {
            "avg_tokens": float(weighted("avg_input_tokens") + weighted("avg_output_tokens")),
            "avg_rounds": float(weighted("avg_rounds_count")),
            "avg_tool_calls": float(weighted("avg_tool_calls_count")),
        }

    s = summary.get("summary", {})

    # Token consumption = input + output
    avg_input_tokens = s.get("avg_input_tokens", 0) or 0
    avg_output_tokens = s.get("avg_output_tokens", 0) or 0
    avg_tokens = avg_input_tokens + avg_output_tokens

    # Conversation rounds
    avg_rounds = s.get("avg_rounds_count", 0) or 0

    # Tool call count
    avg_tool_calls = s.get("avg_tool_calls_count", 0) or 0

    return {
        "avg_tokens": float(avg_tokens),
        "avg_rounds": float(avg_rounds),
        "avg_tool_calls": float(avg_tool_calls)
    }


# =========================
# Axis Model Logo Labels
# =========================
def add_model_logos_below_axis(ax, models, y_offset_axes=-0.16, zoom=0.065, fontsize=10):
    """
    Add logo + model name below x-axis
    Use coordinate transform for stable layout
    """
    xticks = ax.get_xticks()
    if len(xticks) < len(models):
        return

    for i, model in enumerate(models):
        x = xticks[i]

        # logo
        img = load_logo_image(model, zoom=zoom)
        if img is not None:
            ab = AnnotationBbox(
                img,
                (x, y_offset_axes + 0.035),
                xycoords=ax.get_xaxis_transform(),
                frameon=False,
                box_alignment=(0.5, 0.5),
                pad=0
            )
            ax.add_artist(ab)

        # text
        ax.text(
            x, y_offset_axes - 0.02,
            MODEL_NAMES.get(model, model),
            transform=ax.get_xaxis_transform(),
            ha="center", va="top",
            fontsize=fontsize, fontweight="bold"
        )

    ax.set_xticklabels([])
    plt.subplots_adjust(bottom=0.22)


# =========================
# Chart 1: LaTeX Table by Difficulty
# =========================
def _find_best_and_second(values):
    """Return (best_idx, second_idx), best is max value index, second is second-max value index"""
    if not values:
        return None, None
    sorted_indices = sorted(range(len(values)), key=lambda i: values[i], reverse=True)
    best = sorted_indices[0] if len(sorted_indices) > 0 else None
    second = sorted_indices[1] if len(sorted_indices) > 1 else None
    return best, second


def _fmt_val(val, is_best, is_second):
    s = f"{val:.2f}"
    if is_best:
        return f"\\textbf{{{s}}}"
    if is_second:
        return f"\\underline{{{s}}}"
    return s


def plot_chart1_joint_success_by_difficulty(models):
    print("Generating Table 1: Four accuracy metrics by difficulty (LaTeX)")

    # Collect four metrics per model per difficulty
    model_data = {}
    for model in models:
        summary = get_model_summary(model)
        model_data[model] = get_four_rates_by_difficulty(summary)

    metrics = ["micro", "tool", "result", "joint"]
    metric_labels = ["Micro", "Tool", "Result", "Joint"]

    # Pre-compute best / second best per column
    col_best = {}   # (difficulty, metric) -> best_model_idx
    col_second = {}
    for d in DIFFICULTIES:
        for m in metrics:
            vals = [model_data[model][d][m] for model in models]
            best, second = _find_best_and_second(vals)
            col_best[(d, m)] = best
            col_second[(d, m)] = second

    # Build LaTeX
    lines = []
    lines.append(r"\begin{table*}[t]")
    lines.append(r"\centering")
    lines.append(r"% \caption{Performance by Difficulty on EgoBench.}")
    lines.append(r"\label{tab:difficulty_results}")
    lines.append(r"\footnotesize")
    lines.append(r"\setlength{\tabcolsep}{4pt}")
    lines.append(r"\begin{tabular}{clcccccccccccc}")
    lines.append(r"\toprule")
    lines.append(r" & & \multicolumn{4}{c}{\textbf{Easy}} & \multicolumn{4}{c}{\textbf{Hard}} & \multicolumn{4}{c}{\textbf{Static}} \\")
    lines.append(r"\cmidrule(lr){3-6}\cmidrule(lr){7-10}\cmidrule(lr){11-14}")
    lines.append(r" & \textbf{Model} & \textbf{Micro} & \textbf{Tool} & \textbf{Result} & \textbf{Joint} & \textbf{Micro} & \textbf{Tool} & \textbf{Result} & \textbf{Joint} & \textbf{Micro} & \textbf{Tool} & \textbf{Result} & \textbf{Joint} \\")
    lines.append(r"\midrule")

    for i, model in enumerate(models):
        logo_file = LOGO_FILES.get(model, "")
        logo_name = logo_file.replace(".png", "") if logo_file else ""
        display_name = MODEL_NAMES.get(model, model)

        row_vals = []
        for d in DIFFICULTIES:
            for j, m in enumerate(metrics):
                val = model_data[model][d][m]
                is_best = (col_best[(d, m)] == i)
                is_second = (col_second[(d, m)] == i)
                row_vals.append(_fmt_val(val, is_best, is_second))

        logo_part = f"\\includegraphics[height=0.3cm]{{logo/{logo_name}}}" if logo_name else ""
        line = f"{logo_part} & {display_name} & " + " & ".join(row_vals) + r" \\"
        lines.append(line)

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}")
    lines.append(r"\end{table*}")

    latex_str = "\n".join(lines)

    save_path = os.path.join(FIGURES_DIR, "table1_difficulty_results.tex")
    with open(save_path, "w", encoding="utf-8") as f:
        f.write(latex_str)
    print(f"LaTeX table saved to: {save_path}")


# =========================
# Chart 2: Bar Chart by Scenario
# =========================
def plot_chart2_joint_success_by_scenario(models):
    print("Plotting Chart 2: Joint success rate by scenario (bar chart)")

    x = np.arange(len(models))
    width = 0.8 / len(SCENARIOS)

    scenario_data = {s: [] for s in SCENARIOS}
    for model in models:
        summary = get_model_summary(model)
        rates = get_joint_success_rate_by_scenario(summary)
        for s in SCENARIOS:
            scenario_data[s].append(rates[s])

    fig, ax = plt.subplots(figsize=(15, 8))

    colors = {
        "retail": "#2E86AB",
        "restaurant": "#E55934",
        "kitchen": "#9BC53D",
        "warehouse": "#7B61A8",
        "household": "#F2B134",
    }

    for idx, scenario in enumerate(SCENARIOS):
        ax.bar(
            x + (idx - (len(SCENARIOS) - 1) / 2) * width,
            scenario_data[scenario],
            width=width,
            label=scenario.capitalize(),
            color=colors[scenario],
            edgecolor="white",
            linewidth=1.2
        )

    ax.set_ylabel("Joint Success Rate (%)", fontsize=19)
    # No title
    ax.set_xticks(x)
    ax.grid(True, axis="y", linestyle="--", alpha=0.3)
    ax.tick_params(axis="y", labelsize=16)
    ax.legend(fontsize=15)

    ymax = max([max(v) if v else 0 for v in scenario_data.values()] + [5])
    ax.set_ylim(0, min(100, ymax + 10))

    add_model_logos_below_axis(ax, models, y_offset_axes=-0.14, zoom=0.06, fontsize=10)

    save_path = os.path.join(FIGURES_DIR, "chart2_joint_success_by_scenario.png")
    save_figure_pair(save_path)
    plt.close()


# =========================
# Error Analysis Data Loading
# =========================
PIE_LABELS = ["Structural Non-Compliance", "Multimodal Perceptual Misinterpretations", "Hallucination", "Logical Fallacies", "Risky Operations", "Correct"]
PIE_KEYS = ["syntax", "multimodal", "hallucination", "logic", "over_action", "correct"]

# Error colors: red-orange-yellow gradient; Correct: green
PIE_COLORS = ["#C0392B", "#E74C3C", "#E67E22", "#F39C12", "#F1C40F", "#27AE60"]


def _compute_pie_proportions(counts):
    """
    Calculate proportions (percentages) from error type counts, summing to 100%.
    Memory errors are merged into Logic.

    counts: {"total": N, "syntax_error": n, ...}
    Returns: {"syntax": %, "multimodal": %, "hallucination": %, "logic": %, "over_action": %, "correct": %}
    """
    total = counts.get("total", 0)
    if total == 0:
        return {}

    syntax = counts.get("syntax_error", 0)
    multimodal = counts.get("multimodal_error", 0)
    hallucination = counts.get("hallucination_error", 0)
    logic = counts.get("logic_error", 0) + counts.get("memory_error", 0)  # memory merged into logic
    over_op = counts.get("over_operation_error", 0)
    correct = counts.get("correct", 0)

    props = {}
    props["syntax"] = syntax / total * 100
    props["multimodal"] = multimodal / total * 100
    props["hallucination"] = hallucination / total * 100
    props["logic"] = logic / total * 100
    props["over_action"] = over_op / total * 100
    props["correct"] = correct / total * 100
    return props


def load_all_error_analysis():
    """
    Read detailed results from error_analysis/all_scenarios_error_analysis_details.json,
    aggregate error counts by scenario and model, then calculate pie chart proportions.

    Returns:
    (per_scenario, overall)
      per_scenario: {scenario: {model: {"syntax": %, ...}}}
      overall:      {model: {"syntax": %, ...}}
    """
    per_scenario = {s: defaultdict(dict) for s in SCENARIOS}
    overall_counts = {}

    json_path = os.path.join(ERROR_ANALYSIS_DIR, "all_scenarios_error_analysis_details.json")
    if not os.path.exists(json_path):
        print(f"[WARN] Error analysis JSON not found: {json_path}")
        return per_scenario, {}

    details = safe_read_json(json_path)
    if not details:
        return per_scenario, {}

    # Aggregate error type counts by (scenario_type, model)
    _EMPTY = lambda: {"total": 0, "syntax_error": 0, "multimodal_error": 0,
                      "hallucination_error": 0, "logic_error": 0, "memory_error": 0,
                      "over_operation_error": 0, "correct": 0}
    counts = defaultdict(lambda: defaultdict(_EMPTY))

    for entry in details:
        if "error" in entry:
            continue
        scenario_type = entry.get("scenario_type")
        model = entry.get("model")
        if not scenario_type or not model:
            continue

        for r in entry.get("results", []):
            error_type = r.get("error_type")
            if error_type in ("missing_gt", "missing_eval"):
                continue
            counts[scenario_type][model]["total"] += 1
            if error_type in counts[scenario_type][model]:
                counts[scenario_type][model][error_type] += 1

    # Calculate pie proportions per scenario per model
    for scenario_type in SCENARIOS:
        for model, cnt in counts[scenario_type].items():
            per_scenario[scenario_type][model] = _compute_pie_proportions(cnt)

    # Calculate pie proportions per model across scenarios
    all_models = set()
    for s in SCENARIOS:
        all_models.update(counts[s].keys())

    for model in all_models:
        merged = _EMPTY()
        for s in SCENARIOS:
            if model in counts[s]:
                for k in merged:
                    merged[k] += counts[s][model][k]
        overall_counts[model] = _compute_pie_proportions(merged)

    return per_scenario, overall_counts


# =========================
# Chart 3: Error Reason Donut Charts
# =========================
def _draw_single_donut(ax, props, model, logo_zoom=0.10, name_fontsize=10, pct_fontsize=7):
    """
    Draw a single donut chart on the given ax.
    props: {"syntax": %, "multimodal": %, ...}  summing to 100%
    """
    values = [props.get(k, 0) for k in PIE_KEYS]

    # Filter out zero-value items
    filtered_labels = []
    filtered_values = []
    filtered_colors = []
    for i, v in enumerate(values):
        if v > 0:
            filtered_labels.append(PIE_LABELS[i])
            filtered_values.append(v)
            filtered_colors.append(PIE_COLORS[i])

    if not filtered_values:
        ax.text(0.5, 0.5, "No Data", transform=ax.transAxes,
                ha="center", va="center", fontsize=name_fontsize)
        ax.set_aspect("equal")
        ax.axis("off")
        return

    wedges, texts, autotexts = ax.pie(
        filtered_values,
        colors=filtered_colors,
        autopct=lambda pct: f"{pct:.1f}" if pct >= 4 else "",
        startangle=90,
        pctdistance=0.80,
        wedgeprops=dict(width=0.35, edgecolor="white", linewidth=1.5),
        textprops=dict(fontsize=pct_fontsize, fontweight="bold"),
    )
    for t in autotexts:
        t.set_fontsize(pct_fontsize)
        t.set_color("#333333")

    # Center logo (offset upward)
    img = load_logo_image(model, zoom=logo_zoom)
    if img is not None:
        ab = AnnotationBbox(img, (0, 0.10), frameon=False, box_alignment=(0.5, 0.5), pad=0)
        ax.add_artist(ab)

    # Model name placed below center logo
    ax.text(0, -0.18, MODEL_NAMES.get(model, model),
            ha="center", va="center", fontsize=name_fontsize, fontweight="bold")


def plot_chart3a_pie_by_model(models):
    """Chart 3a: Overall error reason donuts in a dynamic grid."""
    print(f"Plotting Chart 3a: Overall error reason donuts for {len(models)} models")

    _, overall_data = load_all_error_analysis()

    ncols = min(4, max(1, len(models)))
    nrows = math.ceil(len(models) / ncols)
    fig, axes = plt.subplots(nrows, ncols, figsize=(ncols * 5, nrows * 5.5))
    axes = np.asarray(axes, dtype=object).reshape(nrows, ncols)

    for idx, model in enumerate(models):
        r, c = divmod(idx, ncols)
        if r >= nrows:
            break
        ax = axes[r][c]
        props = overall_data.get(model, {})
        _draw_single_donut(ax, props, model, logo_zoom=0.12, name_fontsize=13, pct_fontsize=11)

    # Hide extra subplots
    for idx in range(len(models), nrows * ncols):
        r, c = divmod(idx, ncols)
        axes[r][c].axis("off")

    # Legend
    legend_elements = [plt.matplotlib.patches.Patch(
        facecolor=PIE_COLORS[i], edgecolor="white", label=PIE_LABELS[i]
    ) for i in range(len(PIE_LABELS))]
    fig.legend(handles=legend_elements, loc="lower center", ncol=len(PIE_LABELS),
               fontsize=13, frameon=True, bbox_to_anchor=(0.5, -0.02))

    plt.tight_layout(rect=[0, 0.03, 1, 1.0])

    save_path = os.path.join(FIGURES_DIR, "chart3a_error_pie_by_model.png")
    save_figure_pair(save_path)
    plt.close()
    print(f"Saved: {save_path}")


def plot_chart3b_pie_by_model_scenario(models):
    """Chart 3b: Error reason donuts by scenario and model."""
    print(f"Plotting Chart 3b: Error reason donuts for {len(SCENARIOS)} scenarios")

    per_scenario, _ = load_all_error_analysis()

    scenario_labels = {
        "retail": "Retail", "restaurant": "Restaurant",
        "kitchen": "Kitchen", "warehouse": "Warehouse",
        "household": "Household",
    }

    nrows = len(SCENARIOS)
    ncols = len(models)
    fig, axes = plt.subplots(nrows, ncols, figsize=(ncols * 3, nrows * 3.5))

    for row, scenario in enumerate(SCENARIOS):
        for col, model in enumerate(models):
            ax = axes[row][col] if nrows > 1 else axes[col]
            props = per_scenario[scenario].get(model, {})
            _draw_single_donut(ax, props, model,
                               logo_zoom=0.07, name_fontsize=9, pct_fontsize=8)
            # Add scenario label to first column
            if col == 0:
                ax.text(-0.25, 0.5, scenario_labels.get(scenario, scenario),
                        transform=ax.transAxes, ha="center", va="center",
                        fontsize=14, fontweight="bold", rotation=90)

    # Legend
    legend_elements = [plt.matplotlib.patches.Patch(
        facecolor=PIE_COLORS[i], edgecolor="white", label=PIE_LABELS[i]
    ) for i in range(len(PIE_LABELS))]
    fig.legend(handles=legend_elements, loc="lower center", ncol=len(PIE_LABELS),
               fontsize=12, frameon=True, bbox_to_anchor=(0.5, -0.01))

    plt.tight_layout(rect=[0.03, 0.03, 1, 1.0])

    save_path = os.path.join(FIGURES_DIR, "chart3b_error_pie_by_model_scenario.png")
    save_figure_pair(save_path)
    plt.close()
    print(f"Saved: {save_path}")


def plot_chart3_error_pie(models):
    """Plot all error reason donut charts"""
    plot_chart3a_pie_by_model(models)
    plot_chart3b_pie_by_model_scenario(models)


# =========================
# Scatter Plot Utility Functions
# =========================
def annotate_scatter_with_logo(ax, x, y, model, text_offset=(0, -12), zoom=0.11, fontsize=10):
    img = load_logo_image(model, zoom=zoom)
    if img is not None:
        ab = AnnotationBbox(
            img, (x, y),
            frameon=False,
            box_alignment=(0.5, 0.5),
            pad=0
        )
        ax.add_artist(ab)

    ax.annotate(
        MODEL_NAMES.get(model, model),
        (x, y),
        textcoords="offset points",
        xytext=text_offset,
        ha="center",
        va="top",
        fontsize=fontsize,
        fontweight="bold"
    )


def get_axis_padding(vals, ratio=0.08):
    vals = [v for v in vals if v is not None]
    if not vals:
        return 0, 1
    vmin = min(vals)
    vmax = max(vals)
    if math.isclose(vmin, vmax):
        pad = vmax * ratio if vmax != 0 else 1
    else:
        pad = (vmax - vmin) * ratio
    return vmin - pad, vmax + pad


# =========================
# Chart 4: Tokens vs Success
# =========================
def plot_chart4_tokens_vs_success(models):
    print("Plotting Chart 4: Avg token consumption vs joint success rate")

    xs, ys = [], []

    for model in models:
        summary = get_model_summary(model)
        metrics = get_metrics_from_summary(summary)
        xs.append(metrics["avg_tokens"])
        ys.append(get_overall_joint_success_rate(summary))

    fig, ax = plt.subplots(figsize=(14, 9))

    for model, x, y in zip(models, xs, ys):
        annotate_scatter_with_logo(ax, x, y, model, text_offset=(0, -18), zoom=0.08, fontsize=12)

    ax.set_xlabel("Average Tokens per Trajectory (Input + Output)", fontsize=15)
    ax.set_ylabel("Joint Success Rate (%)", fontsize=15)
    # No title
    ax.grid(True, linestyle="--", alpha=0.3)

    xmin, xmax = get_axis_padding(xs)
    ymin, ymax = get_axis_padding(ys)
    ax.set_xlim(max(0, xmin), xmax)
    ax.set_ylim(max(0, ymin - 2), min(100, ymax + 4))

    save_path = os.path.join(FIGURES_DIR, "chart4_tokens_vs_success.png")
    save_figure_pair(save_path)
    plt.close()


# =========================
# Chart 5: Rounds vs Success
# =========================
def plot_chart5_rounds_vs_success(models):
    print("Plotting Chart 5: Avg conversation rounds vs joint success rate")

    xs, ys = [], []

    for model in models:
        summary = get_model_summary(model)
        metrics = get_metrics_from_summary(summary)
        xs.append(metrics["avg_rounds"])
        ys.append(get_overall_joint_success_rate(summary))

    fig, ax = plt.subplots(figsize=(14, 9))

    for model, x, y in zip(models, xs, ys):
        annotate_scatter_with_logo(ax, x, y, model, text_offset=(0, -18), zoom=0.08, fontsize=12)

    ax.set_xlabel("Average User-Agent Conversation Rounds per Trajectory", fontsize=15)
    ax.set_ylabel("Joint Success Rate (%)", fontsize=15)
    # No title
    ax.grid(True, linestyle="--", alpha=0.3)

    xmin, xmax = get_axis_padding(xs)
    ymin, ymax = get_axis_padding(ys)
    ax.set_xlim(max(0, xmin), xmax)
    ax.set_ylim(max(0, ymin - 2), min(100, ymax + 4))

    save_path = os.path.join(FIGURES_DIR, "chart5_rounds_vs_success.png")
    save_figure_pair(save_path)
    plt.close()


# =========================
# Chart 6: Tool Calls vs Success
# =========================
def plot_chart6_tool_calls_vs_success(models):
    print("Plotting Chart 6: Avg tool calls vs joint success rate")

    xs, ys = [], []

    for model in models:
        summary = get_model_summary(model)
        metrics = get_metrics_from_summary(summary)
        xs.append(metrics["avg_tool_calls"])
        ys.append(get_overall_joint_success_rate(summary))

    fig, ax = plt.subplots(figsize=(14, 9))

    for model, x, y in zip(models, xs, ys):
        annotate_scatter_with_logo(ax, x, y, model, text_offset=(0, -18), zoom=0.08, fontsize=12)

    ax.set_xlabel("Average Tool Calls per Trajectory", fontsize=15)
    ax.set_ylabel("Joint Success Rate (%)", fontsize=15)
    # No title
    ax.grid(True, linestyle="--", alpha=0.3)

    xmin, xmax = get_axis_padding(xs)
    ymin, ymax = get_axis_padding(ys)
    ax.set_xlim(max(0, xmin), xmax)
    ax.set_ylim(max(0, ymin - 2), min(100, ymax + 4))

    save_path = os.path.join(FIGURES_DIR, "chart6_tool_calls_vs_success.png")
    save_figure_pair(save_path)
    plt.close()


# =========================
# Main Function
# =========================
def main():
    print("=" * 60)
    print("Starting evaluation result chart generation")
    print(f"EVAL_RESULT_DIR   : {EVAL_RESULT_DIR}")
    print(f"LOGO_DIR          : {LOGO_DIR}")
    print(f"ERROR_ANALYSIS_DIR: {ERROR_ANALYSIS_DIR}")
    print(f"FIGURES_DIR       : {FIGURES_DIR}")
    print("=" * 60)

    models = list_model_dirs()
    if not models:
        print("[ERROR] No valid model directories found under eval_result (containing summary.json)")
        return

    print("Detected models:")
    for m in models:
        print(f" - {m}")

    plot_chart1_joint_success_by_difficulty(models)
    plot_chart2_joint_success_by_scenario(models)
    plot_chart3_error_pie(models)
    plot_chart4_tokens_vs_success(models)
    plot_chart5_rounds_vs_success(models)
    plot_chart6_tool_calls_vs_success(models)

    print("=" * 60)
    print("All charts generated.")
    print(f"Output directory: {FIGURES_DIR}")
    print("=" * 60)


if __name__ == "__main__":
    main()