#!/usr/bin/env python3
from pathlib import Path
import shutil,sys,re
root=Path(sys.argv[1]) if len(sys.argv)>1 else Path.cwd();front=root/'frontend';src=Path(__file__).resolve().parent
(front/'js').mkdir(parents=True,exist_ok=True)
for name in ['final_guard_v249410.js','feed_radical_v249386.js','creator_publication_v249388.js','unified_account_v249386.js']:
 p=src/name
 if not p.exists(): raise RuntimeError('missing component '+name)
 shutil.copy2(p,front/'js'/name)
html=front/'index.html';h=html.read_text(encoding='utf-8')
h=re.sub(r'\n?<script[^>]+final_guard_v249(?:40[0-9]|410)\.js[^>]*></script>\s*','\n',h)
tag='<script src="/js/final_guard_v249410.js?v=249410-ram-only-preview-active-self" charset="utf-8" defer></script>\n'
h=h.replace('</body>',tag+'</body>') if '</body>' in h else h+'\n'+tag
html.write_text(h,encoding='utf-8')
idx=front/'index.js';j=idx.read_text(encoding='utf-8')
for token in ['V249410_RAM_ONLY_PREVIEW_ACTIVE_SELF','function v249408NormalizeOnline(p)','self=id===String(state.device)']:
 if token not in j: raise RuntimeError('index missing '+token)
idx.write_text(j,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.410-ram-only-preview-active-self"',r,count=1)
if 'BEGIN V249410_RAM_ONLY_PREVIEW_ACTIVE_SELF' not in r:
 r += """
# BEGIN V249410_RAM_ONLY_PREVIEW_ACTIVE_SELF
@app.get('/api/diagnostics/v249410')
def api_diagnostics_v249410(room_id: str = Query('ithaki-phone-test'), device_id: str = Query('')):
    online = _people_visible_online(room_id, max_age_seconds=180)
    return {'ok': True, 'version': 'V249410-ram-only-preview-active-self', 'online_response_count': len(online), 'ram_only_preview': True, 'indexeddb_blob_copy_disabled': True, 'current_active_member_included': True, 'one_preview_owner': True, 'apk_required_for_this_fix': False}
# END V249410_RAM_ONLY_PREVIEW_ACTIVE_SELF
"""
relay.write_text(r,encoding='utf-8')
count=h.count('final_guard_v249410.js')
if count != 1: raise RuntimeError('final guard count after patch='+str(count))
print('PATCH_SERVER_V249410B=OK')
print('FINAL_GUARD_TAG_COUNT='+str(count))
