import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.family'] = 'sans-serif'
for f in ['WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'SimHei', 'DejaVu Sans']:
    try:
        plt.rcParams['font.sans-serif'] = [f]
        break
    except:
        continue
plt.rcParams['axes.unicode_minus'] = False

# Data
ranges = ['0分钟', '5-10', '10-15', '15-20', '20-30', '30-45', '45-60', '60-90', '90-120', '120+']
combos = [1403, 4, 21, 240, 1208, 1331, 463, 233, 68, 50]
users  = [9, 3, 16, 138, 638, 710, 283, 144, 54, 35]

fig, axes = plt.subplots(1, 2, figsize=(16, 6))

x = np.arange(len(ranges))
colors = plt.cm.Blues(np.linspace(0.35, 0.95, len(ranges)))

# === Left: Combo count ===
bars1 = axes[0].bar(x, combos, color=colors, edgecolor='white', linewidth=0.5)
for bar, v in zip(bars1, combos):
    if v > 0:
        axes[0].text(bar.get_x() + bar.get_width()/2, bar.get_height() + max(combos)*0.02,
                    str(v), ha='center', fontsize=9, color='#333')
axes[0].set_xticks(x)
axes[0].set_xticklabels(ranges, fontsize=10, rotation=30)
axes[0].set_ylabel('重复学习组合数', fontsize=12)
axes[0].set_title('按总学习时长分布（组合数）', fontsize=14, fontweight='bold')
axes[0].grid(axis='y', alpha=0.2, linestyle='--')
axes[0].set_ylim(0, max(combos)*1.18)

# Highlight 0-min bar differently
bars1[0].set_color('#E74C3C')

# === Right: User count ===
bars2 = axes[1].bar(x, users, color=colors, edgecolor='white', linewidth=0.5)
for bar, v in zip(bars2, users):
    if v > 0:
        axes[1].text(bar.get_x() + bar.get_width()/2, bar.get_height() + max(users)*0.02,
                    str(v), ha='center', fontsize=9, color='#333')
axes[1].set_xticks(x)
axes[1].set_xticklabels(ranges, fontsize=10, rotation=30)
axes[1].set_ylabel('用户数', fontsize=12)
axes[1].set_title('按总学习时长分布（用户数）', fontsize=14, fontweight='bold')
axes[1].grid(axis='y', alpha=0.2, linestyle='--')
axes[1].set_ylim(0, max(users)*1.18)
bars2[0].set_color('#E74C3C')

fig.suptitle('最近3个月（2026.03-05）重复学习时长分布（总学习时长 = 各次完成时长累加）', 
             fontsize=16, fontweight='bold', y=1.02)

fig.text(0.5, 0.01,
    '整体: 5,021个重复组合, 平均总时长28.0分钟(非零38.8分钟), 中位数27.3分钟 | '
    '注: 红色=无组件级时长记录(0分钟), 占28%',
    ha='center', fontsize=10, color='#555')

plt.tight_layout(rect=[0, 0.06, 1, 0.95])
plt.savefig('/root/.openclaw/workspace/output/repeat_duration_3m.png', dpi=150, bbox_inches='tight')
print('Saved.')
