todoke 2.4.0

A rule-driven file and URL dispatcher: hands incoming paths (or URLs) to the right handler based on TOML-defined rules.
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
//! TOML + Tera config schema.
//!
//! Two layers:
//! - [`Config`]: the raw TOML deserialization target.
//! - [`ResolvedConfig`]: [`Config`] + pre-compiled regex patterns + validated
//!   cross-references. Everything you actually want to use at dispatch time.
//!
//! Tera expansion happens at dispatch time (not load time) because rule.group
//! and todoke.* templates can reference per-input context.

use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use anyhow::{Context as _, Result, anyhow};
use directories::BaseDirs;
use regex::Regex;
use serde::Deserialize;

use crate::input::InputKind;

pub const DEFAULT_CONFIG_TOML: &str = include_str!("../assets/default.toml");

#[derive(Debug, Clone, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub vars: BTreeMap<String, toml::Value>,
    /// Scalar tool-wide settings (`[options]`). Currently the background
    /// auto-update behaviour.
    #[serde(default)]
    pub options: Options,
    /// Named targets for delivery. Keyed by handler name, referenced from
    /// `rule.to`.
    #[serde(default)]
    pub todoke: BTreeMap<String, Target>,
    #[serde(default)]
    pub rules: Vec<Rule>,
}

/// Tool-wide scalar settings under `[options]`.
#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
pub struct Options {
    /// Background auto-update behaviour. Defaults to [`AutoUpdateMode::Install`]
    /// (opt-out silent install). Overridden at runtime by the
    /// `TODOKE_NO_AUTOUPDATE` env kill-switch, which always wins.
    #[serde(default)]
    pub auto_update: AutoUpdateMode,
    /// Throttle interval between background update checks (humantime, e.g.
    /// `"24h"` / `"1d"` / `"30m"`). Unset => 24h. An unparseable value falls
    /// back to the 24h default at runtime.
    #[serde(default)]
    pub update_interval: Option<String>,
}

/// How todoke handles a newer GitHub release found in the background.
#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AutoUpdateMode {
    /// Never check for or install updates.
    Off,
    /// Check in the background and print a one-line banner when a newer
    /// release exists, but never install it.
    Notify,
    /// Silently download + swap the binary in the background (the default).
    /// The running process keeps the old binary; the new version applies on
    /// the next launch.
    #[default]
    Install,
}

/// A named delivery target. Describes what happens when a rule picks this
/// entry: a command to spawn, optional per-mode arg lists, and optional
/// neovim-specific fields when `kind = "neovim"`.
#[derive(Debug, Clone, Deserialize)]
pub struct Target {
    /// `"exec"` (default) spawns `command` with the resolved args.
    /// `"neovim"` enables msgpack-RPC reuse of a running nvim on `listen`.
    #[serde(default)]
    pub kind: TargetKind,
    pub command: String,
    #[serde(default)]
    pub listen: Option<String>,
    /// Per-mode arg lists. `args.default` (if present) is the fallback when
    /// the rule's `mode` has no matching key in this map.
    #[serde(default)]
    pub args: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Controls whether the exec backend appends each input's display
    /// string as a trailing positional arg after the rendered `args` list.
    ///
    /// - `None` / omitted (**auto**, the default): appended **unless** any
    ///   `args` template references `{{ input }}` / `{{ file_* }}` /
    ///   `{{ url_* }}` — in which case the trailing append is skipped so
    ///   the same value isn't passed twice. `{{ cap.* }}` is **not** a
    ///   signal (cap can be used for extraction unrelated to input
    ///   reconstruction).
    /// - `Some(true)`: force append regardless of templates.
    /// - `Some(false)`: force skip regardless of templates.
    #[serde(default)]
    pub append_inputs: Option<bool>,
    /// Controls whether passthrough-rule argv (`+42`, `-c :set …`, …) is
    /// appended after the rendered `args` list. Same auto / true / false
    /// semantics as [`Self::append_inputs`], but the auto trigger is
    /// a `{{ passthrough }}` reference (any form).
    #[serde(default)]
    pub append_passthrough: Option<bool>,
    /// Set to `true` when the handler is a **GUI** application (neovide,
    /// nvim-qt, vscode, firefox, …). On Windows, detached spawns then use
    /// `CREATE_NO_WINDOW + DETACHED_PROCESS` instead of the default
    /// `cmd /c start` wrapper, so no transient cmd window flashes before
    /// the GUI appears. On Unix this flag is a no-op.
    ///
    /// Leave unset / `false` for console / TUI handlers (nvim in a terminal,
    /// helix, bat, …) — those rely on the fresh console window that
    /// `cmd /c start` allocates.
    #[serde(default)]
    pub gui: bool,
}

impl Target {
    /// Look up the arg list for a given mode, falling back to `args.default`
    /// and then to an empty list.
    pub fn args_for(&self, mode: &str) -> &[String] {
        self.args
            .get(mode)
            .or_else(|| self.args.get("default"))
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }
}

#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TargetKind {
    #[default]
    Exec,
    Neovim,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Rule {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(rename = "match")]
    pub match_: StringOrVec,
    /// Negative filter. When any `exclude` pattern hits the input, this rule
    /// does NOT apply even if `match` hits — todoke keeps looking at
    /// subsequent rules. Accepts a single pattern or an array.
    #[serde(default)]
    pub exclude: Option<StringOrVec>,
    /// Name of a `[todoke.<name>]` entry to deliver the matched input to.
    /// Tera-templated — `to = "{{ vars.gui }}"` works.
    ///
    /// **Optional only for `passthrough = true` rules.** A passthrough
    /// rule with no `to` acts as "collect argv, let another rule decide
    /// the target": at Phase 2b, the passthrough is merged into the
    /// already-built batch that shares its resolved `group` (target
    /// isn't required to match). If no such batch exists, the
    /// passthrough is dropped with a warning. Useful for generic flag
    /// rules like `match = '^[-+]'` that should ride along with whoever
    /// the other rules decided to deliver to.
    ///
    /// Normal (non-passthrough) rules and joined rules still require `to`.
    #[serde(default)]
    pub to: Option<String>,
    #[serde(default)]
    pub group: Option<String>,
    /// Free-form mode string. For `kind = "neovim"` the reserved values
    /// `"remote"` and `"new"` select RPC reuse vs fresh spawn. For
    /// `kind = "exec"` the value is used purely to pick the matching
    /// `target.args.<mode>` list.
    #[serde(default = "default_mode")]
    pub mode: String,
    #[serde(default)]
    pub sync: bool,
    /// Restrict which [`crate::input::InputKind`]s this rule can match.
    /// Accepts a single kind (`"file"`) or an array (`["file", "raw"]`).
    /// Omitted = no restriction (all kinds allowed).
    ///
    /// Needed because auto-detection treats bare words like `HEAD` / `main`
    /// as files — a rule that wants to handle those as git refs should set
    /// `input_type = "raw"` so it only fires for `--as raw HEAD`.
    #[serde(default)]
    pub input_type: Option<InputTypes>,
    /// When true, this rule matches against the space-joined argv (all
    /// inputs concatenated) instead of each input individually. On a hit,
    /// the named capture `input` is re-classified via `Input::from_arg`
    /// and becomes the sole input of the resulting batch; the remaining
    /// captures are available to the target's arg templates as
    /// `{{ cap.<name> }}`.
    ///
    /// Designed for the `$EDITOR=todoke +42 file.txt` pattern where the
    /// caller passes editor-specific flags ahead of the file. Mutually
    /// exclusive with `passthrough`.
    #[serde(default)]
    pub joined: bool,
    /// When true, inputs matched by this rule are NOT opened (no `:edit`,
    /// no URL open, no positional append). Instead, the raw argv string is
    /// injected into the target's start-up argv as a passthrough flag.
    /// Use for rules like `match = '^[-+]'` that catch editor flags
    /// (`+42`, `-c :set ft=...`) and forward them verbatim to the handler
    /// command line.
    ///
    /// Mutually exclusive with `joined` (joined achieves the same effect
    /// via capture-driven arg templates).
    #[serde(default)]
    pub passthrough: bool,
    /// Number of following argv items to **also** forward as passthrough
    /// when this rule matches. Only meaningful when `passthrough = true`.
    ///
    /// Designed for spaced-value editor flags like `-c :set ft=md` where
    /// the value (`:set ft=md`) is its own argv. With `consumes = 1`,
    /// matching `^-c$` on the flag pulls the next argv along so both
    /// strings reach the target's start-up command line intact.
    #[serde(default)]
    pub consumes: usize,
    /// Regex. When set, `-p a.txt b.txt c.txt` style multi-value flags
    /// can be absorbed wholesale: the passthrough rule matches `-p`,
    /// then todoke keeps eating argv until one matches this regex
    /// (or argv ends). The stopper argv itself is NOT consumed.
    ///
    /// Typical values: `'^[-+]'` (stop at next flag), `'^--$'` (stop at
    /// GNU separator). Mutually exclusive with `consumes` and
    /// `consumes_rest`; only valid when `passthrough = true`.
    #[serde(default)]
    pub consumes_until: Option<String>,
    /// Consume every remaining argv as part of this passthrough. Useful
    /// for "trailing args are all for this target" patterns.
    ///
    /// Mutually exclusive with `consumes` and `consumes_until`; only
    /// valid when `passthrough = true`.
    #[serde(default)]
    pub consumes_rest: bool,
}

/// One or many [`InputKind`]s — mirrors [`StringOrVec`] so TOML users can
/// write `input_type = "raw"` or `input_type = ["file", "raw"]`.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum InputTypes {
    One(InputKind),
    Many(Vec<InputKind>),
}

impl InputTypes {
    pub fn contains(&self, kind: InputKind) -> bool {
        match self {
            InputTypes::One(k) => *k == kind,
            InputTypes::Many(v) => v.contains(&kind),
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum StringOrVec {
    One(String),
    Many(Vec<String>),
}

impl StringOrVec {
    pub fn as_slice(&self) -> Vec<&str> {
        match self {
            StringOrVec::One(s) => vec![s.as_str()],
            StringOrVec::Many(v) => v.iter().map(String::as_str).collect(),
        }
    }
}

pub const DEFAULT_GROUP: &str = "default";
pub const DEFAULT_MODE: &str = "remote";

fn default_mode() -> String {
    DEFAULT_MODE.to_string()
}

fn is_template(s: &str) -> bool {
    s.contains("{{") || s.contains("{%")
}

/// Config + ahead-of-time regex compilation + cross-reference validation.
#[derive(Debug)]
pub struct ResolvedConfig {
    pub raw: Config,
    pub rule_regexes: Vec<Vec<Regex>>,
    /// Parallel to [`Self::rule_regexes`]. Empty Vec for rules without an
    /// `exclude` clause.
    pub rule_excludes: Vec<Vec<Regex>>,
    /// Parallel to [`Self::rule_regexes`]. `Some` when the rule has
    /// `consumes_until`, else `None`.
    pub rule_consumes_until: Vec<Option<Regex>>,
}

impl ResolvedConfig {
    pub fn rule(&self, idx: usize) -> &Rule {
        &self.raw.rules[idx]
    }

    pub fn target(&self, name: &str) -> Result<&Target> {
        self.raw
            .todoke
            .get(name)
            .ok_or_else(|| anyhow!("rule references unknown todoke target: {name}"))
    }

    fn compile(raw: Config) -> Result<Self> {
        // validate rule.to references; skip rules whose `to` is a Tera
        // template (e.g. `"{{ vars.gui }}"`) — those resolve at dispatch time
        // and the dispatcher surfaces a clear error if the rendered name is
        // still not a known target.
        for (i, rule) in raw.rules.iter().enumerate() {
            if rule.joined && rule.passthrough {
                return Err(anyhow!(
                    "rule[{i}] ({}) sets both joined = true and passthrough = true — these are mutually exclusive; joined already lets args templates place captures anywhere, so passthrough is redundant",
                    rule.name.as_deref().unwrap_or("<unnamed>"),
                ));
            }
            let consumes_forms = (rule.consumes > 0) as u8
                + rule.consumes_until.is_some() as u8
                + rule.consumes_rest as u8;
            if consumes_forms > 1 {
                return Err(anyhow!(
                    "rule[{i}] ({}) sets more than one of consumes / consumes_until / consumes_rest — pick exactly one",
                    rule.name.as_deref().unwrap_or("<unnamed>"),
                ));
            }
            if consumes_forms > 0 && !rule.passthrough {
                return Err(anyhow!(
                    "rule[{i}] ({}) has consumes* set but passthrough = false — consume options only apply to passthrough rules",
                    rule.name.as_deref().unwrap_or("<unnamed>"),
                ));
            }
            match &rule.to {
                None => {
                    if !rule.passthrough {
                        return Err(anyhow!(
                            "rule[{i}] ({}) has no `to` — only `passthrough = true` rules may omit it (they merge into another rule's batch)",
                            rule.name.as_deref().unwrap_or("<unnamed>"),
                        ));
                    }
                }
                Some(to) => {
                    if is_template(to) {
                        continue;
                    }
                    if !raw.todoke.contains_key(to) {
                        return Err(anyhow!(
                            "rule[{i}] ({}) references unknown todoke target '{}'. Known targets: {}",
                            rule.name.as_deref().unwrap_or("<unnamed>"),
                            to,
                            raw.todoke.keys().cloned().collect::<Vec<_>>().join(", ")
                        ));
                    }
                }
            }
        }

        // compile all match regexes
        let rule_regexes = raw
            .rules
            .iter()
            .enumerate()
            .map(|(i, rule)| {
                rule.match_
                    .as_slice()
                    .iter()
                    .map(|p| {
                        Regex::new(p).with_context(|| {
                            format!("rule[{i}]: failed to compile match pattern '{p}'")
                        })
                    })
                    .collect::<Result<Vec<_>>>()
            })
            .collect::<Result<Vec<_>>>()?;

        // compile all exclude regexes (empty Vec when the rule has no exclude)
        let rule_excludes = raw
            .rules
            .iter()
            .enumerate()
            .map(|(i, rule)| match &rule.exclude {
                None => Ok(Vec::new()),
                Some(patterns) => patterns
                    .as_slice()
                    .iter()
                    .map(|p| {
                        Regex::new(p).with_context(|| {
                            format!("rule[{i}]: failed to compile exclude pattern '{p}'")
                        })
                    })
                    .collect::<Result<Vec<_>>>(),
            })
            .collect::<Result<Vec<_>>>()?;

        let rule_consumes_until = raw
            .rules
            .iter()
            .enumerate()
            .map(|(i, rule)| match &rule.consumes_until {
                None => Ok(None),
                Some(p) => Regex::new(p)
                    .map(Some)
                    .with_context(|| format!("rule[{i}]: failed to compile consumes_until '{p}'")),
            })
            .collect::<Result<Vec<_>>>()?;

        Ok(Self {
            raw,
            rule_regexes,
            rule_excludes,
            rule_consumes_until,
        })
    }
}

/// Resolve which config file todoke should load.
///
/// Priority:
/// 1. Explicit `--config <path>` argument.
/// 2. `$TODOKE_CONFIG` env var.
/// 3. `~/.config/todoke/todoke.toml` on every platform. We deliberately pick
///    the XDG-style layout on Windows too (instead of `%APPDATA%\todoke\`) so
///    the same dotfiles repo works everywhere — the common setup for users
///    of chezmoi / stow / yadm, who put configs under `.config/` on all OSes.
pub fn resolve_path(explicit: Option<&Path>) -> Result<PathBuf> {
    if let Some(p) = explicit {
        return Ok(p.to_path_buf());
    }
    if let Ok(env_path) = std::env::var("TODOKE_CONFIG") {
        return Ok(PathBuf::from(env_path));
    }
    let home = BaseDirs::new()
        .map(|d| d.home_dir().to_path_buf())
        .ok_or_else(|| anyhow!("could not determine home directory"))?;
    Ok(home.join(".config").join("todoke").join("todoke.toml"))
}

/// Load + parse config. Falls back to the embedded default when the file does
/// not exist (but NOT when it exists and is broken — that should always error).
pub fn load(explicit: Option<&Path>) -> Result<ResolvedConfig> {
    let path = resolve_path(explicit)?;
    let (text, source) = if path.exists() {
        let t = std::fs::read_to_string(&path)
            .with_context(|| format!("failed to read config file: {}", path.display()))?;
        (t, Some(path))
    } else {
        (DEFAULT_CONFIG_TOML.to_string(), None)
    };

    let rendered = prerender(&text).with_context(|| {
        source
            .as_ref()
            .map(|p| format!("Tera pre-render failed for {}", p.display()))
            .unwrap_or_else(|| "Tera pre-render failed for embedded default TOML".into())
    })?;

    let raw: Config = toml::from_str(&rendered).with_context(|| {
        source
            .as_ref()
            .map(|p| format!("failed to parse TOML at {}", p.display()))
            .unwrap_or_else(|| "failed to parse embedded default TOML".into())
    })?;

    ResolvedConfig::compile(raw)
}

/// Alternative loader that parses from an explicit string (useful for tests).
#[allow(dead_code)]
pub fn load_from_str(text: &str) -> Result<ResolvedConfig> {
    let rendered = prerender(text).context("Tera pre-render failed")?;
    let raw: Config = toml::from_str(&rendered).context("failed to parse TOML")?;
    ResolvedConfig::compile(raw)
}

/// Pre-render the TOML text through Tera so users can use structural
/// conditionals like `{% if vars.use_neovide %}[editors.X]...{% endif %}` or
/// value-level expressions like `command = "{{ vars.gui }}"`.
///
/// The context exposes:
/// - `vars.*` — extracted from the raw text's `[vars]` / `[vars.*]` sections
///   via a lightweight line scan (so we can populate vars without having to
///   parse the whole — still-templated — file as valid TOML yet).
/// - `env.*` — process env vars.
/// - `is_windows()` / `is_linux()` / `is_mac()` — provided by [`teravars`].
/// - Dispatch-time placeholders (`file_path`, `group`, `rule`, …) are inserted
///   as self-referential strings (`"{{ group }}"`) so those tokens pass
///   through pre-render unchanged and get rendered later with real values in
///   [`crate::dispatcher`].
///
/// `cap` / `passthrough` can't use the self-referential-placeholder trick
/// (they're accessed via subscript / attribute / filter), so instead any
/// `{{ … }}` expression referencing them is hidden from the render pass and
/// restored afterwards — see [`defer_dispatch_exprs`].
pub fn prerender(text: &str) -> Result<String> {
    let vars = extract_vars(text);

    let mut tera = crate::template::new_engine();
    let mut ctx = teravars::Context::new();

    let vars_map: HashMap<String, toml::Value> = vars.into_iter().collect();
    ctx.insert("vars", &vars_map);

    let env_map: HashMap<String, String> = std::env::vars().collect();
    ctx.insert("env", &env_map);

    // Self-referential placeholders keep dispatch-time tokens intact.
    for name in [
        "input",
        "input_type",
        "file_path",
        "file_dir",
        "file_name",
        "file_stem",
        "file_ext",
        "url_scheme",
        "url_host",
        "url_port",
        "url_path",
        "url_query",
        "url_fragment",
        "command_path",
        "command_dir",
        "command_name",
        "command_stem",
        "command_ext",
        "cwd",
        "group",
        "rule",
    ] {
        ctx.insert(name, &format!("{{{{ {name} }}}}"));
    }

    // Defer dispatch-time-only expressions (`cap` / `passthrough`) so pre-render
    // doesn't try to resolve them against an undefined variable and fail — they
    // survive verbatim and are rendered later with real values at dispatch.
    let protected = defer_dispatch_exprs(text);

    // teravars::Engine::render already flattens Tera's nested error chain into
    // a single message (its resilience feature), so the underlying line/column
    // cause reaches the user without walking Error::source by hand here. No
    // extra `.context()` — both callers (`load` / `load_from_str`) already add
    // the "Tera pre-render failed" prefix, so adding it here too doubles it.
    crate::template::render(&mut tera, &protected, &ctx).map(|rendered| restore_deferred(&rendered))
}

/// Sentinels from the Unicode private-use area — vanishingly unlikely to appear
/// in a real config and never produced by Tera itself — used to hide `{{`/`}}`
/// delimiters from the pre-render pass.
const DEFER_OPEN: &str = "\u{E000}";
const DEFER_CLOSE: &str = "\u{E001}";

/// Neutralize `{{ … }}` value expressions that reference dispatch-time-only
/// variables (`cap` / `passthrough`) so [`prerender`] leaves them literal for
/// the dispatch pass to render.
///
/// Unlike the scalar dispatch tokens (`group`, `file_path`, …), which survive
/// pre-render via self-referential placeholders, `cap` / `passthrough` are
/// accessed through subscript / attribute / filter (`cap["1"]`, `cap.name`,
/// `passthrough | join`) — the placeholder trick can't reproduce those, so we
/// hide the whole expression behind private-use sentinels and restore it with
/// [`restore_deferred`] after rendering.
///
/// Scope: only `{{ … }}` value expressions are deferred. `{% for p in
/// passthrough %}` / `{% if … %}` control blocks that reference dispatch-only
/// vars would need block-level handling and are out of scope here (see #95).
/// False positives (e.g. `{{ vars.cap }}`) are harmless: those vars are also
/// present at dispatch, so deferral just moves the render one phase later.
fn defer_dispatch_exprs(text: &str) -> String {
    // Compiled once — pre-render is cold, but a `OnceLock` static avoids
    // recompiling on every config load and matches `input.rs`'s pattern.
    static MUSTACHE: OnceLock<Regex> = OnceLock::new();
    static DISPATCH_REF: OnceLock<Regex> = OnceLock::new();
    let mustache = MUSTACHE.get_or_init(|| Regex::new(r"(?s)\{\{.*?\}\}").expect("static regex"));
    let dispatch_ref =
        DISPATCH_REF.get_or_init(|| Regex::new(r"\b(?:cap|passthrough)\b").expect("static regex"));
    mustache
        .replace_all(text, |caps: &regex::Captures| {
            // `replace_all`'s closure `Replacer` is higher-ranked over the
            // `&Captures` lifetime, so the return value can't borrow from it —
            // it has to be owned. (Borrowing non-matching blocks would need a
            // manual `captures_iter` loop, not worth it: the closure only fires
            // per `{{ … }}` match, and pre-render is cold.)
            let expr = &caps[0];
            if dispatch_ref.is_match(expr) {
                expr.replace("{{", DEFER_OPEN).replace("}}", DEFER_CLOSE)
            } else {
                expr.to_string()
            }
        })
        .into_owned()
}

/// Restore the `{{`/`}}` delimiters hidden by [`defer_dispatch_exprs`].
fn restore_deferred(text: &str) -> String {
    text.replace(DEFER_OPEN, "{{").replace(DEFER_CLOSE, "}}")
}

/// Scan raw text for `[vars]` / `[vars.*]` sections and parse them as TOML.
/// Tera block lines (`{% … %}`) that may live in between sections are
/// stripped before parsing. Any parse failure yields an empty map so the
/// later pre-render pass can surface a clearer error.
fn extract_vars(text: &str) -> BTreeMap<String, toml::Value> {
    let mut buf = String::new();
    let mut in_vars = false;
    for line in text.lines() {
        let tr = line.trim_start();
        if let Some(rest) = tr.strip_prefix('[') {
            // Parse out the section name up to the closing ']'. Handles both
            // `[vars]` and `[vars.sub]`; ignores `[[array_of_tables]]`.
            let is_aot = rest.starts_with('[');
            let inner = rest
                .trim_start_matches('[')
                .split(']')
                .next()
                .unwrap_or("")
                .trim();
            in_vars = !is_aot && (inner == "vars" || inner.starts_with("vars."));
        }
        if in_vars {
            buf.push_str(line);
            buf.push('\n');
        }
    }
    if buf.is_empty() {
        return BTreeMap::new();
    }
    // Drop any Tera control blocks that slipped into buf between a [vars*]
    // section and the next section header; they are not valid TOML.
    let tera_block = Regex::new(r"(?s)\{%.*?%\}").expect("static regex");
    let cleaned = tera_block.replace_all(&buf, "");
    #[derive(Deserialize, Default)]
    struct VarsOnly {
        #[serde(default)]
        vars: BTreeMap<String, toml::Value>,
    }
    toml::from_str::<VarsOnly>(&cleaned)
        .map(|w| w.vars)
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn options_default_when_absent_is_install() {
        // No `[options]` table at all => auto_update defaults to Install
        // (opt-out silent install) and update_interval is None.
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert_eq!(cfg.raw.options.auto_update, AutoUpdateMode::Install);
        assert_eq!(cfg.raw.options.update_interval, None);
    }

    #[test]
    fn load_accepts_positional_capture_in_args() {
        // Regression for #95: a config value referencing a numbered capture
        // must survive pre-render (cap is only known at dispatch) and reach the
        // parsed config verbatim, ready for the dispatch-time render.
        let text = r#"
            [[rules]]
            match = "issue:(\\d+)"
            to = "gh-issue"

            [todoke.gh-issue]
            command = "echo"
            args.default = ['https://example.com/issues/{{ cap["1"] }}']
        "#;
        let cfg = load_from_str(text).expect("config with a cap reference should load");
        let arg = &cfg.raw.todoke["gh-issue"].args["default"][0];
        assert_eq!(arg, r#"https://example.com/issues/{{ cap["1"] }}"#);
    }

    #[test]
    fn load_accepts_named_capture_and_passthrough_filter() {
        // Named captures and `passthrough`-filter expressions are dispatch-only
        // too and must survive pre-render literally.
        let text = r#"
            [[rules]]
            match = "(?P<id>\\d+)"
            to = "a"

            [todoke.a]
            command = "echo"
            args.default = ["{{ cap.id }}", "{{ passthrough | join(sep=' ') }}"]
        "#;
        let cfg = load_from_str(text).expect("named cap + passthrough filter should load");
        let args = &cfg.raw.todoke["a"].args["default"];
        assert_eq!(args[0], "{{ cap.id }}");
        assert_eq!(args[1], "{{ passthrough | join(sep=' ') }}");
    }

    #[test]
    fn deferred_capture_renders_at_dispatch() {
        // The end-to-end path the isolated tests missed (#95): a load-deferred
        // `{{ cap["1"] }}` must render with a real capture at dispatch time.
        use crate::template::{Context as TemplateCtx, build_context, new_engine, render};

        let text = r#"
            [[rules]]
            match = "issue:(\\d+)"
            to = "gh-issue"

            [todoke.gh-issue]
            command = "echo"
            args.default = ['https://example.com/issues/{{ cap["1"] }}']
        "#;
        let cfg = load_from_str(text).unwrap();
        let tmpl = cfg.raw.todoke["gh-issue"].args["default"][0].clone();

        let mut cap = BTreeMap::new();
        cap.insert("0".to_string(), "issue:42".to_string());
        cap.insert("1".to_string(), "42".to_string());
        let passthrough: Vec<String> = Vec::new();
        let ctx = build_context(TemplateCtx {
            input: None,
            command: "echo",
            cwd: "/cwd",
            group: "",
            rule_name: "gh-issue",
            vars: &BTreeMap::new(),
            cap: &cap,
            passthrough: &passthrough,
        });
        let mut engine = new_engine();
        let out = render(&mut engine, &tmpl, &ctx).unwrap();
        assert_eq!(out, "https://example.com/issues/42");
    }

    #[test]
    fn options_auto_update_off_parses() {
        let text = r#"
            [options]
            auto_update = "off"

            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert_eq!(cfg.raw.options.auto_update, AutoUpdateMode::Off);
    }

    #[test]
    fn options_auto_update_notify_parses() {
        let text = r#"
            [options]
            auto_update = "notify"

            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert_eq!(cfg.raw.options.auto_update, AutoUpdateMode::Notify);
    }

    #[test]
    fn options_auto_update_install_parses() {
        let text = r#"
            [options]
            auto_update = "install"

            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert_eq!(cfg.raw.options.auto_update, AutoUpdateMode::Install);
    }

    #[test]
    fn options_empty_table_keeps_install_default() {
        // An `[options]` table with no keys still resolves to the Install
        // default (serde field default), matching the embedded config.
        let text = r#"
            [options]

            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert_eq!(cfg.raw.options.auto_update, AutoUpdateMode::Install);
    }

    #[test]
    fn options_update_interval_parses() {
        let text = r#"
            [options]
            update_interval = "12h"

            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert_eq!(cfg.raw.options.update_interval.as_deref(), Some("12h"));
    }

    #[test]
    fn parses_default_config() {
        let cfg = load_from_str(DEFAULT_CONFIG_TOML).expect("default config must parse");
        assert!(cfg.raw.todoke.contains_key("nvim"));
        let names: Vec<&str> = cfg
            .raw
            .rules
            .iter()
            .map(|r| r.name.as_deref().unwrap_or(""))
            .collect();
        assert_eq!(
            names,
            vec!["editor-callback", "nvim-value-flag", "any-flag", "default"],
        );
        // Only editor-callback blocks; passthrough/default rules don't.
        assert!(cfg.raw.rules[0].sync);
        assert!(!cfg.raw.rules[3].sync);
        // Passthrough rules are passthrough; nvim-value-flag eats its next argv.
        assert!(cfg.raw.rules[1].passthrough);
        assert_eq!(cfg.raw.rules[1].consumes, 1);
        assert!(cfg.raw.rules[2].passthrough);
    }

    #[test]
    fn rejects_unknown_to_reference() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "does-not-exist"
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(
            err.to_string().contains("unknown todoke target"),
            "got: {err}"
        );
    }

    #[test]
    fn rejects_invalid_regex() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = "[unterminated"
            to = "a"
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(
            err.to_string().contains("failed to compile match pattern"),
            "got: {err}"
        );
    }

    #[test]
    fn rejects_multiple_consume_forms() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = '.*'
            to = "a"
            passthrough = true
            consumes = 1
            consumes_rest = true
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(err.to_string().contains("pick exactly one"), "got: {err}");
    }

    #[test]
    fn rejects_consumes_until_without_passthrough() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = '.*'
            to = "a"
            consumes_until = '^[-+]'
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(
            err.to_string().contains("consume options only apply"),
            "got: {err}"
        );
    }

    #[test]
    fn rejects_invalid_consumes_until_regex() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = '.*'
            to = "a"
            passthrough = true
            consumes_until = '[unterminated'
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(err.to_string().contains("consumes_until"), "got: {err}");
    }

    #[test]
    fn passthrough_rule_can_omit_to() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            name = "any-flag"
            match = '^-'
            passthrough = true
        "#;
        let cfg = load_from_str(text).expect("passthrough rule should allow omitted `to`");
        assert!(cfg.raw.rules[0].to.is_none());
    }

    #[test]
    fn non_passthrough_rule_requires_to() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            name = "orphan"
            match = '.*'
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(err.to_string().contains("has no `to`"), "got: {err}");
    }

    #[test]
    fn rejects_consumes_without_passthrough() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = '.*'
            to = "a"
            consumes = 1
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(
            err.to_string().contains("consume options only apply"),
            "got: {err}"
        );
    }

    #[test]
    fn rejects_joined_and_passthrough_both_true() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = '.*'
            to = "a"
            joined = true
            passthrough = true
        "#;
        let err = load_from_str(text).unwrap_err();
        assert!(err.to_string().contains("mutually exclusive"), "got: {err}");
    }

    #[test]
    fn mode_defaults_to_remote_kind_defaults_to_exec() {
        let text = r#"
            [todoke.a]
            command = "echo"

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert_eq!(cfg.raw.rules[0].mode, "remote");
        assert!(!cfg.raw.rules[0].sync);
        assert!(cfg.raw.rules[0].group.is_none());
        assert_eq!(cfg.raw.todoke["a"].kind, TargetKind::Exec);
        // gui is a new public field; lock in the backward-compatible default.
        assert!(!cfg.raw.todoke["a"].gui);
    }

    #[test]
    fn target_gui_parses_true() {
        let text = r#"
            [todoke.a]
            command = "neovide"
            gui = true

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        assert!(cfg.raw.todoke["a"].gui);
    }

    #[test]
    fn args_per_mode_with_default_fallback() {
        let text = r#"
            [todoke.a]
            command = "echo"
            [todoke.a.args]
            remote = ["--reuse"]
            default = ["--fallback"]

            [[rules]]
            match = ".*"
            to = "a"
        "#;
        let cfg = load_from_str(text).unwrap();
        let t = &cfg.raw.todoke["a"];
        assert_eq!(t.args_for("remote"), &["--reuse".to_string()]);
        assert_eq!(t.args_for("new"), &["--fallback".to_string()]);
        assert_eq!(t.args_for("anything-else"), &["--fallback".to_string()]);
    }

    #[test]
    fn tera_conditional_blocks_are_applied_at_load_time() {
        let src = r#"
            [vars]
            use_neovide = true

            [todoke.nvim]
            kind = "neovim"
            command = "nvim"
            listen = "/tmp/sock"

            {% if vars.use_neovide %}
            [todoke.nvim-gui]
            kind = "neovim"
            command = "neovide"
            listen = "/tmp/sock-gui"
            [todoke.nvim-gui.args]
            remote = ["--"]
            {% endif %}

            [[rules]]
            match = ".*"
            to = "nvim"
        "#;
        let cfg = load_from_str(src).unwrap();
        assert!(cfg.raw.todoke.contains_key("nvim-gui"));

        let src_off = src.replace("use_neovide = true", "use_neovide = false");
        let cfg2 = load_from_str(&src_off).unwrap();
        assert!(!cfg2.raw.todoke.contains_key("nvim-gui"));
        assert!(cfg2.raw.todoke.contains_key("nvim"));
    }

    #[test]
    fn dispatch_time_placeholders_survive_prerender() {
        let src = r#"
            [todoke.nvim]
            kind = "neovim"
            command = "nvim"
            listen = '/tmp/nvim-todoke-{{ group }}.sock'

            [[rules]]
            match = ".*"
            to = "nvim"
            group = "{{ file_stem }}"
        "#;
        let cfg = load_from_str(src).unwrap();
        assert_eq!(
            cfg.raw.todoke["nvim"].listen.as_deref(),
            Some("/tmp/nvim-todoke-{{ group }}.sock"),
        );
        assert_eq!(cfg.raw.rules[0].group.as_deref(), Some("{{ file_stem }}"));
    }

    #[test]
    fn vars_value_substitutes_top_level() {
        let src = r#"
            [vars]
            gui = "neovide"

            [todoke.nvim]
            kind = "neovim"
            command = "{{ vars.gui }}"
            listen = "/tmp/sock"

            [[rules]]
            match = ".*"
            to = "nvim"
        "#;
        let cfg = load_from_str(src).unwrap();
        assert_eq!(cfg.raw.todoke["nvim"].command, "neovide");
    }

    #[test]
    fn vars_subtables_are_picked_up() {
        let src = r#"
            [vars]
            gui = "neovide"

            [vars.colors]
            primary = "blue"

            [todoke.nvim]
            kind = "neovim"
            command = "{{ vars.gui }}"
            listen = "/tmp/{{ vars.colors.primary }}"

            [[rules]]
            match = ".*"
            to = "nvim"
        "#;
        let cfg = load_from_str(src).unwrap();
        assert_eq!(cfg.raw.todoke["nvim"].command, "neovide");
        assert_eq!(cfg.raw.todoke["nvim"].listen.as_deref(), Some("/tmp/blue"));
    }
}