from pathlib import Path
import sys

relay = Path(sys.argv[1])
text = relay.read_text(encoding='utf-8')

text = text.replace('VERSION  = "2.4.9.389-secure-dm-android-foundation"', 'VERSION  = "2.4.9.390b-friend-identity-acceptance"', 1)
text = text.replace('VERSION = "2.4.9.389-secure-dm-android-foundation"', 'VERSION = "2.4.9.390b-friend-identity-acceptance"', 1)

legacy_bool = '    accepted = bool(payload.get("accepted", False))\n'
strict_bool = r'''
    raw_accepted = payload.get("accepted", False)
    if kind == "contact":
        if isinstance(raw_accepted, bool):
            accepted = raw_accepted
        elif isinstance(raw_accepted, (int, float)) and raw_accepted in (0, 1):
            accepted = bool(raw_accepted)
        else:
            accepted_text = str(raw_accepted or "").strip().casefold()
            if accepted_text in {"1", "true", "yes", "accept", "accepted", "approve", "ok"}:
                accepted = True
            elif accepted_text in {"0", "false", "no", "reject", "rejected", "deny", "decline"}:
                accepted = False
            else:
                raise HTTPException(400, "accepted must be a real boolean")
    else:
        accepted = bool(raw_accepted)
'''
if legacy_bool in text:
    text = text.replace(legacy_bool, strict_bool, 1)
elif 'raw_accepted = payload.get("accepted", False)' not in text:
    raise SystemExit('Could not patch legacy friend boolean handling safely')

old = '''    if not r:\n        raise HTTPException(404, "event not found")\n    if str(r["to_id"]) != device_id and str(r["from_id"]) != device_id:\n        raise HTTPException(403, "not your event")\n'''
new = '''    if not r:\n        raise HTTPException(404, "event not found")\n    if kind == "contact" and str(r["to_id"]) != device_id:\n        raise HTTPException(403, "only the intended recipient can accept or reject a friend request")\n    if kind != "contact" and str(r["to_id"]) != device_id and str(r["from_id"]) != device_id:\n        raise HTTPException(403, "not your event")\n'''
if old in text:
    text = text.replace(old, new, 1)
elif 'only the intended recipient can accept or reject a friend request' not in text:
    raise SystemExit('Could not patch legacy friend responder safely')

block = '''\n# BEGIN V249390_FRIEND_IDENTITY_ACCEPTANCE\ntry:\n    from friend_identity_v249390 import install_friend_identity_v249390 as _install_friend_identity_v249390\n    _install_friend_identity_v249390(\n        app,\n        one=one,\n        rows=rows,\n        execute=execute,\n        now=now,\n        push_notify_devices=push_notify_devices,\n        person_lookup=_person_v249223,\n        friend_request_handler=api_social_friend_request,\n        ws_notify=ws_notify,\n    )\nexcept Exception:\n    LOG.exception("V249390 friend identity/acceptance failed to install")\n# END V249390_FRIEND_IDENTITY_ACCEPTANCE\n'''
if '# BEGIN V249390_FRIEND_IDENTITY_ACCEPTANCE' not in text:
    text += block

relay.write_text(text, encoding='utf-8')
