#!/usr/bin/env python3
from pathlib import Path
import shutil, sys
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)
if (src/'hard_preview_contact_v249404.js').is_file(): shutil.copy2(src/'hard_preview_contact_v249404.js', front/'js/hard_preview_contact_v249404.js')
html=front/'index.html'
s=html.read_text(encoding='utf-8')
s=s.replace('249403-desktop-safe-preview-contact-truth','249404-preview-home-members-recovery').replace('hard_preview_contact_v249403.js','hard_preview_contact_v249404.js')
if 'hard_preview_contact_v249404.js' not in s:
    tag='<script src="/js/hard_preview_contact_v249404.js?v=249404-preview-home-members-recovery"></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.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.404-preview-home-members-recovery')
    for old in ['249403-desktop-safe-preview-contact-truth','249402-hard-preview-contact-clean','249401-immediate-file-preview','249400-preview-friendship-consistency']:
        j=j.replace(old,'249404-preview-home-members-recovery')
    j=j.replace("const ITHAKI_BUILD_249318='249357';", "const ITHAKI_BUILD_249318='249404';")
    idx.write_text(j,encoding='utf-8')
relay=root/'relay_server_clean.py'
r=relay.read_text(encoding='utf-8')
for old in ['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.404-preview-home-members-recovery')
for old in ['249403-desktop-safe-preview-contact-truth','249402-hard-preview-contact-clean','249401-immediate-file-preview','249400-preview-friendship-consistency']:
    r=r.replace(old,'249404-preview-home-members-recovery')
if 'BEGIN V249404_PREVIEW_HOME_MEMBERS_RECOVERY' not in r:
    r += '\n# BEGIN V249404_PREVIEW_HOME_MEMBERS_RECOVERY\n# Recovery for preview selection and home members. No media/message/call/profile deletion.\n@app.get(\'/api/social/member_lists/v249404\')\ndef api_social_member_lists_v249404(room_id: str = Query(\'ithaki-phone-test\'), device_id: str = Query(\'\')):\n    init_social_v249223_db()\n    try: _v249402_dedupe_social(room_id)\n    except Exception: LOG.exception(\'V249404 cleanup skipped\')\n    device_id=str(device_id or \'\')[:120]\n    friends=_friend_rows_v249223(str(room_id or \'ithaki-phone-test\')[:120], device_id) if device_id else []\n    out=[]; seen=set()\n    for p in friends:\n        pid=str((p or {}).get(\'device_id\') or (p or {}).get(\'id\') or \'\')\n        if not pid or pid in seen or pid==device_id: continue\n        seen.add(pid); out.append(p)\n    return {\'ok\': True, \'version\': \'V249404-preview-home-members-recovery\', \'source\': \'server accepted friends only, no localStorage merge\', \'friends\': out, \'counts\': {\'friends\': len(out)}}\n\n@app.get(\'/api/diagnostics/file_preview_v249404\')\ndef api_file_preview_v249404():\n    return {\'ok\': True, \'version\': \'V249404-preview-home-members-recovery\', \'own_file_input\': True, \'uses_globalFile\': False, \'heavy_studio_disabled\': True, \'object_url_before_upload\': False, \'apk_required_for_this_fix\': False}\n\n@app.get(\'/api/diagnostics/home_members_v249404\')\ndef api_home_members_v249404(room_id: str = Query(\'ithaki-phone-test\'), device_id: str = Query(\'\')):\n    people=[]\n    try:\n        db=get_db()\n        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()\n        people=[dict(r) for r in rows]\n    except Exception:\n        people=[]\n    return {\'ok\': True, \'version\': \'V249404-preview-home-members-recovery\', \'room_id\': room_id, \'device_id\': device_id, \'people_count\': len(people), \'people\': people[:80]}\n\n@app.get(\'/api/diagnostics/v249404\')\ndef api_diagnostics_v249404(room_id: str = Query(\'ithaki-phone-test\'), device_id: str = Query(\'\')):\n    clean=_v249402_dedupe_social(room_id)\n    friends=[]\n    try:\n        friends=_friend_rows_v249223(str(room_id or \'ithaki-phone-test\')[:120], str(device_id or \'\')[:120]) if device_id else []\n    except Exception: pass\n    return {\'ok\': True, \'version\': \'V249404-preview-home-members-recovery\', \'own_file_input\': True, \'home_members_recovery\': True, \'server_only_friends\': True, \'friends_for_device\': len(friends), \'cleanup\': clean}\n# END V249404_PREVIEW_HOME_MEMBERS_RECOVERY\n'
relay.write_text(r,encoding='utf-8')
print('PATCH_SERVER_V249404=OK')
