#!/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)
shutil.copy2(src/'final_guard_v249408.js',front/'js/final_guard_v249408.js')
shutil.copy2(src/'feed_radical_v249386.js',front/'js/feed_radical_v249386.js')
html=front/'index.html';h=html.read_text(encoding='utf-8')
h=re.sub(r'\n?<script[^>]+final_guard_v24940[0-8]\.js[^>]*></script>\s*','\n',h)
tag='<script src="/js/final_guard_v249408.js?v=249408-feed-runtime-active-members-preview-route" charset="utf-8" defer></script>\n'
h=h.replace('</body>',tag+'</body>') if '</body>' in h else h+'\n'+tag
h=h.replace('OK-ITHAKI V249407 · Σταθερή Αρχική και προεπισκόπηση','OK-ITHAKI V249408 · Σταθερή Ροή, ενεργά μέλη και σωστή προεπισκόπηση')
html.write_text(h,encoding='utf-8')
idx=front/'index.js';j=idx.read_text(encoding='utf-8')
j=j.replace("const ITHAKI_BUILD_249318='249407';","const ITHAKI_BUILD_249318='249408';")
j=j.replace('2.4.9.407-core-state-stable-home-preview-recovery','2.4.9.408-feed-runtime-active-members-preview-route').replace('249407-core-state-stable-home-preview-recovery','249408-feed-runtime-active-members-preview-route')
override=(src/'v249408_index_override.js').read_text(encoding='utf-8')
if 'V249408_DIRECT_ONLINE_MEMBERS_AND_PREVIEW_ROUTE' not in j:
    marker="boot().catch(e=>{console.error(e);toast('Startup error: '+e.message,6000);renderHome();renderNav()});"
    if marker not in j: raise RuntimeError('V249408 boot marker not found')
    j=j.replace(marker,override+'\n'+marker,1)
idx.write_text(j,encoding='utf-8')
relay=root/'relay_server_clean.py';r=relay.read_text(encoding='utf-8')
r=r.replace('2.4.9.407-core-state-stable-home-preview-recovery','2.4.9.408-feed-runtime-active-members-preview-route').replace('249407-core-state-stable-home-preview-recovery','249408-feed-runtime-active-members-preview-route')
if 'BEGIN V249408_FEED_RUNTIME_ACTIVE_MEMBERS_PREVIEW_ROUTE' not in r:r += """
# BEGIN V249408_FEED_RUNTIME_ACTIVE_MEMBERS_PREVIEW_ROUTE
@app.get('/api/diagnostics/v249408')
def api_diagnostics_v249408(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': 'V249408-feed-runtime-active-members-preview-route', 'online_response_count': len(online), 'feed_ensure_overlay_restored': True, 'explicit_file_buttons_only': True, 'mime_first_preview_kind': True, 'server_accepted_friends_only': True, 'apk_required_for_this_fix': False}
# END V249408_FEED_RUNTIME_ACTIVE_MEMBERS_PREVIEW_ROUTE
"""
relay.write_text(r,encoding='utf-8');print('PATCH_SERVER_V249408=OK')
