#!/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_v249407.js',front/'js/final_guard_v249407.js')
html=front/'index.html'; h=html.read_text(encoding='utf-8')
h=re.sub(r'\n?<script[^>]+final_guard_v249406\.js[^>]*></script>\s*','\n',h);h=re.sub(r'\n?<script[^>]+final_guard_v249407\.js[^>]*></script>\s*','\n',h)
tag='<script src="/js/final_guard_v249407.js?v=249407-core-state-stable-home-preview-recovery" charset="utf-8" defer></script>\n';h=h.replace('</body>',tag+'</body>') if '</body>' in h else h+'\n'+tag
h=h.replace('V249406 · Τελικός guard προεπισκόπησης','V249407 · Σταθερή Αρχική και προεπισκόπηση');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='249406';", "const ITHAKI_BUILD_249318='249407';")
needle="localStorage.setItem('ith_device',state.device);"; export="window.__ITHAKI_CORE_STATE__=state;window.state=state;window.ITH=window.ITH||{};window.ITH.state=state;\n"
if export.strip() not in j:j=j.replace(needle,needle+'\n'+export,1)
j=j.replace("if(state.page==='home')renderHome();renderPeople()}", "if(state.page==='home')refreshHomeStoriesV249407();if(state.page==='dm'||document.getElementById('dmPage')?.classList.contains('active'))renderPeople()}",1)
j=j.replace('setInterval(loadPeople,22000);','setInterval(loadPeople,60000);',1)
boot_expr="boot().catch(e=>{console.error(e);toast('Startup error: '+e.message,6000);renderHome();renderNav()})"
if 'V249407_CORE_STATE_STABLE_HOME_SERVER_FRIENDS' not in j:
    override=(src/'v249407_index_override.js').read_text(encoding='utf-8')
    if boot_expr not in j: raise RuntimeError('V249407 boot insertion marker not found')
    j=j.replace(boot_expr,override+'\n'+boot_expr,1)
if 'V249407_CLEAN_BOOT_BOUNDARY' not in j:
    pos=j.find(boot_expr)
    if pos<0: raise RuntimeError('V249407 clean boot marker not found')
    j=j[:pos]+boot_expr+";\n/* V249407_CLEAN_BOOT_BOUNDARY: unreachable duplicate tail disabled */\n})();\n"
j=j.replace('249406-final-after-defer-preview-home-guard','249407-core-state-stable-home-preview-recovery').replace('2.4.9.406-final-after-defer-preview-home-guard','2.4.9.407-core-state-stable-home-preview-recovery')
idx.write_text(j,encoding='utf-8')
relay=root/'relay_server_clean.py';r=relay.read_text(encoding='utf-8').replace('2.4.9.406-final-after-defer-preview-home-guard','2.4.9.407-core-state-stable-home-preview-recovery').replace('249406-final-after-defer-preview-home-guard','249407-core-state-stable-home-preview-recovery')
if 'BEGIN V249407_CORE_STATE_STABLE_HOME_PREVIEW_RECOVERY' not in r:r += """
# BEGIN V249407_CORE_STATE_STABLE_HOME_PREVIEW_RECOVERY
@app.get('/api/diagnostics/v249407')
def api_diagnostics_v249407(room_id: str = Query('ithaki-phone-test'), device_id: str = Query('')):
    return {'ok': True, 'version': 'V249407-core-state-stable-home-preview-recovery', 'real_core_state_exported': True, 'home_full_rebuild_disabled': True, 'active_home_members_only': True, 'server_accepted_friends_only': True, 'preview_indexeddb_recovery': True, 'feed_member_gate_removed': True, 'apk_required_for_this_fix': False}
@app.get('/api/diagnostics/file_preview_v249407')
def api_file_preview_v249407():
    return {'ok': True, 'version': 'V249407-core-state-stable-home-preview-recovery', 'script': 'final_guard_v249407.js', 'uses_real_core_state': True, 'indexeddb_pending_file': True, 'heavy_studio_disabled': True, 'home_redirect_blocked': True}
# END V249407_CORE_STATE_STABLE_HOME_PREVIEW_RECOVERY
"""
relay.write_text(r,encoding='utf-8');print('PATCH_SERVER_V249407=OK')
