#!/usr/bin/env python3
from pathlib import Path
import shutil,sys,re
root=Path(sys.argv[1]);front=root/'frontend';src=Path(__file__).resolve().parent
(front/'js').mkdir(parents=True,exist_ok=True)
shutil.copy2(src/'final_guard_v249412.js',front/'js/final_guard_v249412.js')
shutil.copy2(src/'frontend_bundle/js/unified_publish_scope_security_v249398.js',front/'js/unified_publish_scope_security_v249398.js')
shutil.copy2(src/'frontend_bundle/index.js',front/'index.js')
h=(src/'frontend_bundle/index.html').read_text(encoding='utf-8')
h=re.sub(r'\n?<script[^>]+final_guard_v249(?:40[0-9]|410|411|412)\.js[^>]*></script>\s*','\n',h)
h=h.replace('</body>','<script src="/js/final_guard_v249412.js?v=249412-direct-create-plus-stable" charset="utf-8" defer></script>\n</body>')
(front/'index.html').write_text(h,encoding='utf-8')
relay=root/'relay_server_clean.py';r=relay.read_text(encoding='utf-8')
r=re.sub(r'(?m)^VERSION\s*=\s*["\'][^"\']+["\']','VERSION  = "2.4.9.412-direct-create-plus-stable"',r,count=1)
if 'BEGIN V249412_DIRECT_CREATE_PLUS_STABLE' not in r:
 r += "\n# BEGIN V249412_DIRECT_CREATE_PLUS_STABLE\n@app.get('/api/diagnostics/v249412')\ndef api_diagnostics_v249412(room_id: str = Query('ithaki-phone-test')):\n    return {'ok': True, 'version': 'V249412-direct-create-plus-stable', 'direct_plus_create': True, 'home_publish_create': True, 'publish_observer': 'childlist-debounced', 'apk_required_for_this_fix': False}\n# END V249412_DIRECT_CREATE_PLUS_STABLE\n"
relay.write_text(r,encoding='utf-8')
assert h.count('final_guard_v249412.js')==1
print('PATCH_SERVER_V249412=OK')
