#!/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_v249409.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_v24940[0-9]\.js[^>]*></script>\s*','\n',h)
tag='<script src="/js/final_guard_v249409.js?v=249409-one-unified-preview-runtime" 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 V249408 · Σταθερή Ροή, ενεργά μέλη και σωστή προεπισκόπηση','OK-ITHAKI V249409 · Μία ενιαία προεπισκόπηση και σταθερή δημοσίευση')
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='249408';","const ITHAKI_BUILD_249318='249409';")
j=j.replace('2.4.9.408-feed-runtime-active-members-preview-route','2.4.9.409-one-unified-preview-runtime').replace('249408-feed-runtime-active-members-preview-route','249409-one-unified-preview-runtime')
required=['V249409_ONE_UNIFIED_PREVIEW_CORE_HOOKS','__ITHAKI_CORE_SEND_PREVIEW__','ithaki:preview-closed']
for token in required:
    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.409-one-unified-preview-runtime\"', r, count=1)
if 'BEGIN V249409_ONE_UNIFIED_PREVIEW_RUNTIME' not in r:
    r += """
# BEGIN V249409_ONE_UNIFIED_PREVIEW_RUNTIME
@app.get('/api/diagnostics/v249409')
def api_diagnostics_v249409(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': 'V249409-one-unified-preview-runtime', 'online_response_count': len(online), 'one_preview_owner': True, 'normal_and_professional_preview_unified': True, 'choose_file_alias_defined': True, 'professional_private_input_not_globally_captured': True, 'send_preview_wrapper_recursion_removed': True, 'apk_required_for_this_fix': False}
# END V249409_ONE_UNIFIED_PREVIEW_RUNTIME
"""
relay.write_text(r,encoding='utf-8')
print('PATCH_SERVER_V249409=OK')
