zad-cli 0.9.4

Command-line interface for zad — connects AI agents to external services (Discord, Slack, Google Calendar, Spotify, Telegram, YouTube Music, 1Password) via scoped service configurations.
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
//! `zad telegram <verb>` — runtime commands against a configured
//! Telegram bot.
//!
//! Credential resolution mirrors `zad service enable telegram`: the
//! project-local config wins over the global one, and the matching
//! keychain entry holds the bot token. The project must already have
//! enabled the Telegram service.

use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

use clap::{Args, Subcommand};
use serde::Serialize;

use zad::config::{self, TelegramServiceCfg};
use zad::error::{Result, ZadError};
use zad::permissions::attachments::AttachmentInfo;
use zad::secrets::{self, Scope};
use zad::service::default_dry_run_sink;
use zad::service::telegram::client::{
    TELEGRAM_MAX_CAPTION_LEN, TELEGRAM_MAX_MEDIA_GROUP, TELEGRAM_MAX_MESSAGE_LEN,
};
use zad::service::telegram::directory::{self as dir, Directory};
use zad::service::telegram::permissions::{self as perms, TelegramFunction};
use zad::service::telegram::{DryRunTelegramTransport, TelegramHttp, TelegramTransport};

// ---------------------------------------------------------------------------
// subcommand plumbing
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct TelegramArgs {
    #[command(subcommand)]
    pub action: Option<Action>,
}

#[derive(Debug, Subcommand)]
pub enum Action {
    /// Send a message to a chat (private, group, supergroup, or channel).
    Send(SendArgs),
    /// Fetch recent messages the bot has buffered for a chat.
    Read(ReadArgs),
    /// Long-poll the Bot API and stream new messages for a chat to stdout.
    Listen(ListenArgs),
    /// List chats the bot has seen (local directory + recent updates).
    Chats(ChatsArgs),
    /// Poll the Bot API for recent updates and upsert chat aliases
    /// into this project's `directory.toml`.
    Discover(DiscoverArgs),
    /// Inspect or hand-edit the name -> chat_id directory.
    Directory(DirectoryArgs),
    /// Inspect, scaffold, or dry-run the permissions policy that
    /// narrows what this service may actually do.
    Permissions(PermissionsArgs),
    /// Manage the private-chat ID resolved from the literal `@me` in
    /// send/read targets. Capture (by polling for your first message
    /// to the bot), show, set, or clear.
    #[command(name = "self")]
    SelfCmd(SelfArgs),
}

pub async fn run(args: TelegramArgs) -> Result<()> {
    let action = args.action.ok_or_else(|| {
        ZadError::Invalid("missing subcommand. Run `zad telegram --help`.".into())
    })?;
    match action {
        Action::Send(a) => run_send(a).await,
        Action::Read(a) => run_read(a).await,
        Action::Listen(a) => run_listen(a).await,
        Action::Chats(a) => run_chats(a).await,
        Action::Discover(a) => run_discover(a).await,
        Action::Directory(a) => run_directory(a),
        Action::Permissions(a) => run_permissions(a),
        Action::SelfCmd(a) => run_self(a).await,
    }
}

// ---------------------------------------------------------------------------
// send
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct SendArgs {
    /// Destination chat: a signed integer chat_id (groups/supergroups
    /// are negative), a `@username` for public channels, or a
    /// directory alias.
    #[arg(long)]
    pub chat: Option<String>,

    /// Read the message body from standard input instead of the
    /// positional argument.
    #[arg(long, conflicts_with = "body")]
    pub stdin: bool,

    /// Attach a file to the message. Repeat up to Telegram's
    /// `sendMediaGroup` cap of 10 to attach multiple files. With one
    /// file the message is sent via `sendDocument`; with 2+ files it
    /// becomes a `sendMediaGroup`. The body (if any) is sent as the
    /// caption on the first item; with attachments present Telegram's
    /// 1024-character caption cap applies instead of the 4096-character
    /// plain-text cap.
    #[arg(long = "file", value_name = "PATH", action = clap::ArgAction::Append)]
    pub files: Vec<PathBuf>,

    /// Message body. Required unless `--stdin` is set or at least one
    /// `--file` is attached.
    pub body: Option<String>,

    /// Emit machine-readable JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,

    /// Preview the outgoing call without contacting the Bot API.
    /// Scope and permission checks still run; no bot token is loaded.
    #[arg(long)]
    pub dry_run: bool,
}

#[derive(Debug, Serialize)]
struct SendOutput {
    command: &'static str,
    chat_id: String,
    message_id: String,
}

async fn run_send(args: SendArgs) -> Result<()> {
    let (cfg, _scope) = effective_config()?;
    let directory = dir::load().unwrap_or_default();
    let permissions = crate::cli::echo::load_effective_or_echo(perms::load_effective)?;
    permissions.check_time(TelegramFunction::Send)?;

    let (chat_input, chat_id) = resolve_chat_arg(
        args.chat.as_deref(),
        cfg.default_chat.as_deref(),
        cfg.self_chat_id,
        &directory,
    )?;
    permissions.check_send_chat(&chat_input, chat_id, &directory)?;

    let body = if args.files.is_empty() {
        resolve_body(args.body.as_deref(), args.stdin)?
    } else {
        resolve_body_or_empty(args.body.as_deref(), args.stdin)?
    };
    let len = body.chars().count();
    // Bot API caption cap (1024) is stricter than the plain-text cap
    // (4096); when attachments are present the body rides as the
    // caption, so narrow the check accordingly.
    let body_cap = if args.files.is_empty() {
        TELEGRAM_MAX_MESSAGE_LEN
    } else {
        TELEGRAM_MAX_CAPTION_LEN
    };
    if len > body_cap {
        let label = if args.files.is_empty() {
            "hard limit"
        } else {
            "caption cap (attachments present)"
        };
        return Err(ZadError::Invalid(format!(
            "message body is {len} characters; Telegram's {label} is {body_cap}"
        )));
    }
    if args.files.len() > TELEGRAM_MAX_MEDIA_GROUP {
        return Err(ZadError::Invalid(format!(
            "{} attachments is above Telegram's per-message cap of {TELEGRAM_MAX_MEDIA_GROUP}",
            args.files.len()
        )));
    }
    permissions.check_send_body(&body)?;

    let infos: Vec<AttachmentInfo> = args
        .files
        .iter()
        .map(|p| {
            AttachmentInfo::probe(p).map_err(|e| {
                ZadError::Invalid(format!("attachment `{}` not readable: {e}", p.display()))
            })
        })
        .collect::<Result<_>>()?;
    permissions.check_send_attachments(&infos)?;

    let http = telegram_http_for("messages.send", args.dry_run)?;
    let message_id = http.send(chat_id, &body, &args.files).await?;

    // When --dry-run is active the transport already emitted a preview
    // record (human summary via `tracing::info!`, JSON payload on
    // stdout). Skip the trailing "Sent …" / SendOutput print so we
    // never claim success for an operation we didn't actually perform.
    if args.dry_run {
        return Ok(());
    }
    if crate::cli::echo::echo_active() {
        crate::cli::echo::render_and_clear(args.json);
        return Ok(());
    }

    if args.json {
        let out = SendOutput {
            command: "telegram.send",
            chat_id: chat_id.to_string(),
            message_id: message_id.to_string(),
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
    } else {
        println!("Sent message {message_id} to chat {chat_id}.");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// read
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct ReadArgs {
    /// Chat to read from. Same accepted formats as `--chat` on `send`.
    #[arg(long)]
    pub chat: String,

    /// Maximum number of messages to fetch (1–100). Defaults to 20.
    #[arg(long, default_value_t = 20)]
    pub limit: usize,

    /// Emit machine-readable JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Serialize)]
struct ReadOutput {
    command: &'static str,
    chat_id: String,
    count: usize,
    messages: Vec<ReadMessage>,
}

#[derive(Debug, Serialize)]
struct ReadMessage {
    id: String,
    author: String,
    body: String,
}

async fn run_read(args: ReadArgs) -> Result<()> {
    if args.limit == 0 || args.limit > 100 {
        return Err(ZadError::Invalid(
            "--limit must be between 1 and 100".into(),
        ));
    }
    let (cfg, _scope) = effective_config()?;
    let directory = dir::load().unwrap_or_default();
    let permissions = crate::cli::echo::load_effective_or_echo(perms::load_effective)?;
    permissions.check_time(TelegramFunction::Read)?;

    let (chat_input, chat_id) =
        resolve_chat_arg(Some(&args.chat), None, cfg.self_chat_id, &directory)?;
    permissions.check_read_chat(&chat_input, chat_id, &directory)?;

    let http = telegram_http_for("messages.read", false)?;
    let msgs = http.history(chat_id, args.limit).await?;

    if crate::cli::echo::echo_active() {
        crate::cli::echo::render_and_clear(args.json);
        return Ok(());
    }

    if args.json {
        let out = ReadOutput {
            command: "telegram.read",
            chat_id: chat_id.to_string(),
            count: msgs.len(),
            messages: msgs
                .iter()
                .map(|m| ReadMessage {
                    id: m.id.to_string(),
                    author: m.author.clone(),
                    body: m.body.clone(),
                })
                .collect(),
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
        return Ok(());
    }

    if msgs.is_empty() {
        println!("(no messages — `getUpdates` is forward-only; see `zad man telegram`)");
        return Ok(());
    }
    // Print oldest-first so a human reads top-to-bottom in chronological
    // order. `history` returned newest-first.
    for m in msgs.iter().rev() {
        println!("[{}] <{}> {}", m.id, m.author, m.body);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// listen
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct ListenArgs {
    /// Chat to stream. Same accepted formats as `--chat` on `send`/`read`.
    #[arg(long)]
    pub chat: String,

    /// Server-side long-poll seconds (1-50; Telegram caps the timeout
    /// at 50). Higher values mean fewer HTTP round-trips when the
    /// queue is idle, at the cost of slightly slower Ctrl-C latency.
    #[arg(long, default_value_t = 30, value_parser = clap::value_parser!(u32).range(1..=50))]
    pub timeout: u32,

    /// Emit one JSON object per message (NDJSON) instead of the
    /// human-readable default.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Serialize)]
struct ListenLine<'a> {
    command: &'static str,
    chat_id: String,
    id: String,
    author: &'a str,
    body: &'a str,
}

async fn run_listen(args: ListenArgs) -> Result<()> {
    let (cfg, _scope) = effective_config()?;
    let directory = dir::load().unwrap_or_default();
    let permissions = crate::cli::echo::load_effective_or_echo(perms::load_effective)?;
    permissions.check_time(TelegramFunction::Listen)?;

    let (chat_input, chat_id) =
        resolve_chat_arg(Some(&args.chat), None, cfg.self_chat_id, &directory)?;
    permissions.check_listen_chat(&chat_input, chat_id, &directory)?;

    let transport = telegram_http_for("messages.read", false)?;

    if crate::cli::echo::echo_active() {
        crate::cli::echo::render_and_clear(args.json);
        return Ok(());
    }

    use std::io::Write;
    let mut offset: Option<i64> = None;
    loop {
        tokio::select! {
            _ = tokio::signal::ctrl_c() => return Ok(()),
            res = transport.listen_updates(offset, args.timeout) => {
                let (msgs, next) = res?;
                let mut stdout = std::io::stdout().lock();
                for m in msgs.iter().filter(|m| m.chat == chat_id) {
                    if args.json {
                        let line = ListenLine {
                            command: "telegram.listen",
                            chat_id: chat_id.to_string(),
                            id: m.id.to_string(),
                            author: &m.author,
                            body: &m.body,
                        };
                        writeln!(stdout, "{}", serde_json::to_string(&line).unwrap()).ok();
                    } else {
                        writeln!(stdout, "[{}] <{}> {}", m.id, m.author, m.body).ok();
                    }
                }
                stdout.flush().ok();
                if let Some(n) = next {
                    offset = Some(n);
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// chats
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct ChatsArgs {
    /// Emit machine-readable JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Serialize)]
struct ChatsOutput {
    command: &'static str,
    count: usize,
    chats: Vec<ChatRow>,
}

#[derive(Debug, Serialize)]
struct ChatRow {
    id: String,
    title: String,
    kind: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    username: Option<String>,
    source: &'static str,
}

async fn run_chats(args: ChatsArgs) -> Result<()> {
    let (_cfg, _scope) = effective_config()?;
    let directory = dir::load().unwrap_or_default();
    let permissions = crate::cli::echo::load_effective_or_echo(perms::load_effective)?;
    permissions.check_time(TelegramFunction::Chats)?;
    if crate::cli::echo::echo_active() {
        crate::cli::echo::render_and_clear(args.json);
        return Ok(());
    }

    let http = telegram_http_for("chats", false)?;
    let observed = http.list_chats().await?;

    // Merge observed chats with the local directory cache so an
    // operator sees every chat zad knows about, not just the ones
    // whose updates happen to be buffered right now. Observed entries
    // override directory rows when they share an id so kind/username
    // come from the live data where possible.
    let mut by_id: std::collections::BTreeMap<i64, ChatRow> = std::collections::BTreeMap::new();
    for (name, id_s) in &directory.chats {
        if let Ok(id) = id_s.parse::<i64>() {
            by_id.entry(id).or_insert_with(|| ChatRow {
                id: id.to_string(),
                title: name.clone(),
                kind: "unknown".into(),
                username: None,
                source: "directory",
            });
        }
    }
    for c in &observed {
        by_id.insert(
            c.id,
            ChatRow {
                id: c.id.to_string(),
                title: c.title.clone(),
                kind: c.kind.clone(),
                username: c.username.clone(),
                source: "observed",
            },
        );
    }
    let rows: Vec<ChatRow> = by_id.into_values().collect();

    if args.json {
        let out = ChatsOutput {
            command: "telegram.chats",
            count: rows.len(),
            chats: rows,
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
        return Ok(());
    }

    if rows.is_empty() {
        println!("(no chats — run `zad telegram discover` once the bot has seen traffic)");
        return Ok(());
    }
    println!("{:<20}  {:<10}  {:<10}  TITLE", "ID", "KIND", "SOURCE");
    for r in &rows {
        println!(
            "{:<20}  {:<10}  {:<10}  {}",
            r.id, r.kind, r.source, r.title
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// discover
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct DiscoverArgs {
    /// Emit machine-readable JSON instead of a human-readable summary.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Serialize)]
struct DiscoverOutput {
    command: &'static str,
    chats: usize,
    added: usize,
    skipped: usize,
    warnings: Vec<String>,
}

async fn run_discover(args: DiscoverArgs) -> Result<()> {
    let (_cfg, _scope) = effective_config()?;
    let permissions = crate::cli::echo::load_effective_or_echo(perms::load_effective)?;
    permissions.check_time(TelegramFunction::Discover)?;
    if crate::cli::echo::echo_active() {
        crate::cli::echo::render_and_clear(args.json);
        return Ok(());
    }

    let http = telegram_http_for("chats", false)?;
    let observed = http.list_chats().await?;

    let mut directory = dir::load().unwrap_or_default();
    let mut added = 0usize;
    let mut skipped = 0usize;
    let warnings: Vec<String> = vec![];

    for c in &observed {
        // Silently skip chats the policy denies from discovery — the
        // walk is best-effort and shouldn't fail the whole call.
        if permissions
            .check_discover_chat(&c.title, c.id, &directory)
            .is_err()
        {
            skipped += 1;
            continue;
        }
        let key = c.title.clone();
        let id_s = c.id.to_string();
        match directory.chats.get(&key) {
            Some(existing) if existing == &id_s => {}
            _ => {
                directory.chats.insert(key, id_s);
                added += 1;
            }
        }
    }

    directory.generated_at_unix = Some(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
    );
    dir::save(&directory)?;

    if args.json {
        let out = DiscoverOutput {
            command: "telegram.discover",
            chats: observed.len(),
            added,
            skipped,
            warnings: warnings.clone(),
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
    } else {
        let total = observed.len();
        println!("Observed {total} chat(s); added {added}, skipped {skipped} (denied by policy).");
        for w in &warnings {
            crate::output::warn(w);
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// credential / config plumbing
// ---------------------------------------------------------------------------

enum EffectiveScope {
    Global,
    Local(String),
}

fn require_telegram_enabled() -> Result<()> {
    let project_path = config::path::project_config_path()?;
    let project_cfg = config::load_from(&project_path)?;
    if !project_cfg.has_service("telegram") {
        return Err(ZadError::Invalid(format!(
            "telegram is not enabled for this project ({}). \
             Run `zad service enable telegram` first.",
            project_path.display()
        )));
    }
    Ok(())
}

fn effective_config() -> Result<(TelegramServiceCfg, EffectiveScope)> {
    require_telegram_enabled()?;

    let slug = config::path::project_slug()?;
    let local_path = config::path::project_service_config_path_for(&slug, "telegram")?;
    if let Some(cfg) = config::load_flat::<TelegramServiceCfg>(&local_path)? {
        return Ok((cfg, EffectiveScope::Local(slug)));
    }
    let global_path = config::path::global_service_config_path("telegram")?;
    if let Some(cfg) = config::load_flat::<TelegramServiceCfg>(&global_path)? {
        return Ok((cfg, EffectiveScope::Global));
    }
    Err(ZadError::Invalid(format!(
        "no Telegram credentials found for this project.\n\
         looked in:\n  {}\n  {}",
        local_path.display(),
        global_path.display()
    )))
}

fn load_token(scope: &EffectiveScope) -> Result<String> {
    let account = match scope {
        EffectiveScope::Global => secrets::account("telegram", "bot", Scope::Global),
        EffectiveScope::Local(slug) => secrets::account("telegram", "bot", Scope::Project(slug)),
    };
    secrets::load(&account)?.ok_or_else(|| {
        ZadError::Invalid(format!(
            "bot token missing from keychain (account `{account}`). \
             Re-run `zad service create telegram` to reinstall it."
        ))
    })
}

/// Resolve config + token + scope set into a ready-to-call transport,
/// failing fast with [`ZadError::ScopeDenied`] if `required` isn't
/// declared. The fail-fast scope check happens *before* the keychain
/// read, so a denied op never touches secrets; [`TelegramHttp`] also
/// guards the same scope internally for library-level callers.
///
/// When `dry_run` is `true` the scope check still runs (so preview
/// respects the caller's policy boundary), but the keychain read is
/// skipped and a [`DryRunTelegramTransport`] is returned instead of a
/// live client. That lets `--dry-run` work before the operator has
/// configured a bot, and guarantees no token is ever loaded into
/// memory for a preview.
fn telegram_http_for(required: &'static str, dry_run: bool) -> Result<Box<dyn TelegramTransport>> {
    let (cfg, scope) = effective_config()?;
    let config_path = match &scope {
        EffectiveScope::Local(slug) => {
            config::path::project_service_config_path_for(slug, "telegram")?
        }
        EffectiveScope::Global => config::path::global_service_config_path("telegram")?,
    };
    let scopes: std::collections::BTreeSet<String> = cfg.scopes.iter().cloned().collect();
    if !scopes.contains(required) {
        return Err(ZadError::ScopeDenied {
            service: "telegram",
            scope: required,
            config_path,
        });
    }
    if dry_run || crate::cli::echo::echo_active() {
        let sink = if crate::cli::echo::echo_active() {
            crate::cli::echo::dry_run_sink_for_echo()
        } else {
            default_dry_run_sink()
        };
        return Ok(Box::new(DryRunTelegramTransport::new(sink)));
    }
    let token = load_token(&scope)?;
    Ok(Box::new(TelegramHttp::new(&token, scopes, config_path)))
}

fn resolve_chat_arg(
    flag: Option<&str>,
    default: Option<&str>,
    self_chat_id: Option<i64>,
    directory: &Directory,
) -> Result<(String, i64)> {
    let raw = flag.or(default).ok_or_else(|| {
        ZadError::Invalid(
            "no chat specified: pass --chat <ID|@username|name> or set `default_chat` in the config"
                .into(),
        )
    })?;
    if raw.eq_ignore_ascii_case("@me") {
        return match self_chat_id {
            Some(id) => Ok((raw.to_string(), id)),
            None => Err(ZadError::Invalid(
                "`@me` has no self-chat configured. Run `zad telegram self capture` \
                 to poll for your first message to the bot, or \
                 `zad telegram self set <id>` if you already know the id."
                    .into(),
            )),
        };
    }
    let id = directory.resolve_chat(raw).ok_or_else(|| {
        let key = raw.strip_prefix('@').unwrap_or(raw);
        ZadError::Invalid(format!(
            "--chat `{raw}` is neither a chat_id nor a known directory entry. \
             Run `zad telegram discover` or map it manually with \
             `zad telegram directory set {key} <id>`."
        ))
    })?;
    Ok((raw.to_string(), id))
}

fn resolve_body(positional: Option<&str>, from_stdin: bool) -> Result<String> {
    resolve_body_inner(positional, from_stdin, false)
}

/// Same as [`resolve_body`] but tolerates an empty result, for send
/// paths that carry at least one attachment (the caption on a
/// `sendDocument` / `sendMediaGroup` is optional).
fn resolve_body_or_empty(positional: Option<&str>, from_stdin: bool) -> Result<String> {
    resolve_body_inner(positional, from_stdin, true)
}

fn resolve_body_inner(
    positional: Option<&str>,
    from_stdin: bool,
    allow_empty: bool,
) -> Result<String> {
    if from_stdin {
        use std::io::Read;
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf).map_err(|e| {
            ZadError::Invalid(format!("failed to read message body from stdin: {e}"))
        })?;
        let trimmed = buf.trim_end_matches(['\n', '\r']).to_string();
        if trimmed.is_empty() && !allow_empty {
            return Err(ZadError::Invalid("message body is empty (stdin)".into()));
        }
        return Ok(trimmed);
    }
    match positional {
        Some(b) if !b.is_empty() => Ok(b.to_string()),
        Some(_) if allow_empty => Ok(String::new()),
        None if allow_empty => Ok(String::new()),
        _ => Err(ZadError::Invalid(
            "missing message body: pass it as a positional arg, --stdin, or attach at least one --file".into(),
        )),
    }
}

// ---------------------------------------------------------------------------
// directory
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct DirectoryArgs {
    #[command(subcommand)]
    pub action: Option<DirectoryAction>,

    /// When no subcommand is given, print the directory as JSON.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Subcommand)]
pub enum DirectoryAction {
    /// Upsert a name -> chat_id mapping.
    Set(DirectorySetArgs),
    /// Remove a single mapping. Silent no-op if the key is absent.
    Remove(DirectoryRemoveArgs),
    /// Wipe every entry. Use with `--force`.
    Clear(DirectoryClearArgs),
}

#[derive(Debug, Args)]
pub struct DirectorySetArgs {
    /// Human-readable name to map from.
    pub name: String,
    /// Signed chat_id (groups/supergroups are negative).
    pub id: String,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct DirectoryRemoveArgs {
    pub name: String,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct DirectoryClearArgs {
    #[arg(long)]
    pub force: bool,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Serialize)]
struct DirectoryOutput<'a> {
    command: &'static str,
    path: String,
    generated_at_unix: Option<u64>,
    chats: &'a std::collections::BTreeMap<String, String>,
}

#[derive(Debug, Serialize)]
struct DirectoryMutation {
    command: &'static str,
    name: String,
    id: Option<String>,
    removed: bool,
}

fn run_directory(args: DirectoryArgs) -> Result<()> {
    require_telegram_enabled()?;
    match args.action {
        None => run_directory_list(args.json),
        Some(DirectoryAction::Set(a)) => run_directory_set(a),
        Some(DirectoryAction::Remove(a)) => run_directory_remove(a),
        Some(DirectoryAction::Clear(a)) => run_directory_clear(a),
    }
}

fn run_directory_list(json: bool) -> Result<()> {
    let path = dir::path_current()?;
    let directory = dir::load_from(&path)?;
    if json {
        let out = DirectoryOutput {
            command: "telegram.directory",
            path: path.display().to_string(),
            generated_at_unix: directory.generated_at_unix,
            chats: &directory.chats,
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
        return Ok(());
    }
    if directory.total() == 0 {
        println!("(empty) {}", path.display());
        println!("Run `zad telegram discover` to populate it (once implemented),");
        println!("or add entries manually with `zad telegram directory set <name> <id>`.");
        return Ok(());
    }
    println!("# {}", path.display());
    if !directory.chats.is_empty() {
        println!("\n[chats]");
        for (n, id) in &directory.chats {
            println!("  {n:<32}  {id}");
        }
    }
    Ok(())
}

fn run_directory_set(args: DirectorySetArgs) -> Result<()> {
    let id = parse_chat_id(&args.id)?;
    let path = dir::path_current()?;
    let mut directory = dir::load_from(&path)?;
    directory.chats.insert(args.name.clone(), id.to_string());
    dir::save_to(&path, &directory)?;

    if args.json {
        let out = DirectoryMutation {
            command: "telegram.directory.set",
            name: args.name,
            id: Some(id.to_string()),
            removed: false,
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
    } else {
        println!("Mapped chat `{}` -> {id} in {}.", args.name, path.display());
    }
    Ok(())
}

fn run_directory_remove(args: DirectoryRemoveArgs) -> Result<()> {
    let path = dir::path_current()?;
    let mut directory = dir::load_from(&path)?;
    let removed = directory.chats.remove(&args.name).is_some();
    if removed {
        dir::save_to(&path, &directory)?;
    }

    if args.json {
        let out = DirectoryMutation {
            command: "telegram.directory.remove",
            name: args.name,
            id: None,
            removed,
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
    } else if removed {
        println!("Removed chat `{}` from {}.", args.name, path.display());
    } else {
        println!("No chat entry named `{}`.", args.name);
    }
    Ok(())
}

fn run_directory_clear(args: DirectoryClearArgs) -> Result<()> {
    if !args.force {
        return Err(ZadError::Invalid(
            "refusing to clear the directory without --force".into(),
        ));
    }
    let path = dir::path_current()?;
    let directory = Directory::default();
    dir::save_to(&path, &directory)?;
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "command": "telegram.directory.clear",
                "path": path.display().to_string(),
            }))
            .unwrap()
        );
    } else {
        println!("Cleared {}.", path.display());
    }
    Ok(())
}

fn parse_chat_id(v: &str) -> Result<i64> {
    v.parse::<i64>().map_err(|_| {
        ZadError::Invalid(format!(
            "<id> must be a signed decimal chat_id (groups are negative), got `{v}`"
        ))
    })
}

// ---------------------------------------------------------------------------
// permissions — inspect / scaffold / dry-run the permissions policy
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct PermissionsArgs {
    #[command(subcommand)]
    pub action: Option<PermissionsAction>,

    /// When no subcommand is given, behave like `show`.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Subcommand)]
pub enum PermissionsAction {
    /// Print the effective policy (global + local) for this project.
    Show(PermissionsShowArgs),
    /// Write a starter `permissions.toml` at the selected scope.
    Init(PermissionsInitArgs),
    /// Print the paths considered for this project, in precedence
    /// order.
    Path(PermissionsPathArgs),
    /// Dry-run: ask whether a proposed action would be admitted
    /// *without* hitting the Bot API. Useful for agents that want to
    /// pre-flight.
    Check(PermissionsCheckArgs),
    /// Staged-commit workflow: queue mutations in a `.pending` file and
    /// only sign on `commit`. See `cli::permissions`.
    #[command(flatten)]
    Staging(crate::cli::permissions::StagingAction),
}

#[derive(Debug, Args)]
pub struct PermissionsShowArgs {
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct PermissionsInitArgs {
    /// Write to the project-local `permissions.toml`. Default is
    /// global.
    #[arg(long)]
    pub local: bool,

    /// Overwrite any existing file at that scope.
    #[arg(long)]
    pub force: bool,

    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct PermissionsPathArgs {
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct PermissionsCheckArgs {
    /// Function to check: `send`, `read`, `chats`, `discover`.
    #[arg(long)]
    pub function: String,

    /// Chat to test against the chats list.
    #[arg(long)]
    pub chat: Option<String>,

    /// Body to test against `content` rules (applies only to `send`).
    #[arg(long)]
    pub body: Option<String>,

    #[arg(long)]
    pub json: bool,
}

fn run_permissions(args: PermissionsArgs) -> Result<()> {
    match args.action {
        None => run_permissions_show(PermissionsShowArgs { json: args.json }),
        Some(PermissionsAction::Show(a)) => run_permissions_show(a),
        Some(PermissionsAction::Init(a)) => run_permissions_init(a),
        Some(PermissionsAction::Path(a)) => run_permissions_path(a),
        Some(PermissionsAction::Check(a)) => run_permissions_check(a),
        Some(PermissionsAction::Staging(a)) => {
            crate::cli::permissions::run::<perms::PermissionsService>(a)
        }
    }
}

#[derive(Debug, Serialize)]
struct PermissionsShowOutput {
    command: &'static str,
    global: PermissionsScopeBlock,
    local: PermissionsScopeBlock,
}

#[derive(Debug, Serialize)]
struct PermissionsScopeBlock {
    path: String,
    present: bool,
}

fn run_permissions_show(args: PermissionsShowArgs) -> Result<()> {
    let global_p = perms::global_path()?;
    let local_p = perms::local_path_current()?;
    let global_present = global_p.exists();
    let local_present = local_p.exists();

    // Pre-load to surface any compile errors up front, before
    // printing.
    let effective = perms::load_effective()?;
    let _ = effective;

    if args.json {
        let out = PermissionsShowOutput {
            command: "telegram.permissions.show",
            global: PermissionsScopeBlock {
                path: global_p.display().to_string(),
                present: global_present,
            },
            local: PermissionsScopeBlock {
                path: local_p.display().to_string(),
                present: local_present,
            },
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
        return Ok(());
    }

    println!("# permissions");
    println!(
        "  global : {} ({})",
        global_p.display(),
        if global_present {
            "present"
        } else {
            "not present (no restrictions at this scope)"
        }
    );
    println!(
        "  local  : {} ({})",
        local_p.display(),
        if local_present {
            "present"
        } else {
            "not present (no restrictions at this scope)"
        }
    );
    println!();
    if !global_present && !local_present {
        println!("No permission files found. Every declared scope is currently unrestricted.");
        println!("Run `zad telegram permissions init` to scaffold a starter policy.");
        return Ok(());
    }
    for p in [&global_p, &local_p] {
        if !p.exists() {
            continue;
        }
        println!("## {}", p.display());
        match std::fs::read_to_string(p) {
            Ok(body) => {
                for line in body.lines() {
                    println!("  {line}");
                }
            }
            Err(e) => println!("  (failed to read: {e})"),
        }
        println!();
    }
    Ok(())
}

#[derive(Debug, Serialize)]
struct PermissionsInitOutput {
    command: &'static str,
    scope: &'static str,
    path: String,
    written: bool,
}

fn run_permissions_init(args: PermissionsInitArgs) -> Result<()> {
    let (path, scope) = if args.local {
        (perms::local_path_current()?, "local")
    } else {
        (perms::global_path()?, "global")
    };
    if path.exists() && !args.force {
        return Err(ZadError::Invalid(format!(
            "permissions file already exists at {}. Pass --force to overwrite.",
            path.display()
        )));
    }
    let template = perms::starter_template();
    let key = zad::permissions::signing::load_or_create_from_keychain()?;
    zad::permissions::signing::write_public_key_cache(&key)?;
    perms::save_file(&path, &template, &key)?;
    if args.json {
        let out = PermissionsInitOutput {
            command: "telegram.permissions.init",
            scope,
            path: path.display().to_string(),
            written: true,
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
    } else {
        println!("Wrote starter permissions ({scope}): {}", path.display());
        println!("Signed with key {}.", key.fingerprint());
        println!("Review it; the defaults deny admin-like chats.");
    }
    Ok(())
}

#[derive(Debug, Serialize)]
struct PermissionsPathOutput {
    command: &'static str,
    global: String,
    local: String,
}

fn run_permissions_path(args: PermissionsPathArgs) -> Result<()> {
    let global_p = perms::global_path()?;
    let local_p = perms::local_path_current()?;
    if args.json {
        let out = PermissionsPathOutput {
            command: "telegram.permissions.path",
            global: global_p.display().to_string(),
            local: local_p.display().to_string(),
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
    } else {
        println!("{}", global_p.display());
        println!("{}", local_p.display());
    }
    Ok(())
}

#[derive(Debug, Serialize)]
struct PermissionsCheckOutput {
    command: &'static str,
    function: String,
    allowed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    config_path: Option<String>,
}

fn run_permissions_check(args: PermissionsCheckArgs) -> Result<()> {
    let function = parse_function(&args.function)?;
    let permissions = perms::load_effective()?;
    let directory = dir::load().unwrap_or_default();

    let mut outcome: Result<()> = Ok(());
    outcome = outcome.and_then(|()| permissions.check_time(function));

    if outcome.is_ok()
        && let Some(c) = &args.chat
    {
        let id = directory.resolve_chat(c).unwrap_or(0);
        outcome = match function {
            TelegramFunction::Send => permissions.check_send_chat(c, id, &directory),
            TelegramFunction::Read => permissions.check_read_chat(c, id, &directory),
            TelegramFunction::Listen => permissions.check_listen_chat(c, id, &directory),
            TelegramFunction::Chats => permissions.check_chats_chat(c, id, &directory),
            TelegramFunction::Discover => permissions.check_discover_chat(c, id, &directory),
        };
    }

    if outcome.is_ok()
        && function == TelegramFunction::Send
        && let Some(body) = &args.body
    {
        outcome = permissions.check_send_body(body);
    }

    let (allowed, reason, config_path) = match outcome {
        Ok(()) => (true, None, None),
        Err(ZadError::PermissionDenied {
            reason,
            config_path,
            ..
        }) => (false, Some(reason), Some(config_path.display().to_string())),
        Err(e) => return Err(e),
    };

    if args.json {
        let out = PermissionsCheckOutput {
            command: "telegram.permissions.check",
            function: args.function.clone(),
            allowed,
            reason,
            config_path,
        };
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
    } else if allowed {
        println!("allow");
    } else {
        println!(
            "deny — {}",
            reason.as_deref().unwrap_or("unspecified reason")
        );
        if let Some(p) = &config_path {
            println!("  config: {p}");
        }
    }
    if !allowed {
        std::process::exit(1);
    }
    Ok(())
}

fn parse_function(name: &str) -> Result<TelegramFunction> {
    match name {
        "send" => Ok(TelegramFunction::Send),
        "read" => Ok(TelegramFunction::Read),
        "listen" => Ok(TelegramFunction::Listen),
        "chats" => Ok(TelegramFunction::Chats),
        "discover" => Ok(TelegramFunction::Discover),
        other => Err(ZadError::Invalid(format!(
            "unknown function `{other}`. Expected one of: send, read, listen, chats, discover."
        ))),
    }
}

// ---------------------------------------------------------------------------
// self — manage the `@me` resolution target
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct SelfArgs {
    #[command(subcommand)]
    pub action: Option<SelfAction>,

    /// When no subcommand is given, behave like `show`.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Subcommand)]
pub enum SelfAction {
    /// Print the stored self-chat ID (or note that it's not set).
    Show(SelfShowArgs),
    /// Set the self-chat ID directly. No validation — use `capture`
    /// for a validated setup.
    Set(SelfSetArgs),
    /// Clear the stored self-chat ID.
    Clear(SelfClearArgs),
    /// Poll `getUpdates` for up to 60s waiting for your first message
    /// to the bot, then store that private-chat ID.
    Capture(SelfCaptureArgs),
}

#[derive(Debug, Args)]
pub struct SelfShowArgs {
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct SelfSetArgs {
    /// Your private-chat ID (a signed integer).
    pub chat_id: i64,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct SelfClearArgs {
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct SelfCaptureArgs {
    /// Don't open the bot's `https://t.me/<username>` link in the
    /// system browser. The link is still printed either way.
    #[arg(long)]
    pub no_browser: bool,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Serialize)]
struct SelfOutput {
    command: &'static str,
    self_chat_id: Option<i64>,
}

async fn run_self(args: SelfArgs) -> Result<()> {
    match args.action {
        None => run_self_show(SelfShowArgs { json: args.json }),
        Some(SelfAction::Show(a)) => run_self_show(a),
        Some(SelfAction::Set(a)) => run_self_set(a),
        Some(SelfAction::Clear(a)) => run_self_clear(a),
        Some(SelfAction::Capture(a)) => run_self_capture(a).await,
    }
}

fn run_self_show(args: SelfShowArgs) -> Result<()> {
    let (cfg, _scope) = effective_config()?;
    emit_self(args.json, "telegram.self.show", cfg.self_chat_id)
}

fn run_self_set(args: SelfSetArgs) -> Result<()> {
    let (mut cfg, scope) = effective_config()?;
    cfg.self_chat_id = Some(args.chat_id);
    save_effective_config(&cfg, &scope)?;
    emit_self(args.json, "telegram.self.set", cfg.self_chat_id)
}

fn run_self_clear(args: SelfClearArgs) -> Result<()> {
    let (mut cfg, scope) = effective_config()?;
    cfg.self_chat_id = None;
    save_effective_config(&cfg, &scope)?;
    emit_self(args.json, "telegram.self.clear", None)
}

async fn run_self_capture(args: SelfCaptureArgs) -> Result<()> {
    let (mut cfg, scope) = effective_config()?;
    let token = load_token(&scope)?;
    let client = TelegramHttp::unscoped(&token);
    let identity = client.get_me().await?;
    let captured =
        crate::cli::service_telegram::capture_self_chat(&client, &identity, !args.no_browser)
            .await?;
    match captured {
        Some(c) => {
            cfg.self_chat_id = Some(c.chat_id);
            save_effective_config(&cfg, &scope)?;
            emit_self(args.json, "telegram.self.capture", cfg.self_chat_id)
        }
        None => {
            // User declined at the confirmation prompt or timeout
            // expired. Report the unchanged state rather than erroring —
            // `capture_self_chat` already printed the reason.
            emit_self(args.json, "telegram.self.capture", cfg.self_chat_id)
        }
    }
}

fn emit_self(json: bool, command: &'static str, self_chat_id: Option<i64>) -> Result<()> {
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&SelfOutput {
                command,
                self_chat_id
            })
            .unwrap()
        );
    } else {
        match self_chat_id {
            Some(id) => println!("self chat id: {id}"),
            None => println!("self chat id: not configured"),
        }
    }
    Ok(())
}

fn save_effective_config(cfg: &TelegramServiceCfg, scope: &EffectiveScope) -> Result<()> {
    let path = match scope {
        EffectiveScope::Local(slug) => {
            config::path::project_service_config_path_for(slug, "telegram")?
        }
        EffectiveScope::Global => config::path::global_service_config_path("telegram")?,
    };
    config::save_flat(&path, cfg)
}