#!/usr/bin/env python3
"""Idempotently wire the YouTube Playables SDK + shim into every <game>/index.html."""
import glob, re
shim = open('yt-playables-shim.js').read()
SDK = '<script src="https://www.youtube.com/game_api/v1"></script>\n'
for f in sorted(glob.glob('*/index.html')):
    h = open(f).read()
    if 'id="game-src"' in h:
        # refresh shim only
        h = re.sub(r'(<script id="yt-shim">).*?(</script>)', lambda m: m.group(1)+'\n'+shim+m.group(2), h, flags=re.S)
    else:
        h = h.replace('<meta charset="UTF-8">\n', '<meta charset="UTF-8">\n'+SDK, 1)
        h = h.replace('\n<script>\n', '\n<script type="text/plain" id="game-src">\n', 1)
        h = re.sub(r'(id="game-src">.*?</script>)', lambda m: m.group(1)+'\n<script id="yt-shim">\n'+shim+'</script>', h, count=1, flags=re.S)
    open(f,'w').write(h)
    print('ok', f)
