#!/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 ['hard_preview_contact_v249405.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=s.replace('249404-preview-home-members-recovery','249405-remove-feed-gate-preview-diagnostic')
s=s.replace('hard_preview_contact_v249404.js','hard_preview_contact_v249405.js')
if 'hard_preview_contact_v249405.js' not in s:
    tag='<script src="/js/hard_preview_contact_v249405.js?v=249405-remove-feed-gate-preview-diagnostic"></script>\n'
    s=s.replace('</body>',tag+'</body>') if '</body>' in s else s+'\n'+tag
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.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.405-remove-feed-gate-preview-diagnostic')
    for old in ['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,'249405-remove-feed-gate-preview-diagnostic')
    j=j.replace("const ITHAKI_BUILD_249318='249404';", "const ITHAKI_BUILD_249318='249405';")
    j=j.replace("const ITHAKI_BUILD_249318='249357';", "const ITHAKI_BUILD_249318='249405';")
    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','V249405')}catch(e){} return false; }", t, flags=re.S)
        t=t.replace('V249386_MEMBER_FULLSCREEN_CONTAIN_GLOBAL_FRIEND_GATE','V249405_MEMBER_FULLSCREEN_NO_MEMBER_GATE')
        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.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.405-remove-feed-gate-preview-diagnostic')
for old in ['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,'249405-remove-feed-gate-preview-diagnostic')
if 'BEGIN V249405_REMOVE_FEED_GATE_PREVIEW_DIAGNOSTIC' not in r:
    r += '''\n# BEGIN V249405_REMOVE_FEED_GATE_PREVIEW_DIAGNOSTIC
# Removes feed member gate and adds diagnostics. No media/message/call/profile deletion.
@app.get('/api/social/member_lists/v249405')
def api_social_member_lists_v249405(room_id: str = Query('ithaki-phone-test'), device_id: str = Query('')):
    init_social_v249223_db()
    try: _v249402_dedupe_social(room_id)
    except Exception: LOG.exception('V249405 cleanup skipped')
    device_id=str(device_id or '')[:120]
    friends=_friend_rows_v249223(str(room_id or 'ithaki-phone-test')[:120], device_id) if device_id else []
    out=[]; seen=set()
    for p in friends:
        pid=str((p or {}).get('device_id') or (p or {}).get('id') or '')
        if not pid or pid in seen or pid==device_id: continue
        seen.add(pid); out.append(p)
    return {'ok': True, 'version': 'V249405-remove-feed-gate-preview-diagnostic', 'source': 'server accepted friends only, no localStorage merge', 'friends': out, 'counts': {'friends': len(out)}}

@app.get('/api/diagnostics/file_preview_v249405')
def api_file_preview_v249405():
    return {'ok': True, 'version': 'V249405-remove-feed-gate-preview-diagnostic', 'own_file_input': True, 'captures_foreign_file_inputs': True, 'uses_globalFile': False, 'heavy_studio_disabled': True, 'object_url_before_upload': False, 'blocks_home_redirect_during_preview': True, 'feed_member_gate_removed': True, 'apk_required_for_this_fix': False}

@app.get('/api/diagnostics/home_members_v249405')
def api_home_members_v249405(room_id: str = Query('ithaki-phone-test'), device_id: str = Query('')):
    people=[]
    try:
        db=get_db()
        rows=db.execute("SELECT device_id,nickname,avatar,last_seen FROM people WHERE room_id=? ORDER BY COALESCE(last_seen,0) DESC LIMIT 800", (room_id,)).fetchall()
        people=[dict(r) for r in rows]
    except Exception:
        people=[]
    return {'ok': True, 'version': 'V249405-remove-feed-gate-preview-diagnostic', 'room_id': room_id, 'device_id': device_id, 'people_count': len(people), 'people': people[:80]}

@app.get('/api/diagnostics/v249405')
def api_diagnostics_v249405(room_id: str = Query('ithaki-phone-test'), device_id: str = Query('')):
    clean=_v249402_dedupe_social(room_id)
    friends=[]
    try:
        friends=_friend_rows_v249223(str(room_id or 'ithaki-phone-test')[:120], str(device_id or '')[:120]) if device_id else []
    except Exception: pass
    return {'ok': True, 'version': 'V249405-remove-feed-gate-preview-diagnostic', 'feed_member_gate_removed': True, 'foreign_file_input_capture': True, 'preview_home_redirect_guard': True, 'home_members_recovery': True, 'server_only_friends': True, 'friends_for_device': len(friends), 'cleanup': clean}
# END V249405_REMOVE_FEED_GATE_PREVIEW_DIAGNOSTIC
'''
relay.write_text(r,encoding='utf-8')
print('PATCH_SERVER_V249405=OK')
