import csv,datetime as D
import matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm
for f in ['/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc','/usr/share/fonts/opentype/noto/NotoSansCJK-Medium.ttc']: fm.fontManager.addfont(f)
plt.rcParams.update({'font.family':'Noto Sans CJK JP','font.size':10,'axes.edgecolor':'#c9c8c3','axes.labelcolor':'#52514e',
 'xtick.color':'#52514e','ytick.color':'#52514e','text.color':'#0b0b0b','figure.facecolor':'#fcfcfb','axes.facecolor':'#fcfcfb',
 'savefig.facecolor':'#fcfcfb','axes.spines.top':False,'axes.spines.right':False})
BLUE='#2a78d6'; MUTED='#8b8a85'; INK2='#52514e'
J=D.timedelta(hours=9)
s=[D.datetime.fromisoformat(x['accessed_at'].replace('+00','+00:00'))+J for x in csv.DictReader(open('input/crawler_logs.csv'))
   if x['bot_name']=='googlebot' and x['path'].startswith('/sitemap')]
iv=[(b-a).total_seconds()/86400 for a,b in zip(s,s[1:])]
fig,ax=plt.subplots(figsize=(9,4.6))
x=range(len(iv))
ax.bar(x,iv,width=0.62,color=BLUE,linewidth=0)
for i,v in enumerate(iv): ax.text(i,v+0.12,f'{v:.1f}日',ha='center',fontsize=9,color=INK2)
ax.set_xticks(list(x)); ax.set_xticklabels([f'{b.month}/{b.day}' for b in s[1:]],fontsize=9)
ax.set_xlabel('読んだ日（前回からの間隔を棒で表示）',fontsize=9)
ax.set_ylim(0,8.4); ax.set_yticks([]); ax.spines['left'].set_visible(False)
for lab,day,ha in [('10/3 374件を追加 ',D.date(2026,10,3),'right'),(' 10/9 361件を追加',D.date(2026,10,9),'left')]:
    i=next(k for k,b in enumerate(s[1:]) if b.date()>day)-0.5
    ax.axvline(i,color=MUTED,lw=0.8,ls=(0,(3,3)),zorder=0); ax.text(i,8.1,lab,fontsize=8,color=INK2,va='top',ha=ha)
fig.suptitle('Googlebot が sitemap.xml を読んだ間隔',x=0.02,ha='left',fontsize=13)
fig.text(0.02,0.885,'2026年9月13日〜10月13日・日本時間。最初の読み込みは 9/13 16:35',fontsize=8.5,color=INK2,ha='left')
fig.text(0.02,0.01,'herahin.net のアクセスログより作成',fontsize=8,color=MUTED,ha='left')
plt.tight_layout(rect=(0,0.03,1,0.86))
fig.savefig('fig/fig9_googlebot_sitemap_interval.png',dpi=200)
