foukoapi 0.1.2-alpha.2

Cross-platform bot framework in Rust: one codebase, many platforms. Shared accounts, embeds, keyboards, economy, i18n and pluggable storage; Telegram and Discord adapters included.
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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
//! Telegram adapter built on top of [`teloxide`].

use crate::{
    bot::Router,
    ctx::{ChatInfo, ChatInfoFn, Ctx},
    error::{Error, Result},
    keyboard::{AttachmentKind, ButtonKind, Reply},
    platform::PlatformKind,
};
use std::sync::Arc;
use teloxide::{
    payloads::{
        EditMessageTextSetters, SendAudioSetters, SendMessageSetters, SendPhotoSetters,
        SendVideoSetters,
    },
    prelude::*,
    types::{
        BotCommand, CallbackQuery, ChatId, InlineKeyboardButton, InlineKeyboardMarkup, InputFile,
        Message, MessageId, ParseMode, ReplyParameters, ThreadId,
    },
};

/// Start the Telegram adapter. Blocks until the long-poll loop stops.
///
/// `commands` is the list of `(name, description)` pairs the bot has
/// registered. The adapter publishes them via `setMyCommands` so they
/// show up in Telegram's command menu and autocomplete, mirroring how the
/// Discord adapter registers slash commands.
///
/// Honours the standard `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY`
/// environment variables. If any of them is set, the adapter routes its
/// Telegram API calls through that proxy - useful for regions where
/// `api.telegram.org` is blocked.
pub async fn run(
    token: String,
    router: Arc<Router>,
    commands: Vec<(String, Option<String>, bool)>,
    notifier: Option<crate::notifier::Notifier>,
    menu_web_app: Option<(String, String)>,
) -> Result<()> {
    tracing::info!("starting telegram adapter");
    let bot = build_bot(&token)?;

    // If a notifier is present, install a sender so background tasks can
    // push messages into any chat by id. Telegram just needs the chat id
    // as an i64, so we parse the string form back.
    if let Some(notifier) = &notifier {
        let bot_for_push = bot.clone();
        let send: crate::notifier::SendFn = std::sync::Arc::new(move |chat_id: String, reply| {
            let bot = bot_for_push.clone();
            Box::pin(async move {
                let id: i64 = chat_id
                    .parse()
                    .map_err(|_| Error::platform("telegram", format!("bad chat id {chat_id}")))?;
                send_tg_message(&bot, ChatId(id), None, None, reply)
                    .await
                    .map(|_| ())
            })
        });
        notifier
            .register(PlatformKind::Telegram, send.clone())
            .await;
        // On Telegram a private chat's id equals the user's id, so the
        // same sender doubles as the DM path.
        notifier.register_dm(PlatformKind::Telegram, send).await;

        // User lookup via getChat. Only works once the user has messaged
        // the bot at least once; before that Telegram answers "chat not
        // found", which maps to Ok(None).
        let bot_for_lookup = bot.clone();
        let lookup: crate::notifier::UserLookupFn = std::sync::Arc::new(move |user_id: String| {
            let bot = bot_for_lookup.clone();
            Box::pin(async move {
                let id: i64 = user_id
                    .parse()
                    .map_err(|_| Error::platform("telegram", format!("bad user id {user_id}")))?;
                match bot.get_chat(ChatId(id)).await {
                    Ok(chat) => Ok(Some(tg_display_name(&chat))),
                    Err(teloxide::RequestError::Api(teloxide::ApiError::ChatNotFound)) => Ok(None),
                    Err(e) => Err(Error::platform("telegram", e)),
                }
            })
        });
        notifier
            .register_user_lookup(PlatformKind::Telegram, lookup)
            .await;
    }

    // Publish the command menu. Telegram accepts lowercase ASCII names of
    // 1-32 chars made of letters, digits and underscores; anything else
    // (spaces, dashes) is dropped so a single odd entry can't fail the
    // whole call.
    let menu: Vec<BotCommand> = commands
        .iter()
        .filter_map(|(name, desc, _takes_user)| {
            let trimmed = name.trim_start_matches('/').to_ascii_lowercase();
            if !is_valid_tg_command(&trimmed) {
                return None;
            }
            // Telegram requires a non-empty description and caps it at 256
            // chars; fall back to the name when none was given.
            let description = desc
                .clone()
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| trimmed.clone());
            let description = truncate_chars(&description, 256);
            Some(BotCommand::new(trimmed, description))
        })
        .collect();
    if !menu.is_empty() {
        match bot.set_my_commands(menu).await {
            Ok(_) => tracing::info!("telegram: published command menu"),
            Err(e) => tracing::warn!(error = %e, "telegram: could not set command menu"),
        }
    }

    // Publish the Mini App menu button (the one next to the message box
    // in private chats). Profile placement is BotFather-only, so bots
    // should set the Main Mini App there too.
    if let Some((label, url)) = menu_web_app {
        publish_menu_button(&bot, &label, &url).await;
    }

    // Let background tasks (a restarting tunnel with a fresh URL) update
    // the menu button at runtime through the notifier.
    if let Some(notifier) = &notifier {
        let bot_for_menu = bot.clone();
        let publish: crate::notifier::MenuAppFn =
            std::sync::Arc::new(move |label: String, url: String| {
                let bot = bot_for_menu.clone();
                Box::pin(async move {
                    publish_menu_button(&bot, &label, &url).await;
                    Ok(())
                })
            });
        notifier.register_menu_app(publish).await;
    }

    // Drop anything that piled up while the bot was offline. When an age
    // limit is set we treat a restart as "start fresh": ask Telegram for
    // the latest update id and acknowledge everything up to it, so the
    // long-poll loop below only ever sees messages sent from now on. This
    // is what stops a burst of stale `/help`s the moment the bot boots.
    if router.max_update_age().is_some() {
        if let Err(e) = drop_pending_updates(&bot).await {
            tracing::warn!(error = %e, "telegram: could not clear pending updates");
        } else {
            tracing::info!("telegram: cleared backlog of pending updates");
        }
    }

    // Know our own id so a "reply to the bot" can be recognised. One
    // transient network error here would disable reply-to-bot for the
    // whole uptime, so retry a couple of times before giving up.
    let mut self_id: Option<u64> = None;
    for attempt in 0..3 {
        match bot.get_me().await {
            Ok(me) => {
                self_id = Some(me.id.0);
                break;
            }
            Err(e) => {
                tracing::warn!(error = %e, attempt, "telegram: get_me failed");
                tokio::time::sleep(std::time::Duration::from_secs(2)).await;
            }
        }
    }

    let msg_router = router.clone();
    let cbq_router = router.clone();
    let handler = dptree::entry()
        .branch(
            Update::filter_message().endpoint(move |bot: teloxide::Bot, msg: Message| {
                let router = Arc::clone(&msg_router);
                async move {
                    if let Err(e) = handle_message(&bot, &msg, &router, self_id).await {
                        tracing::warn!(error = %e, "telegram handler error");
                    }
                    respond(())
                }
            }),
        )
        .branch(Update::filter_callback_query().endpoint(
            move |bot: teloxide::Bot, q: CallbackQuery| {
                let router = Arc::clone(&cbq_router);
                async move {
                    if let Err(e) = handle_callback(&bot, &q, &router).await {
                        tracing::warn!(error = %e, "telegram callback error");
                    }
                    respond(())
                }
            },
        ));

    // Handle updates concurrently. The default distribution groups
    // updates by chat and runs them one at a time, so a single slow
    // handler (an AI answer streaming for minutes) would queue every
    // other command from that chat behind it.
    Dispatcher::builder(bot, handler)
        .distribution_function(|_| None::<std::convert::Infallible>)
        .build()
        .dispatch()
        .await;

    Ok(())
}

/// Set (or replace) the Mini App menu button. Telegram accepts https
/// only; anything else is rejected here with a readable warning instead
/// of a cryptic API error.
async fn publish_menu_button(bot: &teloxide::Bot, label: &str, url: &str) {
    match url::Url::parse(url) {
        Ok(parsed) if parsed.scheme() != "https" => {
            tracing::warn!(url, "telegram: mini app url must be https; button skipped");
        }
        Ok(parsed) => {
            let button = teloxide::types::MenuButton::WebApp {
                text: label.to_owned(),
                web_app: teloxide::types::WebAppInfo { url: parsed },
            };
            match bot.set_chat_menu_button().menu_button(button).await {
                Ok(_) => tracing::info!("telegram: published mini app menu button"),
                Err(e) => {
                    tracing::warn!(error = %e, "telegram: could not set mini app menu button")
                }
            }
        }
        Err(e) => tracing::warn!(error = %e, url, "telegram: bad mini app url; button skipped"),
    }
}

async fn handle_message(
    bot: &teloxide::Bot,
    msg: &Message,
    router: &Router,
    self_id: Option<u64>,
) -> Result<()> {
    // Photos and image documents carry a caption instead of text; treat
    // it as the message text so ctx.text()/args() keep working. An image
    // with no caption still dispatches with empty text, so handlers can
    // react to the picture itself.
    let image_file_id = tg_image_file_id(msg);
    let text = match msg.text().or_else(|| msg.caption()) {
        Some(t) => t.to_owned(),
        None if image_file_id.is_some() => String::new(),
        None => return Ok(()),
    };

    // Drop stale messages. After downtime Telegram delivers everything the
    // bot missed; without this guard the bot would answer a whole backlog
    // at once. `msg.date` is when the user actually sent it.
    if let Some(max_age) = router.max_update_age() {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        let sent = msg.date.timestamp();
        if now.saturating_sub(sent) > max_age.as_secs() as i64 {
            tracing::debug!(age_secs = now - sent, "telegram: skipping stale message");
            return Ok(());
        }
    }

    let chat_id = msg.chat.id;
    let user_id = msg
        .from
        .as_ref()
        .map(|u| u.id.0.to_string())
        .unwrap_or_default();
    // Display name: "First Last" when both are set, falling back through
    // first name alone to @username.
    let user_name = msg.from.as_ref().map(|u| {
        let mut name = u.first_name.clone();
        if let Some(last) = &u.last_name {
            if !last.is_empty() {
                if !name.is_empty() {
                    name.push(' ');
                }
                name.push_str(last);
            }
        }
        if name.is_empty() {
            name = u.username.clone().unwrap_or_default();
        }
        name
    });
    let is_dm = Some(msg.chat.is_private());
    // Keep the source message id and forum-topic id so every reply lands
    // as a real reply in the right topic / chat. Users in Telegram now
    // expect that behaviour - replies live in the thread they belong to.
    let source_msg_id = msg.id;
    let thread_id = msg.thread_id;

    // Last message the bot sent in reply to this update, shared between
    // reply_fn (writes it) and edit_fn (edits it). Lets ctx.edit_reply()
    // rewrite the bot's own answer in place - e.g. streaming AI output
    // into a single message instead of spamming new ones.
    let last_sent: Arc<std::sync::Mutex<Option<MessageId>>> = Arc::new(std::sync::Mutex::new(None));

    let bot_clone = bot.clone();
    let sent_for_reply = Arc::clone(&last_sent);
    let reply_fn: crate::ctx::ReplyFn = Box::new(move |reply: Reply| {
        let bot = bot_clone.clone();
        let sent = Arc::clone(&sent_for_reply);
        Box::pin(async move {
            let id = send_tg_message(&bot, chat_id, Some(source_msg_id), thread_id, reply).await?;
            if let Ok(mut slot) = sent.lock() {
                *slot = Some(id);
            }
            Ok(())
        })
    });
    // Edit the last reply when there is one, otherwise fall back to a
    // fresh message so early edit_reply() calls still answer the user.
    let bot_for_edit = bot.clone();
    let sent_for_edit = Arc::clone(&last_sent);
    let edit_fn: crate::ctx::EditFn = Arc::new(move |reply: Reply| {
        let bot = bot_for_edit.clone();
        let sent = Arc::clone(&sent_for_edit);
        Box::pin(async move {
            let target = sent.lock().ok().and_then(|slot| *slot);
            match target {
                Some(msg_id) => edit_tg_message(&bot, chat_id, msg_id, reply).await,
                None => {
                    let id = send_tg_message(&bot, chat_id, Some(source_msg_id), thread_id, reply)
                        .await?;
                    if let Ok(mut slot) = sent.lock() {
                        *slot = Some(id);
                    }
                    Ok(())
                }
            }
        })
    });

    let ctx = Ctx::new_with_edit(
        PlatformKind::Telegram,
        chat_id.0.to_string(),
        user_id,
        text,
        reply_fn,
        is_dm,
        None,
        Some(edit_fn),
    )
    .with_lookups(
        // Telegram avatars aren't exposed as a public URL (the file link
        // carries the bot token), so we don't offer them. Chat info is
        // fine to look up, though.
        None,
        None,
        chatinfo_lookup(bot.clone(), msg.chat.id, msg.chat.is_private()),
    )
    .with_typing(typing_lookup(bot.clone(), msg.chat.id, thread_id))
    .with_temp_reply(temp_reply_lookup(bot.clone(), msg.chat.id, thread_id))
    .with_user_name(user_name)
    .with_incoming_image(
        image_file_id.is_some(),
        image_file_id.map(|id| image_lookup(bot.clone(), id)),
    )
    .with_reply_to_bot(
        // A reply whose quoted message came from us.
        msg.reply_to_message()
            .and_then(|r| r.from.as_ref())
            .map(|u| Some(u.id.0) == self_id)
            .unwrap_or(false),
    );

    router.dispatch(ctx).await
}

async fn handle_callback(bot: &teloxide::Bot, q: &CallbackQuery, router: &Router) -> Result<()> {
    // We need a chat to reply into. Messages attached to a callback carry
    // the originating chat; if the button came from inline mode without a
    // chat, we silently ack it and walk away.
    let Some(maybe_msg) = q.message.as_ref() else {
        // Best effort: acknowledge the press so the client stops spinning.
        let _ = bot.answer_callback_query(&q.id).await;
        return Ok(());
    };
    let chat_id = maybe_msg.chat().id;
    let user_id = q.from.id.0.to_string();
    // Same display-name fallback chain as the message path.
    let user_name = {
        let u = &q.from;
        let mut name = u.first_name.clone();
        if let Some(last) = &u.last_name {
            if !last.is_empty() {
                if !name.is_empty() {
                    name.push(' ');
                }
                name.push_str(last);
            }
        }
        if name.is_empty() {
            name = u.username.clone().unwrap_or_default();
        }
        Some(name)
    };
    let data = q.data.clone().unwrap_or_default();
    let is_private = maybe_msg.chat().is_private();
    let is_dm = Some(is_private);
    // The attached message tells us which topic (if any) the user tapped
    // the button in. Reply in the same thread so the answer doesn't leak
    // into the general topic.
    let thread_id = thread_id_of(maybe_msg);
    // Message id of the bot's post that carries the button - we'll use
    // it to edit that message in place from handlers via ctx.edit_reply().
    let bot_msg_id = maybe_msg.id();

    // Acknowledge the press. Ignore errors - they don't affect dispatch.
    let _ = bot.answer_callback_query(&q.id).await;

    let bot_for_reply = bot.clone();
    let reply_fn: crate::ctx::ReplyFn = Box::new(move |reply: Reply| {
        let bot = bot_for_reply.clone();
        Box::pin(async move {
            // Thread new messages right off the button message so the
            // conversation stays tidy in groups and forums.
            send_tg_message(&bot, chat_id, Some(bot_msg_id), thread_id, reply)
                .await
                .map(|_| ())
        })
    });
    let bot_for_edit = bot.clone();
    let edit_fn: crate::ctx::EditFn = std::sync::Arc::new(move |reply: Reply| {
        let bot = bot_for_edit.clone();
        Box::pin(async move { edit_tg_message(&bot, chat_id, bot_msg_id, reply).await })
    });

    // We pass the callback payload as both text (for handlers that key off
    // `ctx.text()` like slash-command dispatch) and as dedicated
    // `callback_data`. Slash-style payloads (`/confirm me`) still route
    // through `dispatch` like a typed message; free-form ones end up in
    // `Ctx::callback_data()`.
    let ctx = Ctx::new_with_edit(
        PlatformKind::Telegram,
        chat_id.0.to_string(),
        user_id,
        data.clone(),
        reply_fn,
        is_dm,
        Some(data),
        Some(edit_fn),
    )
    .with_lookups(
        // Same as the message path: Telegram avatars need the bot token
        // in the URL, so only chat info is offered.
        None,
        None,
        chatinfo_lookup(bot.clone(), chat_id, is_private),
    )
    .with_typing(typing_lookup(bot.clone(), chat_id, thread_id))
    .with_temp_reply(temp_reply_lookup(bot.clone(), chat_id, thread_id))
    // Button presses never carry an image.
    .with_incoming_image(false, None)
    .with_user_name(user_name);

    router.dispatch(ctx).await
}

/// Build a `teloxide::Bot` honouring proxy env vars.
fn build_bot(token: &str) -> Result<teloxide::Bot> {
    let proxy = std::env::var("HTTPS_PROXY")
        .ok()
        .or_else(|| std::env::var("https_proxy").ok())
        .or_else(|| std::env::var("HTTP_PROXY").ok())
        .or_else(|| std::env::var("http_proxy").ok())
        .or_else(|| std::env::var("ALL_PROXY").ok())
        .or_else(|| std::env::var("all_proxy").ok())
        .filter(|s| !s.trim().is_empty());

    let mut builder =
        reqwest::Client::builder().connect_timeout(std::time::Duration::from_secs(20));

    if let Some(url) = proxy.as_deref() {
        match reqwest::Proxy::all(url) {
            Ok(p) => {
                tracing::info!(proxy = %url, "telegram adapter using proxy");
                builder = builder.proxy(p);
            }
            Err(e) => {
                tracing::warn!(proxy = %url, error = %e, "ignoring bad proxy URL");
            }
        }
    }

    let client = builder
        .build()
        .map_err(|e| Error::platform("telegram", format!("reqwest client build: {e}")))?;
    Ok(teloxide::Bot::with_client(token, client))
}

/// Fish the forum-topic id out of a `MaybeInaccessibleMessage` that came
/// with a callback query. `None` when the message is inaccessible (very
/// old in a channel, deleted, etc.) or when the chat isn't a forum.
fn thread_id_of(maybe_msg: &teloxide::types::MaybeInaccessibleMessage) -> Option<ThreadId> {
    match maybe_msg {
        teloxide::types::MaybeInaccessibleMessage::Regular(m) => m.thread_id,
        teloxide::types::MaybeInaccessibleMessage::Inaccessible(_) => None,
    }
}

/// Telegram caps a message at ~4096 chars.
const TG_LIMIT: usize = 4096;

/// Send a [`Reply`] into a Telegram chat, optionally replying to a
/// specific message and/or pinning the reply to a forum topic.
///
/// Both are important in group chats:
/// - `reply_to` makes the bot's answer appear as a proper reply instead
///   of a loose message at the bottom of the chat;
/// - `thread_id` keeps the reply inside the forum topic the user typed
///   in, so a question in "General" doesn't get answered in "Random".
///
/// Returns the id of the last message sent (the last chunk when the
/// text had to be split), so callers can edit it later.
async fn send_tg_message(
    bot: &teloxide::Bot,
    chat_id: ChatId,
    reply_to: Option<MessageId>,
    thread_id: Option<ThreadId>,
    reply: Reply,
) -> Result<MessageId> {
    // Raw media bytes take the native-media path: the rendered body
    // becomes the caption and the keyboard rides on the media message.
    if reply.get_attachment().is_some() {
        return send_tg_media(bot, chat_id, reply_to, thread_id, &reply).await;
    }

    // Telegram has no real embeds, but it *does* render HTML inside a
    // regular message. When the reply carries an Embed we dress it up
    // with <b> headers / dividers so the result still looks like a
    // "card" rather than a flat wall of text.
    let (body, use_html) = render_for_telegram(&reply);

    // Short replies (embeds, normal answers) go as one HTML message. If
    // something is genuinely long - a wall of text from an AI model, say -
    // we split it across messages. Splitting can land mid-tag, so the
    // multi-part path drops HTML and sends plain text, which is exactly
    // what long free-form output is.
    if body.chars().count() > TG_LIMIT {
        let plain = reply.get_text();
        let source = if plain.is_empty() { &body } else { plain };
        let parts = crate::util::split_chunks(source, TG_LIMIT);
        let last = parts.len().saturating_sub(1);
        let mut last_id = None;
        for (i, part) in parts.iter().enumerate() {
            let mut req = bot.send_message(chat_id, part);
            if i == 0 {
                if let Some(id) = reply_to {
                    req = req
                        .reply_parameters(ReplyParameters::new(id).allow_sending_without_reply());
                }
            }
            if let Some(tid) = thread_id {
                req = req.message_thread_id(tid);
            }
            // Attach the keyboard only to the final part.
            if i == last {
                if let Some(kb) = reply.get_keyboard() {
                    req = req.reply_markup(to_tg_markup(kb));
                }
            }
            let sent = req.await.map_err(|e| Error::platform("telegram", e))?;
            last_id = Some(sent.id);
        }
        // parts is never empty here: body was longer than the limit.
        return last_id.ok_or_else(|| Error::platform("telegram", "nothing to send"));
    }

    let mut req = bot.send_message(chat_id, body);
    if use_html {
        req = req.parse_mode(ParseMode::Html);
    }
    if let Some(id) = reply_to {
        // allow_sending_without_reply=true: if the original message is
        // gone (deleted / too old), still send a plain reply instead of
        // erroring out.
        req = req.reply_parameters(ReplyParameters::new(id).allow_sending_without_reply());
    }
    if let Some(tid) = thread_id {
        req = req.message_thread_id(tid);
    }
    if let Some(kb) = reply.get_keyboard() {
        req = req.reply_markup(to_tg_markup(kb));
    }
    let sent = req.await.map_err(|e| Error::platform("telegram", e))?;
    Ok(sent.id)
}

/// Send a [`Reply`] carrying raw media bytes as a native photo, video or
/// audio message.
///
/// The rendered body (text and/or embed) becomes the caption. Telegram
/// caps captions at 1024 chars: longer bodies fall back to a plain-text
/// split - the first chunk rides as the caption, the rest go out as
/// separate messages. The keyboard always sticks to the media message.
///
/// Audio goes through `sendAudio` (the music-player bubble that shows
/// the filename), not `sendVoice` - a voice note re-encodes to OGG and
/// hides the track name, which is wrong for "here's a file" replies.
///
/// Returns the id of the last message sent (the last overflow chunk when
/// the caption spilled over, otherwise the media message itself).
async fn send_tg_media(
    bot: &teloxide::Bot,
    chat_id: ChatId,
    reply_to: Option<MessageId>,
    thread_id: Option<ThreadId>,
    reply: &Reply,
) -> Result<MessageId> {
    let Some((bytes, name, kind)) = reply.get_attachment() else {
        return Err(Error::platform("telegram", "no attachment to send"));
    };
    crate::keyboard::check_attachment_size(bytes, kind)?;
    let file = InputFile::memory(bytes.to_vec()).file_name(name.to_owned());

    const TG_CAPTION_LIMIT: usize = 1024;
    let (body, use_html) = render_for_telegram(reply);

    // Long body: the caption gets the first plain-text chunk, the rest
    // follows as regular messages. Splitting can land mid-tag, so this
    // path drops HTML, same as the long-message path above.
    let (caption, overflow, caption_html) = if body.chars().count() > TG_CAPTION_LIMIT {
        let plain = reply.get_text();
        let source = if plain.is_empty() { &body } else { plain };
        let mut parts = crate::util::split_chunks(source, TG_CAPTION_LIMIT);
        let first = if parts.is_empty() {
            String::new()
        } else {
            parts.remove(0)
        };
        (first, parts, false)
    } else {
        (body, Vec::new(), use_html)
    };

    // sendPhoto/sendVideo/sendAudio build distinct request types with
    // identically-named setters, so a small macro keeps one setter chain.
    macro_rules! send_with_extras {
        ($req:expr) => {{
            let mut req = $req;
            if !caption.is_empty() {
                req = req.caption(caption.clone());
                if caption_html {
                    req = req.parse_mode(ParseMode::Html);
                }
            }
            if let Some(id) = reply_to {
                req = req.reply_parameters(ReplyParameters::new(id).allow_sending_without_reply());
            }
            if let Some(tid) = thread_id {
                req = req.message_thread_id(tid);
            }
            if let Some(kb) = reply.get_keyboard() {
                req = req.reply_markup(to_tg_markup(kb));
            }
            req.await.map_err(|e| Error::platform("telegram", e))?
        }};
    }
    let sent = match kind {
        AttachmentKind::Photo => send_with_extras!(bot.send_photo(chat_id, file)),
        AttachmentKind::Video => send_with_extras!(bot.send_video(chat_id, file)),
        AttachmentKind::Audio => send_with_extras!(bot.send_audio(chat_id, file)),
    };
    let mut last_id = sent.id;

    for part in overflow {
        let mut req = bot.send_message(chat_id, part);
        if let Some(tid) = thread_id {
            req = req.message_thread_id(tid);
        }
        let sent = req.await.map_err(|e| Error::platform("telegram", e))?;
        last_id = sent.id;
    }
    Ok(last_id)
}

/// Edit the bot's message that carried the button the user just pressed.
///
/// Telegram's `editMessageText` + separate `editMessageReplyMarkup`
/// calls are used here: sending the keyboard as part of the text edit
/// is fine when we have one, but when the reply has no keyboard we
/// still want the old buttons gone, so the second call wipes the
/// markup. Errors fall through to the caller so the handler can decide
/// whether to fall back to a fresh message or give up.
///
/// Media bytes are ignored here: `editMessageText` can't turn a text
/// message into a photo/video/audio, and swapping media on an arbitrary
/// message via `editMessageMedia` only works when the original already
/// had media.
async fn edit_tg_message(
    bot: &teloxide::Bot,
    chat_id: ChatId,
    msg_id: MessageId,
    reply: Reply,
) -> Result<()> {
    let (body, use_html) = render_for_telegram(&reply);
    // An edit can't spill into extra messages, so overlong text gets cut
    // at the first chunk boundary. Truncation could land mid-tag, so this
    // path drops HTML and edits in the plain text, same as chunked sends.
    let (body, use_html) = if body.chars().count() > TG_LIMIT {
        let plain = reply.get_text();
        let source = if plain.is_empty() { &body } else { plain };
        (crate::util::truncate_chunk(source, TG_LIMIT), false)
    } else {
        (body, use_html)
    };
    let markup = reply.get_keyboard().map(to_tg_markup);
    let mut edit = bot.edit_message_text(chat_id, msg_id, body);
    if use_html {
        edit = edit.parse_mode(ParseMode::Html);
    }
    if let Some(m) = markup {
        edit = edit.reply_markup(m);
    }
    match edit.await {
        Ok(_) => Ok(()),
        Err(e) => {
            // "message is not modified" is a benign Telegram quirk: the
            // new text matched the old one exactly. Pretend we edited.
            if format!("{e}").contains("message is not modified") {
                return Ok(());
            }
            Err(Error::platform("telegram", e))
        }
    }
}

/// Render a [`Reply`] into the string teloxide actually sends, plus a
/// flag indicating whether HTML parsing should be enabled for it.
///
/// When there's no embed we keep things plain (Telegram escapes nothing
/// extra, auto-linkification handles URLs just fine). When there *is*
/// an embed we build an HTML block with a bold title, description,
/// `name: value` fields, and a small footer line - the closest we can
/// get to Discord's embed without leaving Telegram's formatting rules.
fn render_for_telegram(reply: &Reply) -> (String, bool) {
    // Honour an explicit "don't touch my markdown" request: send the text
    // verbatim with no HTML parsing at all.
    if reply.is_raw() {
        let mut out = reply.get_text().to_owned();
        if let Some(em) = reply.get_embed() {
            if !out.is_empty() {
                out.push_str("\n\n");
            }
            out.push_str(&raw_embed_text(em));
        }
        return (out, false);
    }

    let Some(em) = reply.get_embed() else {
        // A plain text reply: still convert markdown so `code` and **bold**
        // render, matching how the same string looks on Discord.
        return (md_to_tg(reply.get_text()), true);
    };

    let mut out = String::new();

    // Title (linkified when the embed carries a URL).
    if let Some(title) = em.get_title() {
        let rendered = md_to_tg(title);
        match em.get_url() {
            Some(u) => out.push_str(&format!(
                "<b><a href=\"{}\">{rendered}</a></b>\n",
                html_escape(u)
            )),
            None => out.push_str(&format!("<b>{rendered}</b>\n")),
        }
    }
    if let Some(desc) = em.get_description() {
        out.push_str(&md_to_tg(desc));
        out.push('\n');
    }
    if !em.get_fields().is_empty() {
        if em.get_title().is_some() || em.get_description().is_some() {
            out.push('\n');
        }
        for f in em.get_fields() {
            out.push_str(&format!(
                "<b>{}</b>\n{}\n",
                md_to_tg(f.name()),
                md_to_tg(f.value())
            ));
        }
    }
    if let Some(foot) = em.get_footer() {
        out.push_str(&format!("\n<i>{}</i>", md_to_tg(foot)));
    }
    // Big image gets appended as a raw URL on a separate line - Telegram
    // auto-renders a preview for it. Thumbnails are discord-only, so we
    // skip those here.
    if let Some(img) = em.get_image() {
        out.push_str(&format!("\n\n{}", img));
    }
    // Prepend any free-form text that came along with the embed, so
    // handlers can still mix "quick line" + a pretty card in one call.
    if !reply.get_text().is_empty() {
        let head = md_to_tg(reply.get_text());
        out = format!("{head}\n\n{out}");
    }
    // Trim trailing whitespace so Telegram doesn't squint at us.
    while out.ends_with(|c: char| c.is_whitespace()) {
        out.pop();
    }
    (out, true)
}

/// Flatten an embed to plain text for the raw-markdown path (no HTML).
fn raw_embed_text(em: &crate::keyboard::Embed) -> String {
    let mut out = String::new();
    if let Some(t) = em.get_title() {
        out.push_str(t);
        out.push('\n');
    }
    if let Some(d) = em.get_description() {
        out.push_str(d);
        out.push('\n');
    }
    for f in em.get_fields() {
        out.push_str(&format!("{}\n{}\n", f.name(), f.value()));
    }
    if let Some(foot) = em.get_footer() {
        out.push_str(&format!("\n{foot}"));
    }
    if let Some(img) = em.get_image() {
        out.push_str(&format!("\n\n{img}"));
    }
    out.trim_end().to_owned()
}

fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    out
}

/// Convert the small markdown subset the bot uses into Telegram HTML.
///
/// Handles `` `code` ``, `***bold italic***`, `**bold**`, `*italic*` /
/// `_italic_`, and `[text](url)`. HTML-special characters are escaped
/// first so user text can't inject tags; code spans and rendered links
/// are pulled out into placeholders before the emphasis passes so their
/// contents are left literal. This is what lets a handler write one
/// markdown string that looks right on Discord *and* Telegram.
///
/// TODO: ||spoiler|| -> <tg-spoiler> would be nice for two-part jokes.
fn md_to_tg(input: &str) -> String {
    // 0. Strip NUL bytes from the input - they are our placeholder
    //    markers below, and Telegram rejects them anyway.
    let input: String = input.chars().filter(|&c| c != '\u{0}').collect();

    // 1. Extract code spans, replacing each with a placeholder so later
    //    passes don't reinterpret their contents.
    let mut spans: Vec<String> = Vec::new();
    let mut stage = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '`' {
            let mut span = String::new();
            let mut closed = false;
            for cc in chars.by_ref() {
                if cc == '`' {
                    closed = true;
                    break;
                }
                span.push(cc);
            }
            if closed {
                stage.push('\u{0}');
                stage.push_str(&spans.len().to_string());
                stage.push('\u{0}');
                spans.push(format!("<code>{}</code>", html_escape(&span)));
            } else {
                // Unmatched backtick: keep it literal.
                stage.push('`');
                stage.push_str(&span);
            }
        } else {
            stage.push(c);
        }
    }

    // 2. Escape HTML on the non-code text.
    let escaped = html_escape(&stage);

    // 3. Links: [text](url) -> <a href="url">text</a>. Each rendered
    //    anchor is stashed as a placeholder so the emphasis passes below
    //    can't chew on `_` or `*` inside the URL.
    let linked = render_links(&escaped, &mut spans);

    // 4. Emphasis. Triple stars first so `***x***` nests as
    //    <b><i>x</i></b>, then bold, then italics. Underscores never
    //    match inside a word, so snake_case_names stay literal.
    let tri = replace_emphasis(&linked, "***", "<b><i>", "</i></b>", false);
    let bolded = replace_emphasis(&tri, "**", "<b>", "</b>", false);
    let italic_star = replace_emphasis(&bolded, "*", "<i>", "</i>", false);
    let mut result = replace_emphasis(&italic_star, "_", "<i>", "</i>", true);

    // 5. Put code spans and links back.
    for (i, span) in spans.iter().enumerate() {
        let marker = format!("\u{0}{i}\u{0}");
        result = result.replace(&marker, span);
    }
    result
}

/// Replace matched pairs of `delim` with `open`/`close` tags. An opening
/// delimiter must not be followed by whitespace and a closing one must
/// not be preceded by it, so `2 * 3 * 4` stays literal. With
/// `word_boundary` the delimiter must also sit at a word edge, which
/// keeps snake_case_word from turning into italics. Unmatched delimiters
/// are kept as-is.
fn replace_emphasis(s: &str, delim: &str, open: &str, close: &str, word_boundary: bool) -> String {
    let chars: Vec<char> = s.chars().collect();
    let dchars: Vec<char> = delim.chars().collect();
    let dlen = dchars.len();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < chars.len() {
        if chars[i..].starts_with(&dchars[..]) {
            // Candidate opener: next char must exist and not be whitespace
            // or another delimiter char (leave longer runs to their pass).
            // For word-boundary delims the char before must not be part of
            // a word.
            let after = chars.get(i + dlen).copied();
            let opens = matches!(after, Some(c) if !c.is_whitespace() && c != dchars[0])
                && (!word_boundary
                    || i == 0
                    || chars
                        .get(i - 1)
                        .map(|c| !c.is_alphanumeric())
                        .unwrap_or(true));
            if opens {
                // Scan for a closer: delim preceded by non-whitespace and,
                // when word-bounded, not followed by a word char.
                let mut j = i + dlen;
                let mut found = None;
                while j + dlen <= chars.len() {
                    if chars[j..].starts_with(&dchars[..])
                        && chars
                            .get(j - 1)
                            .map(|c| !c.is_whitespace() && *c != dchars[0])
                            .unwrap_or(false)
                        && (!word_boundary
                            || chars
                                .get(j + dlen)
                                .map(|c| !c.is_alphanumeric())
                                .unwrap_or(true))
                    {
                        found = Some(j);
                        break;
                    }
                    j += 1;
                }
                if let Some(end) = found {
                    out.push_str(open);
                    out.extend(&chars[i + dlen..end]);
                    out.push_str(close);
                    i = end + dlen;
                    continue;
                }
            }
        }
        out.push(chars[i]);
        i += 1;
    }
    out
}

/// Turn `[text](url)` into an HTML anchor stored as a placeholder in
/// `spans`, so later emphasis passes can't touch the URL. Operates on
/// already-escaped text.
fn render_links(s: &str, spans: &mut Vec<String>) -> String {
    let bytes: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == '[' {
            if let Some((text, url, next)) = parse_link(&bytes, i) {
                out.push('\u{0}');
                out.push_str(&spans.len().to_string());
                out.push('\u{0}');
                spans.push(format!("<a href=\"{url}\">{text}</a>"));
                i = next;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    out
}

/// Parse a `[text](url)` starting at `start` (`bytes[start] == '['`).
fn parse_link(bytes: &[char], start: usize) -> Option<(String, String, usize)> {
    let close_text = bytes[start..].iter().position(|&c| c == ']')? + start;
    if bytes.get(close_text + 1) != Some(&'(') {
        return None;
    }
    let close_url = bytes[close_text + 2..].iter().position(|&c| c == ')')? + close_text + 2;
    let text: String = bytes[start + 1..close_text].iter().collect();
    let url: String = bytes[close_text + 2..close_url].iter().collect();
    Some((text, url, close_url + 1))
}

fn to_tg_markup(kb: &crate::keyboard::Keyboard) -> InlineKeyboardMarkup {
    let rows: Vec<Vec<InlineKeyboardButton>> = kb
        .rows()
        .iter()
        .map(|row| {
            row.iter()
                .filter_map(|btn| match &btn.kind {
                    ButtonKind::Callback(id) => {
                        // Telegram hard-caps callback data at 64 bytes and
                        // rejects the whole keyboard if any button exceeds
                        // it. Warn loudly so the cause is obvious instead
                        // of a cryptic API error at send time.
                        if id.len() > 64 {
                            tracing::warn!(
                                callback = %id,
                                len = id.len(),
                                "telegram: callback data exceeds 64 bytes and will be rejected"
                            );
                        }
                        Some(InlineKeyboardButton::callback(
                            btn.label().to_owned(),
                            id.clone(),
                        ))
                    }
                    ButtonKind::Url(url) => Some(InlineKeyboardButton::url(
                        btn.label().to_owned(),
                        url::Url::parse(url)
                            .unwrap_or_else(|_| url::Url::parse("https://fouko.xyz").unwrap()),
                    )),
                    ButtonKind::WebApp(url) => match url::Url::parse(url) {
                        Ok(parsed) => Some(InlineKeyboardButton::web_app(
                            btn.label().to_owned(),
                            teloxide::types::WebAppInfo { url: parsed },
                        )),
                        // A broken Mini App URL can't degrade to anything
                        // useful, so drop the button instead of sending a
                        // keyboard Telegram will reject.
                        Err(e) => {
                            tracing::warn!(
                                url = %url,
                                error = %e,
                                "telegram: invalid web_app url, button dropped"
                            );
                            None
                        }
                    },
                })
                .collect()
        })
        .collect();
    InlineKeyboardMarkup::new(rows)
}

/// Telegram command names: 1-32 chars, lowercase ASCII letters, digits and
/// underscores. Unlike Discord, a leading digit is allowed, so `8ball` is
/// fine here.
fn is_valid_tg_command(s: &str) -> bool {
    !s.is_empty()
        && s.len() <= 32
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

/// Truncate `s` to at most `max_chars` characters on a char boundary.
fn truncate_chars(s: &str, max_chars: usize) -> String {
    s.chars().take(max_chars).collect()
}

/// Chat-info lookup for Telegram: `getChat` for the title/description and
/// `getChatMemberCount` for the size. Private chats report `is_private`.
fn chatinfo_lookup(bot: teloxide::Bot, chat_id: ChatId, is_private: bool) -> Option<ChatInfoFn> {
    Some(Arc::new(move || {
        let bot = bot.clone();
        Box::pin(async move {
            let chat = bot
                .get_chat(chat_id)
                .await
                .map_err(|e| Error::platform("telegram", e))?;
            // Member count only makes sense for groups/channels; ignore
            // errors (e.g. in private chats) and leave it unset.
            let member_count = if is_private {
                None
            } else {
                bot.get_chat_member_count(chat_id)
                    .await
                    .ok()
                    .map(|c| c as u64)
            };
            let title = chat.title().map(|s| s.to_owned());
            let description = chat.description().map(|s| s.to_owned());
            Ok(ChatInfo {
                id: chat_id.0.to_string(),
                title,
                member_count,
                icon_url: None,
                description,
                is_private,
            })
        })
    }))
}

/// Build a typing-indicator callback for a chat/topic.
fn typing_lookup(
    bot: teloxide::Bot,
    chat_id: ChatId,
    thread_id: Option<ThreadId>,
) -> Option<crate::ctx::TypingFn> {
    Some(Arc::new(move || {
        let bot = bot.clone();
        Box::pin(async move {
            let mut req = bot.send_chat_action(chat_id, teloxide::types::ChatAction::Typing);
            if let Some(tid) = thread_id {
                req = req.message_thread_id(tid);
            }
            req.await.map_err(|e| Error::platform("telegram", e))?;
            Ok(())
        })
    }))
}

/// Pretty name for a private chat: "First Last (@username)". Falls back
/// through first name alone to the bare @username, then to the chat id.
fn tg_display_name(chat: &teloxide::types::Chat) -> String {
    format_tg_name(
        chat.first_name(),
        chat.last_name(),
        chat.username(),
        chat.id.0,
    )
}

/// The formatting behind [`tg_display_name`], split out for tests.
fn format_tg_name(
    first: Option<&str>,
    last: Option<&str>,
    username: Option<&str>,
    id: i64,
) -> String {
    let mut name = String::new();
    if let Some(first) = first {
        name.push_str(first);
    }
    if let Some(last) = last {
        if !last.is_empty() {
            if !name.is_empty() {
                name.push(' ');
            }
            name.push_str(last);
        }
    }
    match username {
        Some(u) if name.is_empty() => format!("@{u}"),
        Some(u) => format!("{name} (@{u})"),
        None if name.is_empty() => id.to_string(),
        None => name,
    }
}

/// Hard cap on a downloaded incoming image, so one oversized photo can't
/// balloon memory.
const MAX_INCOMING_IMAGE_BYTES: usize = 10 * 1024 * 1024;

/// File id of the image attached to a message, if any: a photo (largest
/// size, which Telegram lists last) or a document with an `image/*` mime.
fn tg_image_file_id(msg: &Message) -> Option<String> {
    if let Some(sizes) = msg.photo() {
        if let Some(largest) = sizes.last() {
            return Some(largest.file.id.clone());
        }
    }
    if let Some(doc) = msg.document() {
        let is_image = doc
            .mime_type
            .as_ref()
            .map(|m| m.type_() == "image")
            .unwrap_or(false);
        if is_image {
            return Some(doc.file.id.clone());
        }
    }
    None
}

/// Build the lazy image download for a message that carries one:
/// `getFile` resolves the file path, then the bytes come from Telegram's
/// file endpoint. Capped at [`MAX_INCOMING_IMAGE_BYTES`].
fn image_lookup(bot: teloxide::Bot, file_id: String) -> crate::ctx::ImageFn {
    Arc::new(move || {
        let bot = bot.clone();
        let file_id = file_id.clone();
        Box::pin(async move {
            let file = bot
                .get_file(file_id)
                .await
                .map_err(|e| Error::platform("telegram", e))?;
            if file.meta.size as usize > MAX_INCOMING_IMAGE_BYTES {
                return Err(Error::platform("telegram", "incoming image too large"));
            }
            let url = format!(
                "https://api.telegram.org/file/bot{}/{}",
                bot.token(),
                file.path
            );
            let bytes = download_capped(bot.client(), &url, MAX_INCOMING_IMAGE_BYTES)
                .await
                .map_err(|e| Error::platform("telegram", e))?;
            Ok(Some(bytes))
        })
    })
}

/// Download a URL with a hard size cap. Returns an error string so the
/// caller can wrap it into a platform error.
async fn download_capped(
    client: &reqwest::Client,
    url: &str,
    cap: usize,
) -> std::result::Result<Vec<u8>, String> {
    let resp = client
        .get(url)
        .send()
        .await
        .map_err(|e| format!("image download failed: {e}"))?;
    if !resp.status().is_success() {
        return Err(format!("image download HTTP {}", resp.status().as_u16()));
    }
    let mut resp = resp;
    let mut bytes = Vec::new();
    while let Some(chunk) = resp
        .chunk()
        .await
        .map_err(|e| format!("image download failed: {e}"))?
    {
        if bytes.len() + chunk.len() > cap {
            return Err("incoming image too large".to_owned());
        }
        bytes.extend_from_slice(&chunk);
    }
    Ok(bytes)
}

/// Acknowledge and discard every update queued before startup.
///
/// Telegram keeps undelivered updates for ~24h and replays them all when
/// the bot reconnects. We fetch just the most recent one (`offset = -1`)
/// to learn the latest update id, then confirm `id + 1`, which tells
/// Telegram to drop everything up to and including it. The next real
/// long-poll then starts clean.
async fn drop_pending_updates(bot: &teloxide::Bot) -> Result<()> {
    use teloxide::payloads::GetUpdatesSetters;

    let latest = bot
        .get_updates()
        .offset(-1)
        .timeout(0)
        .await
        .map_err(|e| Error::platform("telegram", e))?;
    if let Some(last) = latest.last() {
        // Confirm past the last update so it isn't served again. Update
        // ids are u32 while the offset parameter is i32; go through i64
        // and clamp so a large id can't wrap negative or overflow.
        let next = i64::from(last.id.0).saturating_add(1);
        let offset = i32::try_from(next).unwrap_or(i32::MAX);
        let _ = bot
            .get_updates()
            .offset(offset)
            .timeout(0)
            .await
            .map_err(|e| Error::platform("telegram", e))?;
    }
    Ok(())
}

/// Build a "send then delete after a delay" callback for transient notices.
fn temp_reply_lookup(
    bot: teloxide::Bot,
    chat_id: ChatId,
    thread_id: Option<ThreadId>,
) -> Option<crate::ctx::TempReplyFn> {
    Some(Arc::new(move |reply: Reply, secs: u64| {
        let bot = bot.clone();
        Box::pin(async move {
            // Media replies go through the native path so a transient
            // notice with a picture/clip/track still shows it.
            let sent = if let Some((bytes, name, kind)) = reply.get_attachment() {
                crate::keyboard::check_attachment_size(bytes, kind)?;
                let file = InputFile::memory(bytes.to_vec()).file_name(name.to_owned());
                let (body, use_html) = render_for_telegram(&reply);
                let caption: String = body.chars().take(1024).collect();
                macro_rules! send_media {
                    ($req:expr) => {{
                        let mut req = $req;
                        if !caption.is_empty() {
                            req = req.caption(caption.clone());
                            if use_html {
                                req = req.parse_mode(ParseMode::Html);
                            }
                        }
                        if let Some(tid) = thread_id {
                            req = req.message_thread_id(tid);
                        }
                        req.await.map_err(|e| Error::platform("telegram", e))?
                    }};
                }
                match kind {
                    AttachmentKind::Photo => send_media!(bot.send_photo(chat_id, file)),
                    AttachmentKind::Video => send_media!(bot.send_video(chat_id, file)),
                    AttachmentKind::Audio => send_media!(bot.send_audio(chat_id, file)),
                }
            } else {
                let (body, use_html) = render_for_telegram(&reply);
                let mut req = bot.send_message(chat_id, body);
                if use_html {
                    req = req.parse_mode(ParseMode::Html);
                }
                if let Some(tid) = thread_id {
                    req = req.message_thread_id(tid);
                }
                req.await.map_err(|e| Error::platform("telegram", e))?
            };
            let msg_id = sent.id;
            tokio::spawn(async move {
                tokio::time::sleep(std::time::Duration::from_secs(secs)).await;
                let _ = bot.delete_message(chat_id, msg_id).await;
            });
            Ok(())
        })
    }))
}

#[cfg(test)]
mod tests {
    use super::{format_tg_name, md_to_tg};

    #[test]
    fn code_span() {
        assert_eq!(md_to_tg("run `/help` now"), "run <code>/help</code> now");
    }

    #[test]
    fn bold_and_italic() {
        assert_eq!(md_to_tg("**hi** and *there*"), "<b>hi</b> and <i>there</i>");
        assert_eq!(md_to_tg("_stress_"), "<i>stress</i>");
    }

    #[test]
    fn html_is_escaped() {
        assert_eq!(md_to_tg("a < b & c"), "a &lt; b &amp; c");
    }

    #[test]
    fn code_contents_are_literal() {
        // Markdown and angle brackets inside code stay untouched.
        assert_eq!(md_to_tg("`**x** <b>`"), "<code>**x** &lt;b&gt;</code>");
    }

    #[test]
    fn link() {
        assert_eq!(
            md_to_tg("see [site](https://x.io)"),
            "see <a href=\"https://x.io\">site</a>"
        );
    }

    #[test]
    fn unmatched_markers_stay_literal() {
        assert_eq!(md_to_tg("2 * 3 = 6"), "2 * 3 = 6");
        assert_eq!(md_to_tg("a `code"), "a `code");
    }

    #[test]
    fn bold_italic_nests_validly() {
        assert_eq!(md_to_tg("***x***"), "<b><i>x</i></b>");
        assert_eq!(
            md_to_tg("say ***hi there*** now"),
            "say <b><i>hi there</i></b> now"
        );
    }

    #[test]
    fn link_with_underscores_survives() {
        assert_eq!(
            md_to_tg("[x](https://a.io/some_path_here)"),
            "<a href=\"https://a.io/some_path_here\">x</a>"
        );
    }

    #[test]
    fn snake_case_is_not_italic() {
        assert_eq!(md_to_tg("snake_case_word"), "snake_case_word");
        assert_eq!(
            md_to_tg("_stress_ but keep snake_case"),
            "<i>stress</i> but keep snake_case"
        );
    }

    #[test]
    fn spaced_stars_are_not_italic() {
        assert_eq!(md_to_tg("2 * 3 * 4"), "2 * 3 * 4");
    }

    #[test]
    fn quote_in_url_is_escaped() {
        assert_eq!(
            md_to_tg("[x](https://a.io/?q=\"y\")"),
            "<a href=\"https://a.io/?q=&quot;y&quot;\">x</a>"
        );
    }

    #[test]
    fn nul_bytes_in_input_are_stripped() {
        assert_eq!(md_to_tg("a\u{0}0\u{0}b `c`"), "a0b <code>c</code>");
    }

    #[test]
    fn tg_name_full() {
        assert_eq!(
            format_tg_name(Some("Ivan"), Some("Petrov"), Some("ivan"), 1),
            "Ivan Petrov (@ivan)"
        );
    }

    #[test]
    fn tg_name_no_username() {
        assert_eq!(
            format_tg_name(Some("Ivan"), Some("Petrov"), None, 1),
            "Ivan Petrov"
        );
        assert_eq!(format_tg_name(Some("Ivan"), None, None, 1), "Ivan");
    }

    #[test]
    fn tg_name_username_only() {
        assert_eq!(format_tg_name(None, None, Some("ivan"), 1), "@ivan");
    }

    #[test]
    fn tg_name_falls_back_to_id() {
        assert_eq!(format_tg_name(None, None, None, 42), "42");
        assert_eq!(format_tg_name(Some(""), Some(""), None, 42), "42");
    }
}