#!/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_v249406.js','feed_radical_v249386.js','feed_radical_v249384.js']:
    if (src/name).is_file(): shutil.copy2(src/name, front/'js'/name)
html=front/'index.html'
s=html.read_text(encoding='utf-8')
s=re.sub(r'\n?<script[^>]+hard_preview_contact_v24940[3-5]\.js[^>]*></script>\s*','\n',s)
s=re.sub(r'\n?<script[^>]+final_guard_v249406\.js[^>]*></script>\s*','\n',s)
tag='<script src="/js/final_guard_v249406.js?v=249406-final-after-defer-preview-home-guard" charset="utf-8" defer></script>\n'
s=s.replace('</body>',tag+'</body>') if '</body>' in s else s+'\n'+tag
s=s.replace('V249399 · Σταθερή προεπισκόπηση χωρίς λευκή οθόνη','V249406 · Τελικός guard προεπισκόπησης')
html.write_text(s,encoding='utf-8')
idx=front/'index.js'
if idx.exists():
    j=idx.read_text(encoding='utf-8')
    for old in ['2.4.9.405-remove-feed-gate-preview-diagnostic','2.4.9.404-preview-home-members-recovery','2.4.9.403-desktop-safe-preview-contact-truth','2.4.9.402-hard-preview-contact-clean','2.4.9.401-immediate-file-preview','2.4.9.400-preview-friendship-consistency']:
        j=j.replace(old,'2.4.9.406-final-after-defer-preview-home-guard')
    for old in ['249405-remove-feed-gate-preview-diagnostic','249404-preview-home-members-recovery','249403-desktop-safe-preview-contact-truth','249402-hard-preview-contact-clean','249401-immediate-file-preview','249400-preview-friendship-consistency']:
        j=j.replace(old,'249406-final-after-defer-preview-home-guard')
    j=re.sub(r"const ITHAKI_BUILD_249318='[^']+';", "const ITHAKI_BUILD_249318='249406';", j, count=1)
    idx.write_text(j,encoding='utf-8')
for fname in ['feed_radical_v249386.js','feed_radical_v249384.js']:
    p=front/'js'/fname
    if p.exists():
        t=p.read_text(encoding='utf-8')
        t=t.replace("const c=context();if(!c.registered)return showMemberGate382();closeMemberGate382();", "const c=context();closeMemberGate382();")
        t=re.sub(r"function showMemberGate382\(\)\{.*?\n  \}", "function showMemberGate382(){ closeMemberGate382(); try{document.documentElement.setAttribute('data-ithaki-feed-member-gate-removed','V249406')}catch(e){} return false; }", t, flags=re.S)
        p.write_text(t,encoding='utf-8')
relay=root/'relay_server_clean.py'
r=relay.read_text(encoding='utf-8')
for old in ['2.4.9.405-remove-feed-gate-preview-diagnostic','2.4.9.404-preview-home-members-recovery','2.4.9.403-desktop-safe-preview-contact-truth','2.4.9.402-hard-preview-contact-clean','2.4.9.401-immediate-file-preview','2.4.9.400-preview-friendship-consistency']:
    r=r.replace(old,'2.4.9.406-final-after-defer-preview-home-guard')
for old in ['249405-remove-feed-gate-preview-diagnostic','249404-preview-home-members-recovery','249403-desktop-safe-preview-contact-truth','249402-hard-preview-contact-clean','249401-immediate-file-preview','249400-preview-friendship-consistency']:
    r=r.replace(old,'249406-final-after-defer-preview-home-guard')
if 'BEGIN V249406_FINAL_AFTER_DEFER_PREVIEW_HOME_GUARD' not in r:
    r += """
# BEGIN V249406_FINAL_AFTER_DEFER_PREVIEW_HOME_GUARD
# Final frontend guard: runs after deferred scripts, owns file selection, blocks preview->home redirects, no data deletion.
@app.get('/api/diagnostics/v249406')
def api_diagnostics_v249406(room_id: str = Query('ithaki-phone-test'), device_id: str = Query('')):
    return {'ok': True, 'version': 'V249406-final-after-defer-preview-home-guard', 'final_guard_defer_last': True, 'owns_file_clicks': True, 'owns_all_file_changes': True, 'blocks_home_redirect_during_preview': True, 'feed_member_gate_removed': True, 'home_members_native_recovery': True, 'local_storage_contact_merge_disabled': True, 'apk_required_for_this_fix': False}

@app.get('/api/diagnostics/file_preview_v249406')
def api_file_preview_v249406():
    return {'ok': True, 'version': 'V249406-final-after-defer-preview-home-guard', 'script': 'final_guard_v249406.js', 'defer_last': True, 'globalFile_required': False, 'heavy_studio_disabled': True, 'object_url_before_upload': False, 'preview_home_redirect_guard': True}
# END V249406_FINAL_AFTER_DEFER_PREVIEW_HOME_GUARD
"""
relay.write_text(r,encoding='utf-8')
print('PATCH_SERVER_V249406=OK')
