from pathlib import Path
from datetime import datetime
import shutil
base=Path('/opt/struktur/youtube-research')
app=base/'app.py'
tpl=base/'templates/index.html'
ts=datetime.now().strftime('%Y%m%d-%H%M%S')
shutil.copy2(app, str(app)+f'.bak-meta-{ts}')
shutil.copy2(tpl, str(tpl)+f'.bak-meta-{ts}')
s=app.read_text()
old=''' value = item.get("statistics", {}).get("viewCount")\n if value is not None:\n stats_by_video[item["id"]] = int(value)\n duration_by_video[item["id"]] = _iso8601_duration_seconds(item.get("contentDetails", {}).get("duration"))'''
new=''' st = item.get("statistics", {})\n stats_by_video[item["id"]] = {\n "view_count": int(st["viewCount"]) if st.get("viewCount") is not None else None,\n "like_count": int(st["likeCount"]) if st.get("likeCount") is not None else None,\n "comment_count": int(st["commentCount"]) if st.get("commentCount") is not None else None,\n }\n duration_by_video[item["id"]] = _iso8601_duration_seconds(item.get("contentDetails", {}).get("duration"))'''
assert old in s
s=s.replace(old,new,1)
old2=''' view_count = stats_by_video.get(vid_id)\n subscriber_count = subs_by_channel.get(channel_id)'''
new2=''' video_stats = stats_by_video.get(vid_id, {})\n view_count = video_stats.get("view_count")\n like_count = video_stats.get("like_count")\n comment_count = video_stats.get("comment_count")\n subscriber_count = subs_by_channel.get(channel_id)'''
assert old2 in s
s=s.replace(old2,new2,1)
old3=''' "view_count": view_count,\n "duration_seconds": duration_by_video.get(vid_id),'''
new3=''' "view_count": view_count,\n "like_count": like_count,\n "comment_count": comment_count,\n "duration_seconds": duration_by_video.get(vid_id),'''
assert old3 in s
s=s.replace(old3,new3,1)
app.write_text(s)
print(ts)