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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
class ButtonKit:
    """The Telegram button toolkit: inline builders, styles, and icons.

    One instance (``button_kit``) owns the custom button-type registry;
    the module-level functions below are backward-compatible aliases.
    """

    def __init__(self):
        self._registry = {}

    def _is_built_button(self, obj) -> bool:
        return isinstance(obj, (Button, TLObject))

    def _normalize_style(self, style):
        """Normalise a button style to a value ``Button.inline`` accepts."""
        if style is None:
            return None
        if isinstance(style, str):
            return _STYLE_MAP.get(style.lower())
        if isinstance(style, int) and not isinstance(style, bool):
            return _STYLE_MAP.get(style)
        return None

    def _normalize_icon(self, icon):
        """Normalise a button icon to a custom-emoji document id (``int``).

        The fork's ``KeyboardButtonStyle.icon`` field is a ``long`` holding the
        document id of the custom emoji shown inside the button. Anything that
        is not an int (or a digit string) becomes ``None`` so a bad icon never
        breaks TL serialisation at send time.
        """
        if icon is None or isinstance(icon, bool):
            return None
        if isinstance(icon, int):
            return icon
        if isinstance(icon, str) and icon.isdigit():
            return int(icon)
        if isinstance(icon, str):
            _icon = document_id_for(icon)
            return _icon if _icon else None
        return None

    def _fold_stylized(self, text: str) -> str:
        """Fold "stylized" small-caps / phonetic-extension Unicode letters (the
        section-header convention this codebase uses, e.g. ``"Aแด…แด…แดษดs"``,
        ``"ยซ Bแด€แด„แด‹"``) down to plain ASCII, purely so the keyword matcher below
        can still recognise them.

        These glyphs have no case-folding or decomposition mapping in Unicode -
        they're distinct IPA/phonetic-extension code points, not accented Latin
        letters - so ``str.lower()``/``unicodedata.normalize`` leave them alone.
        Their *character name* does encode the plain letter though
        (``U+1D05 LATIN LETTER SMALL CAPITAL D``), so that's what this walks.
        """
        out = []
        for ch in text:
            if ch.isascii():
                out.append(ch)
                continue
            try:
                name = unicodedata.name(ch)
            except ValueError:
                out.append(ch)
                continue
            if name.startswith("LATIN LETTER SMALL CAPITAL "):
                out.append(name.rsplit(" ", 1)[-1].lower())
            else:
                out.append(ch)
        return "".join(out)

    def _cbs_words(self, data):
        """Yield lowercase words found in *data*, segment by segment, in order.

        ``data`` is typically structured colon-model callback data
        (``"assistant:games:aki"`` -> ``"assistant"``, ``"games"``, ``"aki"``),
        but this also degrades gracefully for a plain (non-colon) callback
        string, a URL, or a switch-inline query - ``str.split(":")`` on a
        single-segment string is just ``[string]``, and stray punctuation inside
        a segment is stripped by the word regex.
        """
        if isinstance(data, bytes):
            data = data.decode("utf-8", "ignore")
        if data is None or isinstance(data, (int, float)):
            return
        for segment in str(data).lower().split(":"):
            yield from _WORD_RE.findall(segment)

    def _default_icon_name(self, text, data=None, type_hint=None, fallback=None):
        """Resolve a default icon *name* (a key of ``DEFAULT_ICON_UNICODE``) or ``None``.

        Precedence: callback-data (cbs) words first, in segment order - this is
        the primary source, since callback data is structured and stable while
        titles are free-form display text. Title words (folded to ASCII first,
        see :func:`_fold_stylized`) are a secondary source, checked only if no
        cbs word matched. A per-button-kind default (``type_hint``) is checked
        last, only for the handful of structurally-reliable kinds in
        :data:`_TYPE_ICON_NAMES`. If nothing matches at all, ``fallback`` (``None``
        by default) is returned - i.e. no icon, not a generic one.
        """
        for word in self._cbs_words(data):
            name = _WORD_ICON_NAMES.get(word)
            if name:
                return name
        for word in _WORD_RE.findall(self._fold_stylized(str(text or "")).lower()):
            name = _WORD_ICON_NAMES.get(word)
            if name:
                return name
        return _TYPE_ICON_NAMES.get(type_hint, fallback)

    def _has_icon_glyph(self, text: str) -> bool:
        """True if *text* already starts or ends with an emoji-like glyph
        (crude, avoids double-iconifying a caption such as ``"Close โŒ"``).

        The ``0x2190`` threshold (arrows block onward) deliberately sits above
        the stylized small-caps letters (``U+1D00``-``U+1D7F``) used across the
        codebase's captions, so those never count as icons.
        """
        stripped = text.strip() if text else ""
        if not stripped:
            return False
        return ord(stripped[0]) >= 0x2190 or ord(stripped[-1]) >= 0x2190

    def _resolve_button_icon(
        self, text, icon_elem, *, auto, data=None, type_hint=None, fallback=None
    ):
        """Resolve the final ``(text, style_icon_document_id)`` for one button.

        ``icon_elem`` is the button's own icon slot (an explicit id/digit-string
        or an icon-table name like ``"back"`` always wins over auto-selection;
        ``False`` force-disables auto-selection
        for just this button, overriding a truthy ``auto``). ``auto`` is the
        ``ikm(..., icon=True)`` / ``rkm(..., icon=True)`` call-level toggle.

        Matching precedence: explicit per-button ``icon_elem`` > cbs (callback
        data) keyword > title keyword > per-kind ``type_hint`` icon > no icon.
        See :func:`_default_icon_name`.
        """
        if icon_elem is False:
            return text, None
        # An icon-table *name* ("back", "close", โ€ฆ) is an explicit per-button
        # override too: prefix its emoji and use its document id directly.
        if (
            isinstance(icon_elem, str)
            and not icon_elem.isdigit()
            and icon_elem.lower() in DEFAULT_ICON_UNICODE
        ):
            name = icon_elem.lower()
        else:
            doc_id = self._normalize_icon(icon_elem)
            if doc_id is not None:
                return text, doc_id
            if not auto:
                return text, None
            name = self._default_icon_name(
                text, data=data, type_hint=type_hint, fallback=fallback
            )
            if name is None:
                return text, None
        emoji = DEFAULT_ICON_UNICODE.get(name)
        if emoji and not self._has_icon_glyph(text):
            text = f"{emoji} {text}"
        return text, TG_ANDROID_ICON_DOCUMENT_IDS.get(name)

    def register_button_type(self, name, factory=None):
        """Register a custom ``ikm``/``rkm`` tuple-form button kind.

        ``name`` is the string used as a tuple's 2nd element, e.g.
        ``("Text", name, ...)``. ``factory(text, val, btn_tuple)`` is called
        once per matching tuple and must return a built Telethon button (a
        ``Button`` helper instance or a raw TL ``KeyboardButton*`` object).
        ``val`` is the tuple's 3rd element (``None`` if absent); ``btn_tuple``
        is the full tuple, for factories that need later elements.

        Can be used directly or as a decorator::

            register_button_type("copy", my_factory)

            @register_button_type("copy")
            def my_factory(self, text, val, btn_tuple):
                ...

        Registering an already-used name replaces the previous factory. The
        built-in kinds (``"url"``, ``"user"``, ``"web_app"``, ``"switch_inline"``,
        ``"request_user"``/``"request_chat"``/``"request_broadcast"``, ``"auth"``,
        ``"buy"``, ``"game"``) are handled natively and are never looked up here.
        """
        key = str(name).lower()
        if factory is None:

            def _decorator(fn):
                self._registry[key] = fn
                return fn

            return _decorator
        self._registry[key] = factory
        return factory

    def _build_copy_button(self, text, val, btn_tuple):
        """Built-in ``"copy"`` registration: a copy-to-clipboard button.

        ``("Text", "copy", copy_text[, style[, icon]])``. Uses the native
        ``KeyboardButtonCopy`` TL type when this Telethon build ships it,
        otherwise degrades to an inline callback carrying the copy text.
        """
        copy_text = str(val) if val is not None else text
        style = btn_tuple[3] if len(btn_tuple) > 3 else None
        icon = btn_tuple[4] if len(btn_tuple) > 4 else None
        style, icon = self._normalize_style(style), self._normalize_icon(icon)
        cls = getattr(_types, "KeyboardButtonCopy", None)
        style_obj = Button._get_style(style, icon)
        if cls is not None:
            return cls(text=text, copy_text=copy_text, style=style_obj)
        inline_cls = getattr(_types, "KeyboardInlineButton", None)
        copy_type_cls = getattr(_types, "InlineButtonTypeCopy", None)
        if inline_cls is not None and copy_type_cls is not None:
            return inline_cls(
                text=text, type=copy_type_cls(copy_text=copy_text), style=style_obj
            )
        return Button.inline(text, data=copy_text.encode()[:64], style=style, icon=icon)

    def _build_toggle_button(self, text, val, btn_tuple):
        """Built-in ``"toggle"`` registration: an on/off inline callback button.

        ``("Text", "toggle", callback_data[, is_on[, style]])`` - prefixes the
        title with a checked/unchecked box depending on ``is_on``.
        """
        is_on = bool(btn_tuple[3]) if len(btn_tuple) > 3 else False
        style = self._normalize_style(btn_tuple[4] if len(btn_tuple) > 4 else None)
        box = "โ˜‘๏ธ" if is_on else "โฌœ"
        return Button.inline(f"{box} {text}", data=val, style=style)

    def request_peer_button(
        self,
        text,
        peer="user",
        *,
        button_id=1,
        max_quantity=1,
        style=None,
        icon=None,
        **peer_kwargs,
    ):
        """Build a raw ``KeyboardButtonRequestPeer`` TL button.

        ``peer`` is one of ``"user"`` / ``"chat"`` / ``"broadcast"`` (the
        ``"request_"``-prefixed ikm type names are also accepted). Extra keyword
        arguments are forwarded to the ``RequestPeerType*`` constructor, e.g.
        ``request_peer_button("Bots", "user", bot=True)`` or
        ``request_peer_button("Forums", "chat", forum=True)``.

        .. warning::
            Telegram only allows request-peer buttons in *reply keyboards*
            (they are not inline buttons - the fork's ``Button._is_inline`` does
            not list them). Sending one inside an inline markup will be rejected
            by Telegram with ``BUTTON_TYPE_INVALID``.

        Raises ``ValueError`` for an unknown peer kind and ``NotImplementedError``
        when the installed Telethon build lacks the request-peer TL types.
        """
        kind = str(peer).lower()
        if kind.startswith("request_"):
            kind = kind[len("request_") :]
        try:
            cls_name = _REQUEST_PEER_TYPES[kind]
        except KeyError:
            raise ValueError(
                f"Unknown request-peer type {peer!r}; "
                f"expected one of {sorted(_REQUEST_PEER_TYPES)}"
            ) from None
        peer_cls = getattr(_types, cls_name, None)
        button_cls = getattr(_types, "KeyboardButtonRequestPeer", None)
        if peer_cls is None:
            raise NotImplementedError(
                "This Telethon build does not provide the KeyboardButtonRequestPeer TL types"
            )
        style = self._normalize_style(style)
        icon = self._normalize_icon(icon)
        style_obj = (
            Button._get_style(style, icon)
            if (style is not None or icon is not None)
            else None
        )
        peer_type = peer_cls(**peer_kwargs)
        if button_cls is not None:
            return button_cls(
                text=text,
                button_id=button_id,
                peer_type=peer_type,
                max_quantity=max_quantity,
                style=style_obj,
            )
        keyboard_cls = getattr(_types, "KeyboardButton", None)
        request_type_cls = getattr(_types, "ButtonTypeRequestPeer", None)
        if keyboard_cls is None or request_type_cls is None:
            raise NotImplementedError(
                "This Telethon build does not provide request-peer keyboard types"
            )
        return keyboard_cls(
            text=text,
            type=request_type_cls(
                button_id=button_id,
                peer_type=peer_type,
                max_quantity=max_quantity,
            ),
            style=style_obj,
        )

    def web_app_button(self, text, url, *, style=None, icon=None, simple=False):
        """Build a web_app keyboard button with graceful degradation.

        By default builds a ``KeyboardButtonWebView`` (inline-keyboard web_app
        button that can send data back to the bot). Pass ``simple=True`` for a
        reply-keyboard ``KeyboardButtonSimpleWebView`` (opens the web app without
        the data round-trip).

        On Telethon builds that lack the raw web_app button types, this falls back
        to a ``Button.url`` button (so the link is still usable) or, if ``url`` is
        empty, to an inline callback button carrying the literal ``"web_app"``.
        """
        style = self._normalize_style(style)
        icon = self._normalize_icon(icon)
        style_obj = (
            Button._get_style(style, icon)
            if (style is not None or icon is not None)
            else None
        )

        cls = _SimpleWebViewButtonCls if simple else _WebViewButtonCls
        if cls is not None:
            if cls is getattr(_types, "KeyboardInlineButton", None):
                view_type = getattr(_types, "InlineButtonTypeWebView", None)
                if view_type is not None:
                    return cls(
                        text=text, type=view_type(url=url or ""), style=style_obj
                    )
            if cls is getattr(_types, "KeyboardButton", None):
                view_type = getattr(_types, "ButtonTypeSimpleWebView", None)
                if view_type is not None:
                    return cls(
                        text=text, type=view_type(url=url or ""), style=style_obj
                    )
            return cls(text=text, url=url or "", style=style_obj)

        if url:
            return Button.url(text, url=url, style=style, icon=icon)
        return Button.inline(text, data=b"web_app", style=style, icon=icon)

    def send_web_view_result_message(self, bot_query_id: str, result):
        """Build a ``SendWebViewResultMessageRequest`` TL request when available.

        ``result`` is an ``InputBotInlineResult`` object. Raises
        ``NotImplementedError`` on Telethon builds that lack this request.
        """
        cls = _SendWebViewResultMsgCls
        if cls is None:
            raise NotImplementedError(
                "This Telethon build does not provide SendWebViewResultMessageRequest"
            )
        return cls(bot_query_id=bot_query_id, result=result)

    def _web_app_button_from_tuple(self, text, btn_tuple, val, *, icon=None):
        """Shared parser for the ikm/rkm ``('text', 'web_app', url, ...)`` tuple forms.

        ``btn_tuple`` is the full tuple, ``val`` the URL in its 3rd element,
        ``icon`` the already-resolved style-icon document id (or ``None``).
        """
        simple = btn_tuple[1] in ("simple_web_app", "simple_webapp")
        style = btn_tuple[3] if len(btn_tuple) > 3 else None
        return self.web_app_button(
            text, val or "", style=style, icon=icon, simple=simple
        )

    def ids(self, inline_message_id: str) -> tuple:
        """
        Resolves an inline_message_id into (chat_id, message_id).
        Handles both normal and bot-API style packed IDs.
        """
        data = resolve_inline_message_id(inline_message_id)
        try:
            cid, mid = data.peer, data.id
        except AttributeError:
            cid, mid = struct.unpack(">ii", data.id.to_bytes(8, signed=True))

        if cid < 0 or cid >= MAX_CHANNEL_ID:
            cid = get_peer_id(abs(cid))

        return cid, mid

    def ikm(self, data: list, *, icon: bool = False):
        """
        Constructs an inline keyboard as a list-of-lists of Button objects.

        Telethon's send_message / reply / edit_message `buttons=` param accepts
        list-of-lists and serialises them internally. Do NOT return a pre-built
        ReplyInlineMarkup - that causes ReplyMarkupInvalidError.

        Pre-built Telethon button objects (``Button`` helper instances and raw
        ``KeyboardButton*`` TL objects) pass through untouched - nested inside a
        row, as a bare row, or as the whole input - and are detected positively
        before any tuple-spec len()/indexing happens.

        Supported tuple formats per button:
          (text, cb)                              โ†’ inline button
          (text, cb, style)                       โ†’ inline button with colour style
          (text, cb, style, icon)                 โ†’ inline button, colour + icon
          (text, "url", url)                      โ†’ URL button
          (text, "url", url, style[, icon])       โ†’ URL button with colour style
          (text, "switch_inline", query[, same_peer[, style[, icon]]])
                                                  โ†’ inline switch-to-inline-query button
          (text, "user", uid)                     โ†’ request-peer button when the
                                                    Telethon build supports it,
                                                    otherwise an inline fallback
          (text, "request_user"|"request_chat"|"request_broadcast", button_id[, max_quantity[, style[, icon]]])
                                                  โ†’ raw KeyboardButtonRequestPeer
                                                    (reply-keyboard contexts only)
          (text, "web_app", url)                  โ†’ inline web_app button
                                                    (KeyboardButtonWebView; falls
                                                    back to a URL button on older
                                                    Telethon builds)
          (text, "simple_webapp", url)            โ†’ reply-keyboard simple web_app
                                                    button (KeyboardButtonSimpleWebView)
          (text, name, ...)                       โ†’ any kind registered via
                                                    :func:`register_button_type`

        ``style`` may be one of the strings "default"/"primary"/"success"/"danger"
        or the matching Telegram Bot API integers 0/1/2/3. ``icon`` is a
        custom-emoji document id (int) or an icon-table name (``"back"``,
        ``"close"``, โ€ฆ) - an explicit value here always wins,
        ``False`` disables auto-selection for that one button. Both apply to
        inline AND url buttons (the fork styles both); unknown values degrade to
        the default look instead of raising.

        ``icon=True`` (default ``False``) turns on automatic icon selection for
        every button in this call that doesn't already have an explicit icon:
        a matching unicode emoji (see :data:`DEFAULT_ICON_UNICODE`) is prefixed
        onto the button title, and the matching :data:`TG_ANDROID_ICON_DOCUMENT_IDS`
        entry (if filled in) is used as the style icon. Matching precedence is
        per-button ``icon=`` element > callback-data keyword > title keyword >
        button-type keyword > no icon - there is no generic fallback icon, so
        turning this on is safe to do call-wide without spamming every unrelated
        button. See :func:`_default_icon_name` for the exact matching rules.

        The pinned fork has no ``Button.request_peer`` helper, so
        ``("โ€ฆ", "user", uid)`` deliberately produces an inline callback button
        whose data is the user id. The capability is probed once at import time
        (``_HAS_REQUEST_PEER``), so if the fork ever grows the helper the native
        button is used automatically. ``("โ€ฆ", "web_app", url)`` similarly probes
        ``_HAS_WEBVIEW_BUTTONS`` once at import.

        Usage:
          ikm([("Text", "cb")])
          ikm([[("A", "cb1"), ("B", "cb2")], [("C", "url", "https://...")]])
          ikm([("Confirm", "yes", "success"), ("Cancel", "no", "danger")])
          ikm([("Pick user", "request_user", 1)])
          ikm([("Open app", "web_app", "https://example.com/app")])
          ikm([("Back", "back")], icon=True)  # auto-prefixes "โ—€๏ธ Back"
        """
        auto_icon = icon

        # a bare top-level tuple or pre-built button is a single one-button row
        if isinstance(data, tuple) or self._is_built_button(data):
            data = [data]

        rows = []
        for row in data:
            current_row = []
            if isinstance(row, tuple) or self._is_built_button(row):
                row = [row]

            for btn in row:
                if self._is_built_button(btn):
                    current_row.append(btn)
                    continue

                if not isinstance(btn, (list, tuple)):
                    current_row.append(btn)
                    continue

                if len(btn) < 2:
                    continue

                text = btn[0]
                bt_type = btn[1]
                val = btn[2] if len(btn) > 2 else None

                if bt_type == "url":
                    # (text, "url", url[, style[, icon]])
                    style = btn[3] if len(btn) > 3 else None
                    icon_elem = btn[4] if len(btn) > 4 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, data=val, type_hint="url"
                    )
                    current_row.append(
                        Button.url(
                            text,
                            url=val or "",
                            style=self._normalize_style(style),
                            icon=icon_val,
                        )
                    )
                elif bt_type == "switch_inline":
                    # (text, "switch_inline", query[, same_peer[, style[, icon]]])
                    same_peer = bool(btn[3]) if len(btn) > 3 else False
                    style = btn[4] if len(btn) > 4 else None
                    icon_elem = btn[5] if len(btn) > 5 else None
                    text, icon_val = self._resolve_button_icon(
                        text,
                        icon_elem,
                        auto=auto_icon,
                        data=val,
                        type_hint="switch_inline",
                    )
                    current_row.append(
                        Button.switch_inline(
                            text,
                            query=val or "",
                            same_peer=same_peer,
                            style=self._normalize_style(style),
                            icon=icon_val,
                        )
                    )
                elif bt_type == "user":
                    text, _icon_val = self._resolve_button_icon(
                        text, None, auto=auto_icon, data=val, type_hint="user"
                    )
                    if _HAS_REQUEST_PEER:
                        current_row.append(
                            Button.request_peer(
                                text, button_id=val if isinstance(val, int) else 1
                            )
                        )
                    else:
                        current_row.append(
                            Button.inline(text, data=str(val or "user").encode()[:64])
                        )
                elif bt_type in ("request_user", "request_chat", "request_broadcast"):
                    # (text, "request_*", button_id[, max_quantity[, style[, icon]]])
                    icon_elem = btn[5] if len(btn) > 5 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint=bt_type
                    )
                    current_row.append(
                        self.request_peer_button(
                            text,
                            bt_type,
                            button_id=val if isinstance(val, int) else 1,
                            max_quantity=(
                                btn[3]
                                if len(btn) > 3 and isinstance(btn[3], int)
                                else 1
                            ),
                            style=btn[4] if len(btn) > 4 else None,
                            icon=icon_val,
                        )
                    )
                elif bt_type in (
                    "web_app",
                    "webapp",
                    "simple_web_app",
                    "simple_webapp",
                ):
                    icon_elem = btn[4] if len(btn) > 4 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, data=val, type_hint="web_app"
                    )
                    current_row.append(
                        self._web_app_button_from_tuple(text, btn, val, icon=icon_val)
                    )
                elif bt_type in ("auth", "buy", "game"):
                    icon_elem = btn[3] if len(btn) > 3 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint=bt_type
                    )
                    current_row.append(
                        Button.inline(
                            text,
                            data=(
                                (val or bt_type).encode()[:64]
                                if isinstance(val, str)
                                else val or bt_type.encode()
                            ),
                            icon=icon_val,
                        )
                    )
                else:
                    factory = (
                        self._registry.get(str(bt_type).lower())
                        if isinstance(bt_type, str)
                        else None
                    )
                    if factory is not None:
                        current_row.append(factory(text, val, btn))
                        continue
                    # (text, callback_data)  or  (text, callback_data, style[, icon])
                    # ``val`` is the 3rd element, i.e. the style for inline buttons.
                    icon_elem = btn[3] if len(btn) > 3 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, data=bt_type, type_hint=None
                    )
                    style = self._normalize_style(val)
                    if val is None and str(text).strip().casefold() == "back":
                        style = "primary"
                    current_row.append(
                        Button.inline(
                            text,
                            data=bt_type,
                            style=style,
                            icon=icon_val,
                        )
                    )

            if current_row:
                rows.append(current_row)

        return rows or None

    def rkm(
        self,
        data: list,
        *,
        icon: bool = False,
        resize: bool = None,
        single_use: bool = None,
        selective: bool = None,
        placeholder: str = None,
    ):
        """
        Constructs a reply keyboard (NOT inline) as a list-of-lists of Button objects.

        Sibling of :func:`ikm` for the button kinds that only exist in *reply*
        keyboards (plain text, request_location/phone/poll/peer, the "simple"
        web_app view). Same passthrough rules for pre-built buttons, same
        style/icon/registry handling, same tolerant defaults.

        Supported tuple formats per button:
          "Text"                                   โ†’ plain text button
          (text,)  or  (text, "text")               โ†’ plain text button
          (text, "text", style[, icon])             โ†’ plain text button, styled
          (text, "location")                        โ†’ request_location button
          (text, "phone")                           โ†’ request_phone button
          (text, "poll"[, quiz[, style[, icon]]])    โ†’ request_poll button
          (text, "user"|"request_user"|"chat"|"request_chat"|"broadcast"|"request_broadcast",
           button_id[, max_quantity[, style[, icon]]])
                                                     โ†’ raw KeyboardButtonRequestPeer
          (text, "web_app"|"simple_webapp", url)     โ†’ KeyboardButtonSimpleWebView
                                                      (the only web_app kind valid
                                                      inside a reply keyboard)
          (text, name, ...)                         โ†’ any kind registered via
                                                      :func:`register_button_type`
                                                      (shared registry with ``ikm``)

        ``icon=True`` enables the same default-icon auto-selection as ``ikm``
        (see :data:`DEFAULT_ICON_UNICODE`); an unrecognised tuple type falls
        back to a plain text button instead of raising.

        ``resize``/``single_use``/``selective``/``placeholder`` configure the
        resulting ``ReplyKeyboardMarkup`` the same way ``Button.text(...)``'s
        keyword arguments do - set them here once instead of on every button.
        They are honoured even when every button in the keyboard is a raw TL
        object (``request_peer_button()``, a ``simple_webapp`` button, ...)
        rather than a ``Button`` wrapper - this function wraps whatever it
        built so the options always survive serialisation.

        Usage:
          rkm(["Yes", "No"])
          rkm([("Share number", "phone")], resize=True)
          rkm([("Pick a user", "request_user", 1)], single_use=True)
        """
        auto_icon = icon

        if isinstance(data, (str, tuple)) or self._is_built_button(data):
            data = [data]

        rows = []
        for row in data:
            current_row = []

            if isinstance(row, (str, tuple)) or self._is_built_button(row):
                row = [row]

            for btn in row:
                if self._is_built_button(btn):
                    current_row.append(btn)
                    continue

                if isinstance(btn, str):
                    text, bt_type, val, btn = btn, "text", None, (btn, "text")
                elif isinstance(btn, (list, tuple)):
                    if len(btn) < 1:
                        continue
                    text = btn[0]
                    bt_type = btn[1] if len(btn) > 1 else "text"
                    val = btn[2] if len(btn) > 2 else None
                else:
                    current_row.append(btn)
                    continue

                if bt_type == "text":
                    # (text, "text", style[, icon]) - no ``val`` slot of its own.
                    style = btn[2] if len(btn) > 2 else None
                    icon_elem = btn[3] if len(btn) > 3 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint="text", fallback=None
                    )
                    current_row.append(
                        Button.text(
                            text, style=self._normalize_style(style), icon=icon_val
                        )
                    )
                elif bt_type in ("location", "request_location"):
                    style = btn[3] if len(btn) > 3 else None
                    icon_elem = btn[4] if len(btn) > 4 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint="location"
                    )
                    current_row.append(
                        Button.request_location(
                            text, style=self._normalize_style(style), icon=icon_val
                        )
                    )
                elif bt_type in ("phone", "request_phone"):
                    style = btn[3] if len(btn) > 3 else None
                    icon_elem = btn[4] if len(btn) > 4 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint="phone"
                    )
                    current_row.append(
                        Button.request_phone(
                            text, style=self._normalize_style(style), icon=icon_val
                        )
                    )
                elif bt_type in ("poll", "request_poll"):
                    quiz = bool(val) if len(btn) > 2 else False
                    style = btn[3] if len(btn) > 3 else None
                    icon_elem = btn[4] if len(btn) > 4 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint="poll"
                    )
                    current_row.append(
                        Button.request_poll(
                            text,
                            style=self._normalize_style(style),
                            icon=icon_val,
                            force_quiz=quiz,
                        )
                    )
                elif bt_type in (
                    "user",
                    "request_user",
                    "chat",
                    "request_chat",
                    "broadcast",
                    "request_broadcast",
                ):
                    icon_elem = btn[5] if len(btn) > 5 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint=bt_type
                    )
                    current_row.append(
                        self.request_peer_button(
                            text,
                            bt_type,
                            button_id=val if isinstance(val, int) else 1,
                            max_quantity=(
                                btn[3]
                                if len(btn) > 3 and isinstance(btn[3], int)
                                else 1
                            ),
                            style=btn[4] if len(btn) > 4 else None,
                            icon=icon_val,
                        )
                    )
                elif bt_type in (
                    "web_app",
                    "webapp",
                    "simple_web_app",
                    "simple_webapp",
                ):
                    # Only KeyboardButtonSimpleWebView is valid in reply keyboards.
                    icon_elem = btn[4] if len(btn) > 4 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, data=val, type_hint="web_app"
                    )
                    current_row.append(
                        web_app_button(
                            text,
                            val or "",
                            style=btn[3] if len(btn) > 3 else None,
                            icon=icon_val,
                            simple=True,
                        )
                    )
                else:
                    factory = (
                        self._registry.get(str(bt_type).lower())
                        if isinstance(bt_type, str)
                        else None
                    )
                    if factory is not None:
                        current_row.append(factory(text, val, btn))
                        continue
                    # Unrecognised kind: degrade to a plain text button rather
                    # than raising, matching ikm's tolerant style.
                    icon_elem = btn[3] if len(btn) > 3 else None
                    text, icon_val = self._resolve_button_icon(
                        text, icon_elem, auto=auto_icon, type_hint="text", fallback=None
                    )
                    current_row.append(Button.text(text, icon=icon_val))

            if current_row:
                rows.append(current_row)

        if rows and any(
            v is not None for v in (resize, single_use, selective, placeholder)
        ):
            for row in rows:
                for i, btn in enumerate(row):
                    if isinstance(btn, Button):
                        raw = btn.button
                        prev_resize, prev_single_use = btn.resize, btn.single_use
                        prev_selective, prev_placeholder = (
                            btn.selective,
                            btn.placeholder,
                        )
                        persistent = btn.persistent
                    elif isinstance(btn, TLObject):
                        raw = btn
                        prev_resize = prev_single_use = prev_selective = (
                            prev_placeholder
                        ) = None
                        persistent = None
                    else:
                        continue
                    row[i] = Button(
                        raw,
                        resize=resize if resize is not None else prev_resize,
                        single_use=(
                            single_use if single_use is not None else prev_single_use
                        ),
                        selective=(
                            selective if selective is not None else prev_selective
                        ),
                        persistent=persistent,
                        placeholder=(
                            placeholder if placeholder is not None else prev_placeholder
                        ),
                    )

        return rows or None


button_kit = ButtonKit()


def _is_built_button(*args, **kwargs):
    return button_kit._is_built_button(*args, **kwargs)


def _normalize_style(*args, **kwargs):
    return button_kit._normalize_style(*args, **kwargs)


def _normalize_icon(*args, **kwargs):
    return button_kit._normalize_icon(*args, **kwargs)


def _fold_stylized(*args, **kwargs):
    return button_kit._fold_stylized(*args, **kwargs)


def _cbs_words(*args, **kwargs):
    return button_kit._cbs_words(*args, **kwargs)


def _default_icon_name(*args, **kwargs):
    return button_kit._default_icon_name(*args, **kwargs)


def _has_icon_glyph(*args, **kwargs):
    return button_kit._has_icon_glyph(*args, **kwargs)


def _resolve_button_icon(*args, **kwargs):
    return button_kit._resolve_button_icon(*args, **kwargs)


def register_button_type(*args, **kwargs):
    return button_kit.register_button_type(*args, **kwargs)


def _build_copy_button(*args, **kwargs):
    return button_kit._build_copy_button(*args, **kwargs)


def _build_toggle_button(*args, **kwargs):
    return button_kit._build_toggle_button(*args, **kwargs)


def request_peer_button(*args, **kwargs):
    return button_kit.request_peer_button(*args, **kwargs)


def web_app_button(*args, **kwargs):
    return button_kit.web_app_button(*args, **kwargs)


def send_web_view_result_message(*args, **kwargs):
    return button_kit.send_web_view_result_message(*args, **kwargs)


def _web_app_button_from_tuple(*args, **kwargs):
    return button_kit._web_app_button_from_tuple(*args, **kwargs)


def ids(*args, **kwargs):
    return button_kit.ids(*args, **kwargs)


def ikm(*args, **kwargs):
    return button_kit.ikm(*args, **kwargs)


def rkm(*args, **kwargs):
    return button_kit.rkm(*args, **kwargs)


import logging
import re
import struct
import unicodedata

from telethon import Button
from telethon.tl import TLObject
from telethon.tl import functions as _functions
from telethon.tl import types as _types
from telethon.utils import get_peer_id, resolve_inline_message_id

from .icons import document_id_for

_LOGS = logging.getLogger(__name__)

MAX_CHANNEL_ID = -1000000000000


_STYLE_MAP = {
    # normal
    "default": None,
    "primary": "primary",
    "success": "success",
    "danger": "danger",
    # index
    0: None,
    1: "primary",
    2: "success",
    3: "danger",
    # by name
    "red": "danger",
    "green": "success",
    "blue": "primary",
}


DEFAULT_ICON_UNICODE = {
    "back": "โ—€๏ธ",
    "close": "โœ–๏ธ",
    "cancel": "๐Ÿšซ",
    "noop": "โ–ซ๏ธ",
    "copy": "๐Ÿ“‹",
    "next": "โžก๏ธ",
    "prev": "โฌ…๏ธ",
    "settings": "โš™๏ธ",
    "help": "โ“",
    "download": "โฌ‡๏ธ",
    "play": "โ–ถ๏ธ",
    "pause": "โธ๏ธ",
    "redirect": "๐Ÿ”—",
    "search": "๐Ÿ”",
    "person": "๐Ÿ‘ค",
    "game": "๐ŸŽฎ",
    "buy": "๐Ÿ’ณ",
    "lock": "๐Ÿ”’",
    "location": "๐Ÿ“",
    "phone": "๐Ÿ“ž",
    "poll": "๐Ÿ“Š",
    "lang": "๐ŸŒ",
    "home": "๐Ÿ ",
}

TG_ANDROID_ICON_DOCUMENT_IDS = {name: None for name in DEFAULT_ICON_UNICODE}

_WORD_ICON_NAMES = {name: name for name in DEFAULT_ICON_UNICODE}
_WORD_ICON_NAMES.update(
    {
        "previous": "prev",
        "games": "game",
        "language": "lang",
        "languages": "lang",
        "start": "home",
        "mainmenu": "home",
        "main": "home",
    }
)

_TYPE_ICON_NAMES = {
    "url": "redirect",
    "web_app": "redirect",
    "webapp": "redirect",
    "simple_web_app": "redirect",
    "simple_webapp": "redirect",
    "switch_inline": "search",
    "user": "person",
    "request_user": "person",
    "chat": "person",
    "request_chat": "person",
    "broadcast": "person",
    "request_broadcast": "person",
    "game": "game",
    "buy": "buy",
    "auth": "lock",
    "location": "location",
    "request_location": "location",
    "phone": "phone",
    "request_phone": "phone",
    "poll": "poll",
    "request_poll": "poll",
}

_WORD_RE = re.compile(r"[a-z]+")


_BUTTON_TYPE_REGISTRY = button_kit._registry


register_button_type("copy", _build_copy_button)
register_button_type("toggle", _build_toggle_button)


_HAS_REQUEST_PEER = hasattr(Button, "request_peer")
if _HAS_REQUEST_PEER:
    _LOGS.debug(
        "custom.tg: Button.request_peer available - 'user' buttons use native request-peer."
    )
else:
    _LOGS.debug(
        "custom.tg: Button.request_peer absent on this Telethon build - "
        "'user' buttons deliberately fall back to inline callback buttons "
        "carrying the user id as callback data."
    )

_REQUEST_PEER_TYPES = {
    "user": "RequestPeerTypeUser",
    "chat": "RequestPeerTypeChat",
    "broadcast": "RequestPeerTypeBroadcast",
}


_WebViewButtonCls = getattr(_types, "KeyboardButtonWebView", None) or getattr(
    _types, "KeyboardInlineButton", None
)
_SimpleWebViewButtonCls = getattr(_types, "KeyboardButtonSimpleWebView", None) or getattr(
    _types, "KeyboardButton", None
)
_WebViewDataSentCls = getattr(_types, "MessageActionWebViewDataSent", None)
_WebViewDataSentMeCls = getattr(_types, "MessageActionWebViewDataSentMe", None)
_WebViewResultSentCls = getattr(_types, "UpdateWebViewResultSent", None)
_WebViewResultUrlCls = getattr(_types, "WebViewResultUrl", None)
_SendWebViewResultMsgCls = getattr(
    _functions.messages, "SendWebViewResultMessageRequest", None
)

_HAS_WEBVIEW_BUTTONS = (
    _WebViewButtonCls is not None and _SimpleWebViewButtonCls is not None
)
_HAS_WEBVIEW_DATA_ACTIONS = (
    _WebViewDataSentCls is not None and _WebViewDataSentMeCls is not None
)
_HAS_WEBVIEW_RESULT_SENT = _WebViewResultSentCls is not None
_HAS_WEBVIEW_RESULT_MSG = _SendWebViewResultMsgCls is not None

if _HAS_WEBVIEW_BUTTONS:
    _LOGS.debug(
        "custom.tg: web_app button TL types available - "
        "('text', 'web_app', url) builds KeyboardButtonWebView."
    )
else:
    _LOGS.debug(
        "custom.tg: web_app button TL types absent on this Telethon build - "
        "web_app buttons deliberately fall back to URL/inline buttons."
    )