#!/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)
for name in ['index.js','index.html','frontend_build_v249414.txt']:
 shutil.copy2(src/'frontend_bundle'/name,front/name)
for name in ['final_guard_v249414.js','professional_isolation_v249413.js','unified_account_v249386.js','creator_publication_v249388.js']:
 shutil.copy2(src/'frontend_bundle/js'/name,front/'js'/name)
h=(front/'index.html').read_text(encoding='utf-8')
for old in ['professional_flow_v249397.js','unified_publish_scope_security_v249398.js','preview_stability_v249400.js','final_guard_v249412.js']:
 h=re.sub(r'\s*<script[^>]+(?:/js/)?'+re.escape(old)+r'[^>]*></script>\s*','\n',h)
h=re.sub(r'\s*<script[^>]+final_guard_v249414\.js[^>]*></script>\s*','\n',h)
h=h.replace('</body>','<script src="/js/final_guard_v249414.js?v=249414-plus-menu-single-preview" 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.414-plus-menu-single-preview"',r,count=1)
if 'BEGIN V249414_PLUS_MENU_SINGLE_PREVIEW' not in r:r += "\n# BEGIN V249414_PLUS_MENU_SINGLE_PREVIEW\n@app.get('/api/diagnostics/v249414')\ndef api_diagnostics_v249414(room_id: str = Query('ithaki-phone-test')):\n    return {'ok': True, 'version': 'V249414-plus-menu-single-preview', 'plus_menu': True, 'single_preview_owner': True, 'professional_publishing': False, 'professional_contacts': False, 'apk_required_for_this_fix': False}\n# END V249414_PLUS_MENU_SINGLE_PREVIEW\n"
relay.write_text(r,encoding='utf-8')
assert h.count('final_guard_v249414.js')==1
print('PATCH_SERVER_V249414=OK')
