foukoapi 0.1.0-alpha.1

Cross-platform bot framework in Rust. Write your handlers once, run the same bot on Telegram and Discord with shared accounts, embeds, keyboards and SQLite storage.
Documentation
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
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
//! The [`Bot`] builder and its runtime.

use crate::{
    accounts::Accounts,
    adapters,
    command::{Command, Handler},
    error::{Error, Result},
    platform::{Platform, PlatformConfig},
    Ctx,
};
use futures::future::{self, BoxFuture};
use std::{collections::HashMap, future::Future, sync::Arc};

/// The main entry point.
///
/// Build one with [`Bot::new`], add platforms and commands with the
/// chainable methods, then call [`Bot::run`].
///
/// ```no_run
/// use foukoapi::{Bot, Platform};
///
/// # async fn run() -> foukoapi::Result<()> {
/// Bot::new()
///     .add_platform(Platform::telegram("123:abc"))
///     .command("/help", |ctx| async move {
///         ctx.reply("hi").await
///     })
///     .run()
///     .await
/// # }
/// ```
#[must_use = "a Bot does nothing until you call .run().await on it"]
pub struct Bot {
    platforms: Vec<Platform>,
    commands: HashMap<String, CommandSlot>,
    /// Plain-text triggers (no leading `/`). Matched case-insensitively in
    /// registration order.
    text_commands: Vec<TextSlot>,
    fallback: Option<Handler>,
    /// Runs for every incoming message (after command dispatch), useful for
    /// XP counters and logging. It never answers the user - just observes.
    on_message: Vec<Handler>,
    /// Handle to the account helper. When set, built-in helpers like
    /// [`Bot::with_default_lang_command`] and the i18n-aware
    /// [`Bot::with_default_help`] can read/write per-user language.
    accounts: Option<Accounts>,
}

#[derive(Clone)]
struct TextSlot {
    pattern: String,
    matcher: TextMatch,
    handler: Handler,
}

/// How a text-trigger matches an incoming message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextMatch {
    /// The whole message (trimmed) equals the pattern, case-insensitive.
    Exact,
    /// The message starts with the pattern (trimmed, case-insensitive).
    Prefix,
    /// The pattern appears anywhere in the message, case-insensitive.
    Contains,
}

#[derive(Clone)]
struct CommandSlot {
    handler: Handler,
    /// `None` means "runs on every platform".
    platforms: Option<Vec<crate::PlatformKind>>,
    /// Default-language description. Shown by the auto-generated `/help`
    /// when nothing else matches the user's language.
    description: Option<String>,
    /// Per-language descriptions keyed by lang code (e.g. `"en"`, `"ru"`).
    /// Populated by [`Bot::command_described_i18n`].
    descriptions_i18n: HashMap<String, String>,
}

impl Bot {
    /// Start a fresh, empty bot.
    pub fn new() -> Self {
        Self {
            platforms: Vec::new(),
            commands: HashMap::new(),
            text_commands: Vec::new(),
            fallback: None,
            on_message: Vec::new(),
            accounts: None,
        }
    }

    /// Hand the bot a ready-made [`Accounts`] so that built-in helpers
    /// (like [`Bot::with_default_lang_command`] and i18n in
    /// [`Bot::with_default_help`]) can read per-user preferences.
    ///
    /// You typically still keep your own clone of `Accounts` for your
    /// handlers - this call is just `.clone()` under the hood.
    pub fn with_accounts(mut self, accounts: Accounts) -> Self {
        self.accounts = Some(accounts);
        self
    }

    /// Attach another platform to this bot. Every registered command runs
    /// on every attached platform.
    pub fn add_platform(mut self, platform: Platform) -> Self {
        self.platforms.push(platform);
        self
    }

    /// Register a command handler.
    ///
    /// `name` is the trigger including the leading slash (`"/help"`, `"/roll"`).
    /// The handler is any async closure taking a [`Ctx`].
    pub fn command<F, Fut>(mut self, name: impl Into<String>, handler: F) -> Self
    where
        F: Fn(Ctx) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.commands.insert(
            name.into(),
            CommandSlot {
                handler: Handler::new(handler),
                platforms: None,
                description: None,
                descriptions_i18n: HashMap::new(),
            },
        );
        self
    }

    /// Register a command and attach a short human description (used by
    /// the auto-generated `/help`).
    pub fn command_described<F, Fut>(
        mut self,
        name: impl Into<String>,
        description: impl Into<String>,
        handler: F,
    ) -> Self
    where
        F: Fn(Ctx) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.commands.insert(
            name.into(),
            CommandSlot {
                handler: Handler::new(handler),
                platforms: None,
                description: Some(description.into()),
                descriptions_i18n: HashMap::new(),
            },
        );
        self
    }

    /// Register a command with per-language descriptions.
    ///
    /// `descriptions` maps a lang code (e.g. `"en"`, `"ru"`) to the short
    /// description that [`Bot::with_default_help`] should show when the
    /// user is on that language. The first entry is also used as the
    /// default description (shown when the user's language isn't in the
    /// map).
    ///
    /// ```no_run
    /// use foukoapi::Bot;
    /// use std::collections::HashMap;
    ///
    /// let mut descs = HashMap::new();
    /// descs.insert("en".to_string(), "flip a coin".to_string());
    /// descs.insert("ru".to_string(), "подбросить монетку".to_string());
    ///
    /// Bot::new().command_described_i18n("/coin", descs, |ctx| async move {
    ///     ctx.reply("heads").await
    /// });
    /// ```
    pub fn command_described_i18n<F, Fut>(
        mut self,
        name: impl Into<String>,
        descriptions: HashMap<String, String>,
        handler: F,
    ) -> Self
    where
        F: Fn(Ctx) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        // Pick a default: prefer "en", otherwise any value in the map.
        let default = descriptions
            .get("en")
            .cloned()
            .or_else(|| descriptions.values().next().cloned());
        self.commands.insert(
            name.into(),
            CommandSlot {
                handler: Handler::new(handler),
                platforms: None,
                description: default,
                descriptions_i18n: descriptions,
            },
        );
        self
    }

    /// Restrict the last registered command to only run on `platforms`.
    pub fn only_on(mut self, name: &str, platforms: &[crate::PlatformKind]) -> Self {
        if let Some(slot) = self.commands.get_mut(name) {
            slot.platforms = Some(platforms.to_vec());
        }
        self
    }

    /// Run `handler` on every incoming message, regardless of command.
    /// Useful for XP counters and audit logging.
    pub fn on_message<F, Fut>(mut self, handler: F) -> Self
    where
        F: Fn(Ctx) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.on_message.push(Handler::new(handler));
        self
    }

    /// Register a text-trigger (no leading `/`). Matches run after slash
    /// commands: if the user typed `/help`, slash dispatch wins. Only when
    /// the message isn't a slash command do text triggers fire.
    pub fn text_command<F, Fut>(
        mut self,
        pattern: impl Into<String>,
        matcher: TextMatch,
        handler: F,
    ) -> Self
    where
        F: Fn(Ctx) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.text_commands.push(TextSlot {
            pattern: pattern.into().to_lowercase(),
            matcher,
            handler: Handler::new(handler),
        });
        self
    }

    /// Register a built-in `/help` that lists every described command.
    ///
    /// When an [`Accounts`] has been attached via
    /// [`Bot::with_accounts`], the generated help picks a per-language
    /// description for each command (from
    /// [`Bot::command_described_i18n`]) and a localised header, so a
    /// Russian user sees `команды:` and Russian summaries while an
    /// English user keeps the default.
    pub fn with_default_help(self) -> Self {
        // Snapshot (name, default_desc, i18n_map) for every described
        // command, so the `/help` closure can pick the right one at
        // dispatch time without holding a lock on `self`.
        let snapshot: Vec<(String, Option<String>, HashMap<String, String>)> = self
            .commands
            .iter()
            .filter(|(_, slot)| slot.description.is_some() || !slot.descriptions_i18n.is_empty())
            .map(|(name, slot)| {
                (
                    name.clone(),
                    slot.description.clone(),
                    slot.descriptions_i18n.clone(),
                )
            })
            .collect();
        let accounts = self.accounts.clone();
        self.command("/help", move |ctx| {
            let snapshot = snapshot.clone();
            let accounts = accounts.clone();
            async move {
                // Figure out the user's language. Falls back to "en" when
                // we have no accounts handle or the lookup fails.
                let lang = match &accounts {
                    Some(a) => a
                        .lang_for(ctx.platform(), ctx.user_id())
                        .await
                        .unwrap_or_else(|_| "en".to_owned()),
                    None => "en".to_owned(),
                };
                let header = match lang.as_str() {
                    "ru" => "команды:",
                    _ => "commands:",
                };
                let mut body = String::from(header);
                body.push('\n');
                let mut sorted = snapshot;
                sorted.sort_by(|a, b| a.0.cmp(&b.0));
                for (name, default_desc, i18n) in sorted {
                    let desc = i18n
                        .get(&lang)
                        .cloned()
                        .or(default_desc)
                        .unwrap_or_default();
                    if desc.is_empty() {
                        body.push_str(&format!("  {name}\n"));
                    } else {
                        body.push_str(&format!("  {name}  -  {desc}\n"));
                    }
                }
                ctx.reply(body.trim_end()).await
            }
        })
    }

    /// Register a built-in `/lang` command with inline buttons.
    ///
    /// No argument: shows the current language plus a button for every
    /// language in `supported`. Tapping a button switches instantly -
    /// no typing `/lang ru` needed. Typing `/lang ru` still works for
    /// users on clients without inline keyboards.
    ///
    /// Callback ids used: `foukoapi:lang:<code>`. They don't clash with
    /// anything the bot defines itself.
    ///
    /// Requires [`Bot::with_accounts`] to have been called - without an
    /// [`Accounts`] the command politely says so.
    pub fn with_default_lang_command<I, S>(self, supported: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        // `foukoapi:lang:<invoker>:<code>` - we glue the invoker user id
        // into the callback so only the person who ran `/lang` can press
        // a button that was meant for them.
        const CB_PREFIX: &str = "foukoapi:lang:";

        let supported: Vec<String> = supported
            .into_iter()
            .map(|s| s.into().to_ascii_lowercase())
            .collect();
        let accounts = self.accounts.clone();
        self.command_described(
            "/lang",
            "switch language, e.g. /lang ru",
            move |ctx| {
                let accounts = accounts.clone();
                let supported = supported.clone();
                async move {
                    let Some(accounts) = accounts else {
                        return ctx
                            .reply(
                                "language switching is not wired up on this bot (the author forgot to call Bot::with_accounts)",
                            )
                            .await;
                    };

                    // Button press: `foukoapi:lang:<invoker>:<code>`.
                    // Parse out both parts and, if we have an invoker id,
                    // make sure it matches the tapping user.
                    let (requested, invoker): (Option<String>, Option<String>) =
                        if let Some(data) = ctx.callback_data() {
                            if let Some(rest) = data.strip_prefix(CB_PREFIX) {
                                let mut parts = rest.splitn(2, ':');
                                let invoker = parts.next().map(|s| s.to_owned());
                                let code = parts.next().map(|s| s.to_ascii_lowercase());
                                (code, invoker)
                            } else {
                                (None, None)
                            }
                        } else {
                            let arg = ctx.args().trim().to_ascii_lowercase();
                            if arg.is_empty() {
                                (None, None)
                            } else {
                                (Some(arg), None)
                            }
                        };

                    // Invoker guard: if this is a button press and the
                    // tap came from someone else, reject quietly. The
                    // "someone else" case is common in group chats.
                    if let Some(inv) = invoker.as_deref() {
                        if !inv.is_empty() && inv != ctx.user_id() {
                            let lang_now = accounts
                                .lang_for(ctx.platform(), ctx.user_id())
                                .await
                                .unwrap_or_else(|_| "en".into());
                            let msg = match lang_now.as_str() {
                                "ru" => "эта кнопка не для тебя",
                                _ => "this button isn't for you",
                            };
                            return ctx.reply(msg).await;
                        }
                    }

                    let current = accounts
                        .lang_for(ctx.platform(), ctx.user_id())
                        .await
                        .unwrap_or_else(|_| "en".into());

                    match requested {
                        None => {
                            // Show the picker. Embed the invoker id in
                            // every callback id so follow-up taps can be
                            // gated to the same user.
                            let body = match current.as_str() {
                                "ru" => format!(
                                    "текущий язык: {current}\nвыбери язык:"
                                ),
                                _ => format!(
                                    "current language: {current}\npick a language:"
                                ),
                            };
                            if supported.is_empty() {
                                return ctx.reply(body).await;
                            }
                            let invoker_id = ctx.user_id().to_owned();
                            let kb =
                                build_lang_keyboard(&supported, &current, &invoker_id, CB_PREFIX);
                            ctx.reply_with(crate::Reply::text(body).keyboard(kb)).await
                        }
                        Some(code) => {
                            if !supported.is_empty() && !supported.contains(&code) {
                                let list = supported.join(", ");
                                let msg = match current.as_str() {
                                    "ru" => format!("поддерживаемые языки: {list}"),
                                    _ => format!("supported languages: {list}"),
                                };
                                return ctx.reply(msg).await;
                            }
                            accounts
                                .set_lang(ctx.platform(), ctx.user_id(), &code)
                                .await?;

                            // Re-render the picker with the new pick
                            // marked. When this is a button press we
                            // edit the original message; when it was a
                            // typed `/lang ru`, edit_reply falls back
                            // to a fresh message.
                            let invoker_id = ctx.user_id().to_owned();
                            let body = match code.as_str() {
                                "ru" => format!(
                                    "язык: {code} \u{2705}\nвыбери другой:"
                                ),
                                _ => format!(
                                    "language set to {code} \u{2705}\npick another:"
                                ),
                            };
                            if supported.is_empty() {
                                return ctx.edit_reply(body).await;
                            }
                            let kb =
                                build_lang_keyboard(&supported, &code, &invoker_id, CB_PREFIX);
                            ctx.edit_reply(crate::Reply::text(body).keyboard(kb)).await
                        }
                    }
                }
            },
        )
    }

    /// Register a built-in `/link` command with inline buttons.
    ///
    /// What the user gets:
    ///
    /// - `/link` with no arguments, not linked yet: issues a 6-char code
    ///   and shows a **cancel** button.
    /// - `/link` when already linked: shows both identities + current
    ///   primary, with **pick primary** and **unlink** buttons.
    /// - `/link CODE`: redeems a code issued on another platform (through
    ///   [`Accounts::redeem_link`]) and shows the primary-picker buttons.
    /// - Button presses are routed back through the same `/link` handler,
    ///   so the whole dance lives on one command.
    ///
    /// Works in English and Russian out of the box. The button-callback
    /// ids used internally start with `foukoapi:link:` so they don't clash
    /// with anything the bot defines itself.
    ///
    /// Requires [`Bot::with_accounts`] to have been called.
    pub fn with_default_link_command(self) -> Self {
        const CB_UNLINK: &str = "foukoapi:link:unlink";
        const CB_CANCEL: &str = "foukoapi:link:cancel";
        const CB_PRIMARY_ME: &str = "foukoapi:link:primary_me";
        const CB_PRIMARY_PARTNER: &str = "foukoapi:link:primary_partner";

        let mut descs = HashMap::new();
        descs.insert(
            "en".to_owned(),
            "Link or unlink accounts across platforms".to_owned(),
        );
        descs.insert(
            "ru".to_owned(),
            "Связать или отвязать аккаунты между платформами".to_owned(),
        );

        let accounts = self.accounts.clone();
        self.command_described_i18n("/link", descs, move |ctx| {
            let accounts = accounts.clone();
            async move {
                let Some(accounts) = accounts else {
                    return ctx
                        .reply(
                            "account linking is not wired up on this bot (the author forgot to call Bot::with_accounts)",
                        )
                        .await;
                };
                let lang = accounts
                    .lang_for(ctx.platform(), ctx.user_id())
                    .await
                    .unwrap_or_else(|_| "en".into());

                // DM-only guard. `/link` juggles short-lived codes tied
                // to a specific account; running it in a public chat
                // would splash the code to every onlooker, which is a
                // recipe for someone else hijacking the link. Refuse
                // outside of direct messages.
                if !ctx.is_dm() {
                    let body = match lang.as_str() {
                        "ru" => "команда /link работает только в личке с ботом. открой переписку и попробуй снова.",
                        _ => "/link only works in a private chat with the bot. open the bot's DM and try again.",
                    };
                    return ctx.reply(body).await;
                }

                if let Some(data) = ctx.callback_data() {
                    return handle_link_callback(
                        &ctx,
                        &accounts,
                        data,
                        &lang,
                        CB_UNLINK,
                        CB_CANCEL,
                        CB_PRIMARY_ME,
                        CB_PRIMARY_PARTNER,
                    )
                    .await;
                }

                let arg = ctx.args().trim().to_owned();

                if arg.starts_with("foukoapi:link:") {
                    return handle_link_callback(
                        &ctx,
                        &accounts,
                        &arg,
                        &lang,
                        CB_UNLINK,
                        CB_CANCEL,
                        CB_PRIMARY_ME,
                        CB_PRIMARY_PARTNER,
                    )
                    .await;
                }

                if arg.is_empty() {
                    return link_status_reply(&ctx, &accounts, &lang, CB_UNLINK, CB_CANCEL)
                        .await;
                }

                match accounts
                    .redeem_link(&arg, ctx.platform(), ctx.user_id())
                    .await
                {
                    Ok(res) => {
                        let (title, body, footer) = match lang.as_str() {
                            "ru" => (
                                "\u{2705} Аккаунты связаны",
                                format!(
                                    "**{}** \u{2194} **{}**",
                                    platform_title(platform_of(&res.primary)),
                                    platform_title(platform_of(&res.partner))
                                ),
                                "Выбери основной аккаунт. На нём остаются XP, монеты и настройки. Выбор делается **один раз** — потом поменять нельзя, можно только /link → Отвязать.",
                            ),
                            _ => (
                                "\u{2705} Accounts Linked",
                                format!(
                                    "**{}** \u{2194} **{}**",
                                    platform_title(platform_of(&res.primary)),
                                    platform_title(platform_of(&res.partner))
                                ),
                                "Pick the primary — XP, coins and settings live there. You can only pick **once**; after that, /link → Unlink is the only reset.",
                            ),
                        };
                        let me = format!("{}:{}", ctx.platform(), ctx.user_id());
                        let em = crate::Embed::new()
                            .title(title)
                            .description(body)
                            .footer(footer)
                            .color(LINK_COLOR);
                        let kb = primary_picker_keyboard(
                            &lang,
                            &me,
                            &res.partner,
                            CB_PRIMARY_ME,
                            CB_PRIMARY_PARTNER,
                        );
                        ctx.reply_with(crate::Reply::embed(em).keyboard(kb)).await
                    }
                    Err(e) => {
                        let (title, desc) = match lang.as_str() {
                            "ru" => ("\u{274C} Не получилось", format!("{e}")),
                            _ => ("\u{274C} Link Failed", format!("{e}")),
                        };
                        let em = crate::Embed::new()
                            .title(title)
                            .description(desc)
                            .color(ERROR_COLOR);
                        ctx.reply_with(crate::Reply::embed(em)).await
                    }
                }
            }
        })
    }

    /// Handler invoked when an incoming message starts with `/` but doesn't
    /// match any registered command. Optional.
    pub fn fallback<F, Fut>(mut self, handler: F) -> Self
    where
        F: Fn(Ctx) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.fallback = Some(Handler::new(handler));
        self
    }

    /// List registered commands as `Command` values.
    pub fn commands(&self) -> Vec<Command> {
        self.commands
            .iter()
            .map(|(name, slot)| Command::new(name.clone(), slot.handler.clone()))
            .collect()
    }

    /// Snapshot `(name, description)` for every registered command.
    /// Used by adapters (e.g. Discord) to register native slash-command
    /// metadata on the platform side.
    #[doc(hidden)]
    pub fn command_snapshot(&self) -> Vec<(String, Option<String>)> {
        self.commands
            .iter()
            .map(|(name, slot)| (name.clone(), slot.description.clone()))
            .collect()
    }

    /// Run the bot until every platform stops or the task is cancelled.
    pub async fn run(self) -> Result<()> {
        if self.platforms.is_empty() {
            return Err(Error::NoPlatforms);
        }

        // Snapshot the command metadata before we move `self.commands`
        // into the router - Discord adapter uses it to register native
        // slash commands with the platform so `/help` shows up in the
        // client's autocomplete list.
        let commands_meta: Vec<(String, Option<String>)> = self
            .commands
            .iter()
            .map(|(name, slot)| (name.clone(), slot.description.clone()))
            .collect();

        let router = Arc::new(Router {
            commands: self
                .commands
                .into_iter()
                .map(|(k, v)| {
                    (
                        k,
                        RouterSlot {
                            handler: v.handler,
                            platforms: v.platforms,
                        },
                    )
                })
                .collect(),
            text_commands: self
                .text_commands
                .into_iter()
                .map(|t| RouterTextSlot {
                    pattern: t.pattern,
                    matcher: t.matcher,
                    handler: t.handler,
                })
                .collect(),
            fallback: self.fallback,
            on_message: self.on_message,
        });

        let mut tasks: Vec<BoxFuture<'static, Result<()>>> = Vec::new();

        for platform in self.platforms {
            let router = Arc::clone(&router);
            let name = platform.kind.to_string();
            match platform.config {
                #[cfg(feature = "telegram")]
                PlatformConfig::Telegram { token } => {
                    tasks.push(Box::pin(async move {
                        adapters::telegram::run(token, router).await
                    }));
                }
                #[cfg(not(feature = "telegram"))]
                PlatformConfig::Telegram { .. } => {
                    tracing::warn!(
                        "Telegram platform configured but the `telegram` feature is off; skipping"
                    );
                }

                #[cfg(feature = "discord")]
                PlatformConfig::Discord { token } => {
                    let cmds = commands_meta.clone();
                    tasks.push(Box::pin(async move {
                        adapters::discord::run(token, router, cmds).await
                    }));
                }
                #[cfg(not(feature = "discord"))]
                PlatformConfig::Discord { .. } => {
                    tracing::warn!(
                        "Discord platform configured but the `discord` feature is off; skipping"
                    );
                }
            }
            tracing::info!(platform = %name, "adapter registered");
        }

        if tasks.is_empty() {
            return Err(Error::NoPlatforms);
        }

        // Run every adapter concurrently. The whole bot stops as soon as one
        // of them returns - successfully or otherwise.
        let (result, _, _rest) = future::select_all(tasks).await;
        result
    }
}

impl Default for Bot {
    fn default() -> Self {
        Self::new()
    }
}

/// Turn a callback-button id into the slash-command name that should
/// handle it.
///
/// Convention:
/// - `foukoapi:<cmd>:<rest>` -> `/<cmd>` (built-in API commands)
/// - `<cmd>:<rest>`          -> `/<cmd>` (bot-defined commands)
/// - anything else           -> `None`
///
/// Returning `None` just means "I don't know, let the router fall
/// through to the usual text/fallback paths".
fn callback_to_command(data: &str) -> Option<String> {
    let first = data.split(':').next()?;
    // Unwrap the API-owned prefix so `foukoapi:link:me` also resolves to
    // `/link`, not to `/foukoapi`.
    let cmd = if first == "foukoapi" {
        data.split(':').nth(1)?
    } else {
        first
    };
    if cmd.is_empty() {
        return None;
    }
    Some(format!("/{cmd}"))
}

/// Build the `/lang` inline keyboard: one row of up to 3 buttons per
/// chunk, the current language marked with a star.
fn build_lang_keyboard(
    supported: &[String],
    current: &str,
    invoker_id: &str,
    cb_prefix: &str,
) -> crate::Keyboard {
    let mut kb = crate::Keyboard::new();
    for chunk in supported.chunks(3) {
        let row: Vec<crate::Button> = chunk
            .iter()
            .map(|code| {
                let marker = if code == current { "\u{2B50} " } else { "" };
                let label = format!("{marker}{}", lang_label(code));
                crate::Button::callback(label, format!("{cb_prefix}{invoker_id}:{code}"))
            })
            .collect();
        kb = kb.row(row);
    }
    kb
}

/// Pretty label for a language code, with a flag-ish prefix.
///
/// Covers the handful of codes most bots care about; anything unknown
/// falls back to the upper-cased code so the picker still shows
/// *something*.
fn lang_label(code: &str) -> String {
    match code {
        "en" => "\u{1F1FA}\u{1F1F8} English".to_owned(),
        "ru" => "\u{1F1F7}\u{1F1FA} Русский".to_owned(),
        "uk" => "\u{1F1FA}\u{1F1E6} Українська".to_owned(),
        "de" => "\u{1F1E9}\u{1F1EA} Deutsch".to_owned(),
        "fr" => "\u{1F1EB}\u{1F1F7} Français".to_owned(),
        "es" => "\u{1F1EA}\u{1F1F8} Español".to_owned(),
        "it" => "\u{1F1EE}\u{1F1F9} Italiano".to_owned(),
        "pt" => "\u{1F1F5}\u{1F1F9} Português".to_owned(),
        "pl" => "\u{1F1F5}\u{1F1F1} Polski".to_owned(),
        "tr" => "\u{1F1F9}\u{1F1F7} Türkçe".to_owned(),
        "ja" => "\u{1F1EF}\u{1F1F5} 日本語".to_owned(),
        "zh" => "\u{1F1E8}\u{1F1F3} 中文".to_owned(),
        "ko" => "\u{1F1F0}\u{1F1F7} 한국어".to_owned(),
        other => other.to_ascii_uppercase(),
    }
}

// ---------------------------------------------------------------------------
// Built-in `/link` helpers, shared by `with_default_link_command`.
// ---------------------------------------------------------------------------

/// Accent colours used by the built-in `/link` embeds on Discord.
/// Ignored on Telegram/Matrix where there's nothing to paint.
const LINK_COLOR: u32 = 0x5B8DEF;
const ERROR_COLOR: u32 = 0xE74C3C;

/// Pretty platform name for an identity of the form `"platform:id"`.
///
/// Used by `/link` and friends to surface "telegram" / "discord" in
/// place of raw numeric ids, so the user doesn't have to squint at
/// `560024252393455645` to figure out which account is which.
fn platform_of(ident: &str) -> &str {
    ident.split(':').next().unwrap_or(ident)
}

/// Render the "linked or not" status screen with an unlink button.
async fn link_status_reply(
    ctx: &Ctx,
    accounts: &Accounts,
    lang: &str,
    cb_unlink: &str,
    cb_cancel: &str,
) -> Result<()> {
    let me = format!("{}:{}", ctx.platform(), ctx.user_id());
    let partner = accounts.partner_for(ctx.platform(), ctx.user_id()).await?;
    match partner {
        Some(p) => {
            let (title, platforms_label, foot) = match lang {
                "ru" => (
                    "\u{1F517} Связанные аккаунты",
                    "Платформы",
                    "Отвязать можно один раз. После отвязки у партнёрской платформы будет чистый профиль.",
                ),
                _ => (
                    "\u{1F517} Linked Accounts",
                    "Platforms",
                    "You can unlink once. After that the other side starts with a fresh profile.",
                ),
            };
            let em = crate::Embed::new()
                .title(title)
                .field(
                    platforms_label,
                    format!(
                        "**{}** \u{2194} **{}**",
                        platform_title(platform_of(&me)),
                        platform_title(platform_of(&p))
                    ),
                )
                .footer(foot)
                .color(LINK_COLOR);
            let kb = crate::Keyboard::new().row([crate::Button::callback(
                match lang {
                    "ru" => "\u{1F494} Отвязать",
                    _ => "\u{1F494} Unlink",
                },
                cb_unlink,
            )]);
            ctx.reply_with(crate::Reply::embed(em).keyboard(kb)).await
        }
        None => {
            let code = accounts.start_link(ctx.platform(), ctx.user_id()).await?;
            let (title, code_label, how_label, how_value, foot) = match lang {
                "ru" => (
                    "\u{1F517} Код привязки",
                    "Код",
                    "Как использовать",
                    format!("Открой бота на другой платформе и отправь:\n`/link {code}`"),
                    "Код живёт 5 минут.",
                ),
                _ => (
                    "\u{1F517} Link Code",
                    "Code",
                    "How To Use",
                    format!("Open the bot on another platform and send:\n`/link {code}`"),
                    "The code expires in 5 minutes.",
                ),
            };
            let em = crate::Embed::new()
                .title(title)
                .field(code_label, format!("`{code}`"))
                .field(how_label, how_value)
                .footer(foot)
                .color(LINK_COLOR);
            let kb = crate::Keyboard::new().row([crate::Button::callback(
                match lang {
                    "ru" => "\u{274C} Отмена",
                    _ => "\u{274C} Cancel",
                },
                cb_cancel,
            )]);
            ctx.reply_with(crate::Reply::embed(em).keyboard(kb)).await
        }
    }
}

/// Pretty, capitalised form of a platform id ("telegram" -> "Telegram").
fn platform_title(raw: &str) -> String {
    let mut chars = raw.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// Two "pick primary" buttons shown once, right after `/link CODE`.
fn primary_picker_keyboard(
    lang: &str,
    me: &str,
    partner: &str,
    cb_me: &str,
    cb_partner: &str,
) -> crate::Keyboard {
    let (me_label, partner_label) = match lang {
        "ru" => (
            format!("\u{1F4CD} Эта ({})", platform_title(platform_of(me))),
            format!(
                "\u{1F517} Другая ({})",
                platform_title(platform_of(partner))
            ),
        ),
        _ => (
            format!("\u{1F4CD} This ({})", platform_title(platform_of(me))),
            format!("\u{1F517} Other ({})", platform_title(platform_of(partner))),
        ),
    };
    crate::Keyboard::new().row([
        crate::Button::callback(me_label, cb_me),
        crate::Button::callback(partner_label, cb_partner),
    ])
}

/// Shared handler for every `foukoapi:link:*` button.
#[allow(clippy::too_many_arguments)]
async fn handle_link_callback(
    ctx: &Ctx,
    accounts: &Accounts,
    data: &str,
    lang: &str,
    cb_unlink: &str,
    cb_cancel: &str,
    cb_primary_me: &str,
    cb_primary_partner: &str,
) -> Result<()> {
    if data == cb_cancel {
        let (title, desc) = match lang {
            "ru" => (
                "\u{274C} Отменено",
                "Запусти /link ещё раз, когда будешь готов.",
            ),
            _ => (
                "\u{274C} Cancelled",
                "Run /link again whenever you're ready.",
            ),
        };
        let em = crate::Embed::new()
            .title(title)
            .description(desc)
            .color(ERROR_COLOR);
        return ctx.edit_reply(crate::Reply::embed(em)).await;
    }

    if data == cb_primary_me || data == cb_primary_partner {
        let me = format!("{}:{}", ctx.platform(), ctx.user_id());
        let partner = match accounts.partner_for(ctx.platform(), ctx.user_id()).await? {
            Some(p) => p,
            None => {
                let (title, desc) = match lang {
                    "ru" => ("\u{2753} Нет связки", "Сначала выполни /link CODE."),
                    _ => ("\u{2753} No Link", "Redeem a /link CODE first."),
                };
                let em = crate::Embed::new()
                    .title(title)
                    .description(desc)
                    .color(ERROR_COLOR);
                return ctx.edit_reply(crate::Reply::embed(em)).await;
            }
        };

        // One-shot guard: once primary is picked, the lock key disables
        // further presses from either side.
        let lock_key = format!("foukoapi:link:primary_locked:{me}");
        let partner_lock = format!("foukoapi:link:primary_locked:{partner}");
        let already = accounts
            .storage_ref()
            .get(&lock_key)
            .await
            .ok()
            .flatten()
            .is_some()
            || accounts
                .storage_ref()
                .get(&partner_lock)
                .await
                .ok()
                .flatten()
                .is_some();
        if already {
            let (title, desc) = match lang {
                "ru" => (
                    "\u{1F512} Уже выбрано",
                    "Основная платформа уже зафиксирована. Поменять можно только через /link → Отвязать.",
                ),
                _ => (
                    "\u{1F512} Already Locked",
                    "The primary is already locked in. You can only change it via /link → Unlink.",
                ),
            };
            let em = crate::Embed::new()
                .title(title)
                .description(desc)
                .color(ERROR_COLOR);
            return ctx.edit_reply(crate::Reply::embed(em)).await;
        }

        let chosen = if data == cb_primary_me {
            me.clone()
        } else {
            partner.clone()
        };
        accounts
            .set_primary(ctx.platform(), ctx.user_id(), &chosen)
            .await?;
        let _ = accounts.storage_ref().set(&lock_key, "1").await;
        let _ = accounts.storage_ref().set(&partner_lock, "1").await;

        let (title, desc) = match lang {
            "ru" => (
                "\u{2705} Основная выбрана",
                format!(
                    "Основной аккаунт: **{}**. Поменять больше нельзя — только через /link → Отвязать.",
                    platform_title(platform_of(&chosen))
                ),
            ),
            _ => (
                "\u{2705} Primary Locked",
                format!(
                    "Primary: **{}**. It can't be changed anymore — use /link → Unlink to reset.",
                    platform_title(platform_of(&chosen))
                ),
            ),
        };
        let em = crate::Embed::new()
            .title(title)
            .description(desc)
            .color(LINK_COLOR);
        return ctx.edit_reply(crate::Reply::embed(em)).await;
    }

    if data == cb_unlink {
        let me = format!("{}:{}", ctx.platform(), ctx.user_id());
        let partner_before = accounts.partner_for(ctx.platform(), ctx.user_id()).await?;
        return match accounts.unlink(ctx.platform(), ctx.user_id()).await? {
            Some(partner) => {
                // Release the primary-lock markers on both sides.
                let _ = accounts
                    .storage_ref()
                    .del(&format!("foukoapi:link:primary_locked:{me}"))
                    .await;
                if let Some(p) = partner_before.as_deref() {
                    let _ = accounts
                        .storage_ref()
                        .del(&format!("foukoapi:link:primary_locked:{p}"))
                        .await;
                }
                let (title, desc) = match lang {
                    "ru" => (
                        "\u{1F494} Отвязано",
                        format!(
                            "Больше не связан с **{}**. Основная платформа сохраняет свой профиль, остальные — получают чистый.",
                            platform_title(platform_of(&partner))
                        ),
                    ),
                    _ => (
                        "\u{1F494} Unlinked",
                        format!(
                            "No longer linked to **{}**. The primary keeps its profile; the other side starts fresh.",
                            platform_title(platform_of(&partner))
                        ),
                    ),
                };
                let em = crate::Embed::new()
                    .title(title)
                    .description(desc)
                    .color(LINK_COLOR);
                ctx.edit_reply(crate::Reply::embed(em)).await
            }
            None => {
                let (title, desc) = match lang {
                    "ru" => ("\u{2753} Нечего отвязывать", "Связанного аккаунта нет."),
                    _ => ("\u{2753} Nothing To Unlink", "No partner was set."),
                };
                let em = crate::Embed::new()
                    .title(title)
                    .description(desc)
                    .color(ERROR_COLOR);
                ctx.reply_with(crate::Reply::embed(em)).await
            }
        };
    }

    Ok(())
}

/// Router used by platform adapters to dispatch incoming updates.
///
/// Not part of the public API surface end-users should rely on - it exists
/// mainly so adapters in [`crate::adapters`] can hold a typed handle to the
/// bot's commands. Treat it as semver-exempt.
#[doc(hidden)]
#[derive(Clone)]
pub struct Router {
    pub(crate) commands: HashMap<String, RouterSlot>,
    pub(crate) text_commands: Vec<RouterTextSlot>,
    pub(crate) fallback: Option<Handler>,
    pub(crate) on_message: Vec<Handler>,
}

#[doc(hidden)]
#[derive(Clone)]
pub(crate) struct RouterSlot {
    pub(crate) handler: Handler,
    pub(crate) platforms: Option<Vec<crate::PlatformKind>>,
}

#[doc(hidden)]
#[derive(Clone)]
pub(crate) struct RouterTextSlot {
    pub(crate) pattern: String,
    pub(crate) matcher: TextMatch,
    pub(crate) handler: Handler,
}

impl Router {
    /// Dispatch an incoming message. First runs every `on_message` hook
    /// (errors are logged, not propagated), then tries slash commands,
    /// then plain-text triggers, then the fallback.
    ///
    /// Button presses land here too: adapters populate
    /// [`Ctx::callback_data`] with the id of the pressed button. We route
    /// those to a command by convention - a callback id that looks like
    /// `foukoapi:link:me` or `something:xyz` is mapped to the command
    /// that "owns" it (`/link` and `/something`), so a single handler
    /// serves both typed text and inline taps.
    #[doc(hidden)]
    pub async fn dispatch(&self, ctx: Ctx) -> Result<()> {
        for hook in &self.on_message {
            if let Err(e) = hook.call(ctx.clone()).await {
                tracing::debug!(error = %e, "on_message hook error");
            }
        }

        // Button-callback path: try to find a command whose name matches
        // the callback prefix. Supports `<cmd>:<rest>` and the API-owned
        // `foukoapi:<cmd>:<rest>`. If we find a match, run its handler
        // and return; otherwise fall through to text dispatch.
        if let Some(data) = ctx.callback_data() {
            if let Some(cmd_name) = callback_to_command(data) {
                if let Some(slot) = self.commands.get(&cmd_name) {
                    if let Some(allowed) = &slot.platforms {
                        if !allowed.contains(&ctx.platform()) {
                            return Ok(());
                        }
                    }
                    return slot.handler.call(ctx).await;
                }
            }
        }

        let text = ctx.text().trim();

        // Slash commands first.
        if text.starts_with('/') {
            let cmd_word = text.split_whitespace().next().unwrap_or("");
            let cmd_clean = cmd_word.split('@').next().unwrap_or(cmd_word);
            if let Some(slot) = self.commands.get(cmd_clean) {
                if let Some(allowed) = &slot.platforms {
                    if !allowed.contains(&ctx.platform()) {
                        return Ok(());
                    }
                }
                return slot.handler.call(ctx).await;
            }
            if let Some(fallback) = &self.fallback {
                return fallback.call(ctx).await;
            }
            return Ok(());
        }

        // Plain-text triggers.
        let lower = text.to_lowercase();
        for slot in &self.text_commands {
            let hit = match slot.matcher {
                TextMatch::Exact => lower == slot.pattern,
                TextMatch::Prefix => lower.starts_with(&slot.pattern),
                TextMatch::Contains => lower.contains(&slot.pattern),
            };
            if hit {
                return slot.handler.call(ctx).await;
            }
        }

        Ok(())
    }
}