"""Redraw cited aggregate data, not CCA experiment results. Requires matplotlib.

From CCA root: python -m pip install matplotlib; python site/assets/studies/draw_charts.py
Tables: https://arxiv.org/html/2606.02875v2#S5.T2
        https://arxiv.org/html/2607.21656v1#S3.T2
No confidence intervals or per-task values are inferred from aggregate rows.
"""
import csv
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager

HERE = Path(__file__).resolve().parent
FONT = Path('C:/Windows/Fonts/msjh.ttc')
if FONT.exists():
    font_manager.fontManager.addfont(str(FONT))
    plt.rcParams['font.family'] = font_manager.FontProperties(fname=str(FONT)).get_name()
plt.rcParams.update({'axes.unicode_minus': False, 'font.size': 13, 'text.color': '#e5e9ed',
                     'axes.labelcolor': '#b6c0cb', 'xtick.color': '#b6c0cb', 'ytick.color': '#e5e9ed',
                     'axes.edgecolor': '#46505c', 'axes.facecolor': '#101418', 'figure.facecolor': '#101418'})

HANDOFF = [
    ('檔案＋原始需求', 181, 46.4, 99),
    ('完整操作紀錄', 181, 52.5, 41),
    ('一般摘要', 181, 51.4, 53),
    ('結構化筆記', 181, 50.8, 55),
]
REVIEW = [
    ('Claude 單次產出', 106, 91.4, .226, 86.2),
    ('Claude → Claude', 106, 91.4, .389, 135.8),
    ('Claude → Codex', 96, 82.8, .382, 118.0),
    ('Codex 單次產出', 83, 71.6, .190, 38.5),
    ('Codex → Codex', 98, 84.5, .312, 67.9),
    ('Codex → Claude', 104, 89.7, .443, 112.4),
]

def write_csv(name, headers, rows):
    with (HERE / name).open('w', newline='', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(rows)

write_csv('handoff-literature.csv', ['handoff_view', 'runs', 'solved_rate_percent', 'median_agent_events', 'scope', 'source'],
          [(*r, 'Qwen to Qwen; Table 2; 75 source tasks yield 181 handoff points', 'https://arxiv.org/html/2606.02875v2') for r in HANDOFF])
write_csv('review-literature.csv', ['condition', 'passed', 'total', 'reported_pass_percent', 'reported_cost_usd_per_task', 'reported_latency_seconds', 'source'],
          [(r[0], r[1], 116, *r[2:], 'https://arxiv.org/html/2607.21656v1') for r in REVIEW])


def style(ax):
    ax.spines[['top', 'right', 'left']].set_visible(False)
    ax.tick_params(axis='both', length=0, pad=10)
    ax.grid(axis='x', color='#313943', linewidth=.6)
    ax.set_axisbelow(True)


def heading(fig, title, subtitle):
    fig.text(.07, .95, '公開研究 / 資料重繪', fontsize=12, color='#9ebbd7')
    fig.text(.07, .90, title, fontsize=22, weight='bold')
    fig.text(.07, .855, subtitle, fontsize=12, color='#b6c0cb')

fig, axs = plt.subplots(2, 1, figsize=(10, 10))
fig.subplots_adjust(left=.24, right=.90, top=.79, bottom=.20, hspace=.65)
heading(fig, '交接資訊如何影響接手成本？', 'Qwen → Qwen 子組｜每種交接方式 181 個交接點')
for ax, index, xlabel, xmax in [(axs[0], 3, '代理事件數中位數（不是秒數；較少代表互動較少）', 120),
                               (axs[1], 2, '最終題目解決率（%；不是需求保留率）', 100)]:
    vals = [r[index] for r in HANDOFF]
    ax.barh(range(4), vals, color=['#87929e', '#9ebbd7', '#9ebbd7', '#9ebbd7'], height=.57)
    ax.set_yticks(range(4), [r[0] for r in HANDOFF])
    ax.invert_yaxis()
    ax.set_xlim(0, xmax)
    ax.set_xlabel(xlabel, fontsize=11, labelpad=12)
    for i, v in enumerate(vals):
        ax.text(v + xmax*.025, i, f'{v:g}' + ('%' if index == 2 else ''), va='center', fontsize=13)
    style(ax)
fig.text(.07, .055, '資料：KC & Budathoki，Handoff Debt，arXiv:2606.02875v2，表 2。\n75 個原始任務／每組 181 個交接點；此圖節錄 Qwen → Qwen 配置。', fontsize=10, color='#b6c0cb')
fig.savefig(HERE / 'handoff-literature.png', dpi=180)
plt.close(fig)

fig, ax = plt.subplots(figsize=(10, 8))
fig.subplots_adjust(left=.31, right=.87, top=.78, bottom=.22)
heading(fig, '多一輪審查，不保證通過率提高', 'Claude Opus 4.7 / Codex GPT-5.5｜同一組 116 道題目')
vals = [r[2] for r in REVIEW]
ax.barh(range(6), vals, color=['#87929e', '#9ebbd7', '#d9957a', '#87929e', '#9ebbd7', '#9ebbd7'], height=.6)
ax.set_yticks(range(6), [r[0] for r in REVIEW])
ax.invert_yaxis()
ax.set_xlim(0, 100)
ax.set_xticks([0, 25, 50, 75, 100])
ax.set_xlabel('通過率（%）；箭頭方向為「撰寫 → 審查」', fontsize=11, labelpad=13)
for i, row in enumerate(REVIEW):
    ax.text(row[2] + 1, i, f'{row[2]:.1f}%', va='center', fontsize=13)
    ax.text(2, i, f'{row[1]}/116', va='center', color='#101418', fontsize=12, weight='bold')
style(ax)
fig.text(.07, .06, '資料：Xiang 等人，arXiv:2607.21656v1，表 2（有效完成案例）。\n設定：high 思考程度，單輪靜態審查；審查者不能執行測試。', fontsize=10, color='#b6c0cb')
fig.savefig(HERE / 'review-pass-rates.png', dpi=180)
plt.close(fig)

fig, axs = plt.subplots(2, 1, figsize=(10, 11))
fig.subplots_adjust(left=.31, right=.88, top=.80, bottom=.21, hspace=.5)
heading(fig, '品質之外，審查也增加資源需求', '同一篇論文的成本與延遲｜歷史測試條件，非即時報價')
for ax, index, xlabel, xmax in [(axs[0], 3, '論文估計每題 API 等值成本（美元）', .53),
                               (axs[1], 4, '論文報告延遲（秒）', 165)]:
    vals = [r[index] for r in REVIEW]
    ax.barh(range(6), vals, color=['#87929e', '#9ebbd7', '#d9957a', '#87929e', '#9ebbd7', '#9ebbd7'], height=.57)
    ax.set_yticks(range(6), [r[0] for r in REVIEW], fontsize=11)
    ax.invert_yaxis()
    ax.set_xlim(0, xmax)
    ax.set_xlabel(xlabel, fontsize=11, labelpad=12)
    for i, v in enumerate(vals):
        ax.text(v + xmax*.025, i, f'{v:.3f}' if index == 3 else f'{v:.1f}', va='center', fontsize=12)
    style(ax)
fig.text(.07, .055, '資料：Xiang 等人，arXiv:2607.21656v1，表 2。\n成本由論文依當時 Token 單價估算，不是使用者的訂閱帳單；兩個面板須與通過率一起閱讀。', fontsize=10, color='#b6c0cb')
fig.savefig(HERE / 'review-tradeoffs.png', dpi=180)
plt.close(fig)
print('Saved 3 figures and 2 aggregate-data CSV files')
