#!/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_v249416.txt']:
    shutil.copy2(src/'frontend_bundle'/name,front/name)
for name in ['final_guard_v249416.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','final_guard_v249414.js','final_guard_v249415.js','final_guard_v249416.js']:
    h=re.sub(r'\s*<script[^>]+(?:/js/)?'+re.escape(old)+r'[^>]*></script>\s*','\n',h)
h=h.replace('</body>','<script src="/js/final_guard_v249416.js?v=249416-plus-route-loop-profile-exit-fix" 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.416-plus-route-loop-profile-exit-fix"',r,count=1)
if 'BEGIN V249416_PLUS_ROUTE_LOOP_PROFILE_EXIT_FIX' not in r:
    r += """
# BEGIN V249416_PLUS_ROUTE_LOOP_PROFILE_EXIT_FIX
@app.get('/api/diagnostics/v249416')
def api_diagnostics_v249416(room_id: str = Query('ithaki-phone-test')):
    return {'ok': True, 'version': 'V249416-plus-route-loop-profile-exit-fix', 'recursive_page_wrapper': False, 'plus_close_once': True, 'profile_exit': True, 'full_old_plus_items': 12, 'preview_preserved': True, 'studio_preserved': True, 'professional_preview': False, 'apk_required_for_this_fix': False}
# END V249416_PLUS_ROUTE_LOOP_PROFILE_EXIT_FIX
"""
relay.write_text(r,encoding='utf-8')
assert h.count('final_guard_v249416.js')==1
print('PATCH_SERVER_V249416=OK')
