# -*- coding: utf-8 -*-
from pathlib import Path
import re, sys
server = Path(sys.argv[1]).resolve()
relay = server / 'relay_server_clean.py'
if not relay.is_file(): raise SystemExit('relay_server_clean.py not found')
module = server / 'friendship_consistency_v249400.py'
if not module.is_file(): raise SystemExit('friendship_consistency_v249400.py not found')
text = relay.read_text(encoding='utf-8')
text = re.sub(r'^VERSION\s*=\s*["\'][^"\']+["\']', 'VERSION  = "2.4.9.400-preview-friendship-consistency"', text, count=1, flags=re.M)
marker = '# BEGIN V249400_PREVIEW_FRIENDSHIP_CONSISTENCY'
if marker not in text:
    text += r'''

# BEGIN V249400_PREVIEW_FRIENDSHIP_CONSISTENCY
from friendship_consistency_v249400 import install_friendship_consistency_v249400 as _install_friendship_consistency_v249400
_are_friends_v249400_impl, _friend_rows_v249400_impl, _friend_diag_v249400_impl = _install_friendship_consistency_v249400(
    one=one, rows=rows, execute=execute, now=now, person_lookup=_person_v249223,
)

# All existing message, call and member-list routes resolve these globals at request time.
def _are_friends_v249227(room_id: str, a: str, b: str) -> bool:
    return bool(_are_friends_v249400_impl(str(room_id or "ithaki-phone-test")[:120], str(a or "")[:120], str(b or "")[:120]))

def _friend_rows_v249223(room_id: str, device_id: str) -> list[dict]:
    return list(_friend_rows_v249400_impl(str(room_id or "ithaki-phone-test")[:120], str(device_id or "")[:120]))

@app.get("/api/diagnostics/preview_friendship_v249400")
def api_diagnostics_preview_friendship_v249400(
    room_id: str = Query("ithaki-phone-test"),
    device_id: str = Query(""),
    peer_id: str = Query(""),
):
    result = _friend_diag_v249400_impl(str(room_id or "ithaki-phone-test")[:120], str(device_id or "")[:120], str(peer_id or "")[:120])
    result.update({
        "preview_version": "V249400-single-chooser-native-return",
        "single_file_chooser_transaction": True,
        "android_native_return_callback": True,
        "friend_list_message_call_gate_unified": True,
        "database_deleted": False,
        "media_deleted": False,
    })
    return result
# END V249400_PREVIEW_FRIENDSHIP_CONSISTENCY
'''
relay.write_text(text, encoding='utf-8')
print('PATCH_SERVER_V249400=OK')
