alphai-tui 0.23.2

Terminal stock dashboard: live quotes and charts plus AI-scored financial news and SEC Form 4 insider activity from AlphAI
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
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use clap::ValueEnum;
use ratatui::widgets::BorderType;
use serde::{Deserialize, Serialize};

use crate::alphai;
use crate::app::{ChartStyle, InsiderChartWindow, NewsLayout, NewsScope, RANGE_PRESETS};
use crate::domain::{Interval, Range};
use crate::indicators::{self, MaType};
use crate::keymap::Keymap;
use crate::portfolio::Position;
use crate::theme::Theme;
use crate::ui;

/// Used when neither the CLI nor the config file provides symbols.
pub const DEFAULT_WATCHLIST: [&str; 4] = ["AAPL", "MSFT", "NVDA", "BTC-USD"];

/// One credential a price source (or the app itself) needs. `config_name`
/// is the field name inside `[keys]` in config.toml; existing names are
/// frozen, renaming one would orphan the key in users' files. The env var
/// wins over the file at resolution time.
pub struct KeyField {
    pub config_name: &'static str,
    pub env_var: &'static str,
    /// Row label in the settings screen.
    pub label: &'static str,
}

/// The AlphAI news key: app-level rather than a price source, but it lives
/// in the same `[keys]` table and the same settings list.
pub const ALPHAI_KEY_FIELD: KeyField = KeyField {
    config_name: "alphai",
    env_var: "ALPHAI_API_KEY",
    label: "AlphAI key",
};

/// Persisted app settings. Precedence at use time: CLI args > env vars
/// (for API keys) > this file > built-in defaults.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    pub source: Option<String>,
    pub watchlist: Vec<String>,
    pub every: Option<u64>,
    pub range: Option<String>,
    pub interval: Option<String>,
    /// Whether a source that stops answering is swapped for one that still
    /// does (default true). Yahoo blocks by IP for tens of minutes and no
    /// retry can shorten that, so the only repair is another provider; set
    /// it false to keep the errors and choose by hand.
    pub source_fallback: Option<bool>,
    /// Where Enter opens a news article: "alphai" (article page on
    /// alphai.io, the default) or "original" (the source site).
    pub news_open: Option<String>,
    /// API keys by `KeyField::config_name`. A map rather than a struct so a
    /// key this binary does not know (say, a config written by a newer
    /// version) survives a load -> save round trip instead of being dropped.
    pub keys: BTreeMap<String, String>,
    /// `[ui]` startup defaults (view, news layout and scope).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ui: Option<UiConfig>,
    /// `[chart]` startup defaults and indicator parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chart: Option<ChartConfig>,
    /// `[theme]` color overrides by slot name (see `theme::Theme`). Kept as
    /// raw strings: validation happens in `resolve`, per slot, so one typo
    /// never degrades the whole file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub theme: Option<BTreeMap<String, String>>,
    /// `[keybindings]` overrides by action name (see `keymap::ACTIONS`).
    /// Raw specs; `resolve` validates per entry, so one bad key never
    /// degrades the whole file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub keybindings: Option<BTreeMap<String, KeysSpec>>,
    /// `[[positions]]`: what the user holds, one entry per ticker, with
    /// the quantity and the average price paid. Validated in `resolve`,
    /// per entry like every other section. Declared last on purpose:
    /// `toml` serializes in field order, and a scalar written after an
    /// array of tables would be parsed back as part of it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub positions: Vec<Position>,
}

/// Keys of one `[keybindings]` action: a bare string or a list of them.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum KeysSpec {
    One(String),
    Many(Vec<String>),
}

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

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct UiConfig {
    pub default_view: Option<String>,
    pub news_layout: Option<String>,
    pub news_scope: Option<String>,
    /// Line set of the panel frames: "rounded" (default) or "plain".
    pub borders: Option<String>,
    /// Raw i64 rather than u8: an out-of-range number must degrade to a
    /// warning in `resolve`, not fail deserializing the whole file.
    pub news_min_score: Option<i64>,
    pub insider_min_score: Option<i64>,
    /// Whether the quote rail under the header is drawn (default true).
    pub quote_rail: Option<bool>,
    /// Start in bare mode: no header, no footer (default false).
    pub bare: Option<bool>,
    /// Startup window of the Insider view's chart panel: "3m" (default),
    /// "12m" or "off"; the g key cycles it live.
    pub insider_chart: Option<String>,
    /// How long fetched AlphAI data (news, sentiment, insider) stays fresh
    /// before the visible view re-fetches it. Seconds; raw i64 for the same
    /// warning-not-error reason as the scores.
    pub alphai_ttl_secs: Option<i64>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ChartConfig {
    pub timezone: Option<String>,
    pub session_shading: Option<bool>,
    pub time_grid: Option<bool>,
    pub style: Option<String>,
    pub sma: Option<bool>,
    pub ma_type: Option<String>,
    pub rsi: Option<bool>,
    pub volume: Option<bool>,
    /// Draw pre and post market candles too (Yahoo and Alpaca).
    pub extended_hours: Option<bool>,
    /// Mark the ticker's news on the price chart.
    pub news_markers: Option<bool>,
    pub sma_fast: Option<usize>,
    pub sma_slow: Option<usize>,
    pub rsi_period: Option<usize>,
    /// Percent of the plot width kept free right of the newest candle (the
    /// last-price marker lives there). Raw i64 so an out-of-range number
    /// degrades to a warning in `resolve`, not a whole-file parse error.
    pub right_margin_pct: Option<i64>,
    /// The t/T cycle, as pairs like `["1d", "5m"]`.
    pub presets: Option<Vec<Vec<String>>>,
}

/// Everything derived and validated from the raw config. Semantic problems
/// in these sections warn and fall back per entry; only a TOML syntax error
/// degrades the whole file (in `load_at`).
pub struct Resolved {
    pub theme: Theme,
    /// Which preset `theme` was built from, for the settings row and the
    /// live cycle key.
    pub theme_name: &'static str,
    pub chart: ChartDefaults,
    pub ui: UiDefaults,
    pub keymap: Keymap,
    /// `[[positions]]`, validated; empty when the section is absent.
    pub positions: Vec<Position>,
}

/// Validated `[chart]` values; `Default` is the traditional look. The
/// session keys (c, m, i, t) still toggle everything live, these only seed
/// the startup state and the indicator math.
#[derive(Clone, Debug, PartialEq)]
pub struct ChartDefaults {
    pub timezone: ChartTimezone,
    pub session_shading: bool,
    pub time_grid: bool,
    pub style: ChartStyle,
    pub sma: bool,
    /// Simple or exponential; the periods below serve whichever is picked.
    pub ma_type: MaType,
    pub rsi: bool,
    pub volume: bool,
    /// Start with premarket and after-hours candles drawn.
    pub extended_hours: bool,
    /// Start with the news marks on the price chart. They are drawn from
    /// the news the app already holds for the ticker, so this costs no
    /// request either way.
    pub news_markers: bool,
    pub sma_fast: usize,
    pub sma_slow: usize,
    pub rsi_period: usize,
    /// 0 disables the margin (and the last-price marker drawn in it).
    pub right_margin_pct: u16,
    pub presets: Vec<(Range, Interval)>,
}

impl Default for ChartDefaults {
    fn default() -> Self {
        Self {
            timezone: ChartTimezone::Exchange,
            session_shading: true,
            time_grid: true,
            style: ChartStyle::Candles,
            sma: true,
            ma_type: MaType::Sma,
            rsi: true,
            volume: true,
            extended_hours: true,
            news_markers: true,
            sma_fast: indicators::SMA_FAST,
            sma_slow: indicators::SMA_SLOW,
            rsi_period: indicators::RSI_PERIOD,
            right_margin_pct: DEFAULT_RIGHT_MARGIN_PCT,
            presets: RANGE_PRESETS.to_vec(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChartTimezone {
    Exchange,
    Local,
    Utc,
}

/// Startup default of `[chart] right_margin_pct`: a fifth of the plot stays
/// free right of the newest candle, so it never sits glued to the border and
/// the last-price marker has room to live.
pub const DEFAULT_RIGHT_MARGIN_PCT: u16 = 20;

/// Accepted `[chart] right_margin_pct` values; anything past half the plot
/// would squeeze the candles more than it helps.
pub const RIGHT_MARGIN_RANGE: RangeInclusive<i64> = 0..=50;

/// Startup default of the news score filter: relevance 7 and up (the API
/// itself defaults to 4; +/- adjust it live, `[ui] news_min_score` seeds it).
pub const DEFAULT_NEWS_MIN_SCORE: u8 = 7;

/// Startup default of the insider score filter. Insider rows are scored from
/// the event's dollar value, so this is a trade-size filter; 4 matches the
/// server default and keeps every filing the feed used to show.
pub const DEFAULT_INSIDER_MIN_SCORE: u8 = 4;

/// Accepted `[ui] alphai_ttl_secs` values. The floor keeps a typo (or "5"
/// meant as minutes) from burning the free request budget; the ceiling is
/// one day, past which the value is surely a mistake.
pub const ALPHAI_TTL_RANGE: RangeInclusive<i64> = 30..=86_400;

/// Validated `[ui]` startup values.
#[derive(Clone, Debug, PartialEq)]
pub struct UiDefaults {
    pub view_idx: usize,
    /// The quote rail under the header; file-only, like the border style.
    pub quote_rail: bool,
    /// Start without the header and footer; `--bare` also turns it on.
    pub bare: bool,
    pub news_layout: NewsLayout,
    pub news_scope: NewsScope,
    pub news_min_score: u8,
    pub insider_min_score: u8,
    pub insider_chart: InsiderChartWindow,
    pub alphai_ttl: Duration,
}

impl Default for UiDefaults {
    fn default() -> Self {
        Self {
            view_idx: ui::view_index(ui::ViewId::Split),
            quote_rail: true,
            bare: false,
            news_layout: NewsLayout::default(),
            news_scope: NewsScope::default(),
            news_min_score: DEFAULT_NEWS_MIN_SCORE,
            insider_min_score: DEFAULT_INSIDER_MIN_SCORE,
            insider_chart: InsiderChartWindow::default(),
            alphai_ttl: alphai::CACHE_TTL,
        }
    }
}

/// Validate the raw config into ready-to-use values plus human-readable
/// warnings (printed to stderr before the TUI starts).
/// `cli_theme` is `--theme`; it wins over `[theme] preset`, like every
/// other CLI value.
pub fn resolve(cfg: &Config, cli_theme: Option<&str>) -> (Resolved, Vec<String>) {
    let mut warnings = Vec::new();
    let (mut theme, theme_name) = Theme::resolve(cfg.theme.as_ref(), cli_theme, &mut warnings);
    theme.border_type = resolve_borders(
        cfg.ui.as_ref().and_then(|u| u.borders.as_deref()),
        &mut warnings,
    );
    let chart = resolve_chart(cfg.chart.as_ref(), &mut warnings);
    let ui = resolve_ui(cfg.ui.as_ref(), &mut warnings);
    let keymap = Keymap::from_config(
        cfg.keybindings
            .iter()
            .flatten()
            .map(|(name, spec)| (name.as_str(), spec.as_list())),
        &mut warnings,
    );
    let positions = resolve_positions(&cfg.positions, &mut warnings);
    (
        Resolved {
            theme,
            theme_name,
            chart,
            ui,
            keymap,
            positions,
        },
        warnings,
    )
}

/// `[[positions]]`: a broken entry warns and is dropped, the rest stand.
/// Symbols are upper-cased the way the watchlist is, so a holding written
/// in lower case still meets its quote.
fn resolve_positions(raw: &[Position], warnings: &mut Vec<String>) -> Vec<Position> {
    let mut out: Vec<Position> = Vec::new();
    for entry in raw {
        let symbol = entry.symbol.trim().to_uppercase();
        if symbol.is_empty() {
            warnings.push("[[positions]]: an entry has no symbol, skipping it".to_string());
            continue;
        }
        if !entry.qty.is_finite() || entry.qty == 0.0 {
            warnings.push(format!(
                "[[positions]] {symbol}: qty must be a non-zero number, skipping it"
            ));
            continue;
        }
        if !entry.avg_price.is_finite() || entry.avg_price < 0.0 {
            warnings.push(format!(
                "[[positions]] {symbol}: avg_price must be zero or more, skipping it"
            ));
            continue;
        }
        if out.iter().any(|kept| kept.symbol == symbol) {
            warnings.push(format!(
                "[[positions]] {symbol}: listed twice, keeping the first entry"
            ));
            continue;
        }
        out.push(Position {
            symbol,
            qty: entry.qty,
            avg_price: entry.avg_price,
        });
    }
    out
}

/// `[ui] borders`: the line set panel frames draw with. Lives in `[ui]`
/// rather than `[theme]` because it is not a color, but it resolves onto
/// the theme, which every renderer already has at hand.
fn resolve_borders(raw: Option<&str>, warnings: &mut Vec<String>) -> BorderType {
    match raw.map(str::to_lowercase).as_deref() {
        None | Some("rounded") => BorderType::Rounded,
        Some("plain") => BorderType::Plain,
        Some(other) => {
            warnings.push(format!(
                "[ui] borders: unknown \"{other}\" (rounded or plain), keeping rounded"
            ));
            BorderType::Rounded
        }
    }
}

fn resolve_chart(raw: Option<&ChartConfig>, warnings: &mut Vec<String>) -> ChartDefaults {
    let mut out = ChartDefaults::default();
    let Some(raw) = raw else { return out };
    if let Some(zone) = &raw.timezone {
        match zone.to_lowercase().as_str() {
            "exchange" | "et" => out.timezone = ChartTimezone::Exchange,
            "local" => out.timezone = ChartTimezone::Local,
            "utc" => out.timezone = ChartTimezone::Utc,
            _ => warnings.push(format!(
                "[chart] timezone: unknown \"{zone}\" (exchange, local or utc), keeping exchange"
            )),
        }
    }
    if let Some(v) = raw.session_shading {
        out.session_shading = v;
    }
    if let Some(v) = raw.time_grid {
        out.time_grid = v;
    }
    if let Some(style) = &raw.style {
        match style.to_lowercase().as_str() {
            "candles" => out.style = ChartStyle::Candles,
            "line" => out.style = ChartStyle::Line,
            other => warnings.push(format!(
                "[chart] style: unknown \"{other}\" (candles or line), keeping candles"
            )),
        }
    }
    if let Some(v) = raw.sma {
        out.sma = v;
    }
    if let Some(kind) = &raw.ma_type {
        match kind.to_lowercase().as_str() {
            "sma" => out.ma_type = MaType::Sma,
            "ema" => out.ma_type = MaType::Ema,
            other => warnings.push(format!(
                "[chart] ma_type: unknown \"{other}\" (sma or ema), keeping sma"
            )),
        }
    }
    if let Some(v) = raw.rsi {
        out.rsi = v;
    }
    if let Some(v) = raw.volume {
        out.volume = v;
    }
    if let Some(v) = raw.extended_hours {
        out.extended_hours = v;
    }
    if let Some(v) = raw.news_markers {
        out.news_markers = v;
    }
    out.sma_fast = period(raw.sma_fast, out.sma_fast, "sma_fast", 2..=250, warnings);
    out.sma_slow = period(raw.sma_slow, out.sma_slow, "sma_slow", 2..=250, warnings);
    out.rsi_period = period(
        raw.rsi_period,
        out.rsi_period,
        "rsi_period",
        2..=100,
        warnings,
    );
    if let Some(pct) = raw.right_margin_pct {
        if RIGHT_MARGIN_RANGE.contains(&pct) {
            out.right_margin_pct = pct as u16;
        } else {
            warnings.push(format!(
                "[chart] right_margin_pct: {pct} is outside {}..={}, keeping {}",
                RIGHT_MARGIN_RANGE.start(),
                RIGHT_MARGIN_RANGE.end(),
                DEFAULT_RIGHT_MARGIN_PCT
            ));
        }
    }
    if let Some(rows) = &raw.presets {
        let mut presets = Vec::new();
        for row in rows {
            match parse_preset(row) {
                Some(p) => presets.push(p),
                None => warnings.push(format!(
                    "[chart] presets: bad pair {row:?}, expected like [\"1d\", \"5m\"]"
                )),
            }
        }
        if presets.is_empty() {
            warnings.push("[chart] presets: no valid pairs, keeping the built-in cycle".into());
        } else {
            out.presets = presets;
        }
    }
    out
}

fn period(
    raw: Option<usize>,
    default: usize,
    name: &str,
    valid: RangeInclusive<usize>,
    warnings: &mut Vec<String>,
) -> usize {
    match raw {
        Some(v) if valid.contains(&v) => v,
        Some(v) => {
            warnings.push(format!(
                "[chart] {name}: {v} is outside {}..={}, keeping {default}",
                valid.start(),
                valid.end()
            ));
            default
        }
        None => default,
    }
}

fn parse_preset(row: &[String]) -> Option<(Range, Interval)> {
    let [range, interval] = row else { return None };
    Some((
        Range::from_str(range, true).ok()?,
        Interval::from_str(interval, true).ok()?,
    ))
}

fn resolve_ui(raw: Option<&UiConfig>, warnings: &mut Vec<String>) -> UiDefaults {
    let mut out = UiDefaults::default();
    let Some(raw) = raw else { return out };
    if let Some(name) = &raw.default_view {
        // Matched by title, so the list stays correct as views register.
        match ui::VIEWS
            .iter()
            .position(|v| v.title().eq_ignore_ascii_case(name))
        {
            Some(idx) => out.view_idx = idx,
            None => {
                let names: Vec<String> =
                    ui::VIEWS.iter().map(|v| v.title().to_lowercase()).collect();
                warnings.push(format!(
                    "[ui] default_view: unknown \"{name}\" (one of {}), keeping split",
                    names.join(", ")
                ));
            }
        }
    }
    if let Some(on) = raw.quote_rail {
        out.quote_rail = on;
    }
    if let Some(on) = raw.bare {
        out.bare = on;
    }
    if let Some(layout) = &raw.news_layout {
        match layout.to_lowercase().as_str() {
            "side" => out.news_layout = NewsLayout::Side,
            "stacked" => out.news_layout = NewsLayout::Stacked,
            other => warnings.push(format!(
                "[ui] news_layout: unknown \"{other}\" (side or stacked), keeping side"
            )),
        }
    }
    if let Some(scope) = &raw.news_scope {
        match scope.to_lowercase().as_str() {
            "ticker" => out.news_scope = NewsScope::Ticker,
            "market" => out.news_scope = NewsScope::Market,
            "trending" => out.news_scope = NewsScope::Trending,
            other => warnings.push(format!(
                "[ui] news_scope: unknown \"{other}\" (ticker, market or trending), keeping ticker"
            )),
        }
    }
    if let Some(window) = &raw.insider_chart {
        match window.to_lowercase().as_str() {
            "off" => out.insider_chart = InsiderChartWindow::Off,
            "3m" => out.insider_chart = InsiderChartWindow::M3,
            "12m" => out.insider_chart = InsiderChartWindow::M12,
            other => warnings.push(format!(
                "[ui] insider_chart: unknown \"{other}\" (3m, 12m or off), keeping 3m"
            )),
        }
    }
    out.news_min_score = min_score(
        raw.news_min_score,
        out.news_min_score,
        "news_min_score",
        warnings,
    );
    out.insider_min_score = min_score(
        raw.insider_min_score,
        out.insider_min_score,
        "insider_min_score",
        warnings,
    );
    if let Some(secs) = raw.alphai_ttl_secs {
        if ALPHAI_TTL_RANGE.contains(&secs) {
            out.alphai_ttl = Duration::from_secs(secs as u64);
        } else {
            warnings.push(format!(
                "[ui] alphai_ttl_secs: {secs} is outside {}..={}, keeping {}",
                ALPHAI_TTL_RANGE.start(),
                ALPHAI_TTL_RANGE.end(),
                alphai::CACHE_TTL.as_secs()
            ));
        }
    }
    out
}

/// One `[ui] *_min_score` entry: 1..=10 or a warning plus the default.
fn min_score(raw: Option<i64>, default: u8, name: &str, warnings: &mut Vec<String>) -> u8 {
    match raw {
        Some(n) if (1..=10).contains(&n) => n as u8,
        Some(n) => {
            warnings.push(format!(
                "[ui] {name}: {n} is outside 1..=10, keeping {default}"
            ));
            default
        }
        None => default,
    }
}

impl Config {
    /// Resolved credential for one key field: the env var wins so a
    /// shell-exported key keeps working after a config file appears; blank
    /// values count as unset.
    pub fn key_value(&self, field: &KeyField) -> Option<String> {
        env_key(field.env_var).or_else(|| {
            self.keys
                .get(field.config_name)
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
        })
    }

    pub fn alphai_key(&self) -> Option<String> {
        self.key_value(&ALPHAI_KEY_FIELD)
    }

    /// True when Enter on a news article should open the original source
    /// instead of the alphai.io article page.
    pub fn news_open_original(&self) -> bool {
        self.news_open.as_deref() == Some("original")
    }
}

fn env_key(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|v| !v.trim().is_empty())
}

/// Unix (including macOS) follows the terminal-tool convention:
/// `$XDG_CONFIG_HOME` or `~/.config`. Windows uses the platform config dir.
pub fn path() -> Option<PathBuf> {
    let base = if cfg!(windows) {
        dirs::config_dir()?
    } else {
        std::env::var_os("XDG_CONFIG_HOME")
            .map(PathBuf::from)
            .filter(|p| p.is_absolute())
            .unwrap_or(dirs::home_dir()?.join(".config"))
    };
    Some(base.join("alphai-tui").join("config.toml"))
}

/// Load from an explicit path (the `--config` flag) or the default
/// location. Returns the config, whether a file existed, and the path Save
/// must write back to (None when the platform has no config dir). A missing
/// file is a normal first run; an unreadable one degrades to defaults with
/// a stderr warning rather than blocking startup.
pub fn load_at(override_path: Option<&Path>) -> (Config, bool, Option<PathBuf>) {
    let Some(p) = override_path.map(Path::to_path_buf).or_else(path) else {
        return (Config::default(), false, None);
    };
    match load_from(&p) {
        Ok(Some(cfg)) => (cfg, true, Some(p)),
        Ok(None) => (Config::default(), false, Some(p)),
        Err(e) => {
            eprintln!("warning: ignoring bad config at {}: {e:#}", p.display());
            (Config::default(), false, Some(p))
        }
    }
}

pub fn load_from(p: &Path) -> Result<Option<Config>> {
    if !p.exists() {
        return Ok(None);
    }
    let raw = std::fs::read_to_string(p).context("read failed")?;
    Ok(Some(toml::from_str(&raw).context("parse failed")?))
}

/// Save to the path `load_at` resolved (the settings screen passes it back).
pub fn save_at(path: Option<&Path>, cfg: &Config) -> Result<()> {
    let p = path.context("no config directory on this platform")?;
    save_to(p, cfg)
}

/// The file may hold API keys, so it is created user-only (0600) on unix.
pub fn save_to(p: &Path, cfg: &Config) -> Result<()> {
    if let Some(dir) = p.parent() {
        std::fs::create_dir_all(dir).context("create config dir failed")?;
    }
    let raw = toml::to_string_pretty(cfg).context("serialize failed")?;
    // Written beside the target and renamed over it. The position prompt
    // saves on every edit, so a torn write is no longer a once-a-session
    // risk, and this file also holds the API keys. The mode is set on the
    // temporary file, before it takes the real name.
    let tmp = p.with_extension(format!("toml.tmp{}", std::process::id()));
    std::fs::write(&tmp, raw).context("write failed")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600));
    }
    if let Err(e) = std::fs::rename(&tmp, p) {
        let _ = std::fs::remove_file(&tmp);
        return Err(e).context("replace failed");
    }
    Ok(())
}

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

    /// A key field whose env var can never be set, so tests exercise the
    /// file side of the resolution deterministically.
    const TEST_FIELD: KeyField = KeyField {
        config_name: "finnhub",
        env_var: "ALPHAI_TUI_TEST_NEVER_SET",
        label: "test",
    };

    /// Every section validates per entry: a broken holding warns and is
    /// dropped, the rest of the list still loads.
    #[test]
    fn bad_positions_warn_and_are_dropped() {
        let cfg: Config = toml::from_str(
            r#"
[[positions]]
symbol = "aapl"
qty = 12
avg_price = 182.31

[[positions]]
symbol = "MSFT"
qty = 0
avg_price = 400

[[positions]]
symbol = "NVDA"
qty = 3
avg_price = -1

[[positions]]
symbol = "AAPL"
qty = 5
avg_price = 100
"#,
        )
        .unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(resolved.positions.len(), 1);
        // Upper-cased like the watchlist, or the holding would never meet
        // its quote.
        assert_eq!(resolved.positions[0].symbol, "AAPL");
        assert_eq!(resolved.positions[0].qty, 12.0);
        assert_eq!(warnings.len(), 3, "{warnings:?}");
        assert!(warnings.iter().any(|w| w.contains("MSFT")), "{warnings:?}");
        assert!(warnings.iter().any(|w| w.contains("NVDA")), "{warnings:?}");
        assert!(warnings.iter().any(|w| w.contains("twice")), "{warnings:?}");
    }

    #[test]
    fn round_trip() {
        let dir = std::env::temp_dir().join(format!("alphai-tui-test-{}", std::process::id()));
        let p = dir.join("config.toml");
        let cfg = Config {
            source: Some("finnhub".into()),
            watchlist: vec!["AAPL".into(), "BTC-USD".into()],
            every: Some(30),
            range: Some("5d".into()),
            interval: Some("15m".into()),
            source_fallback: Some(false),
            news_open: Some("original".into()),
            positions: vec![Position {
                symbol: "AAPL".into(),
                qty: 12.0,
                avg_price: 182.31,
            }],
            keys: BTreeMap::from([
                ("finnhub".to_string(), "fh-key".to_string()),
                ("alphai".to_string(), "ak_live_x".to_string()),
                ("alpaca_key_id".to_string(), "PKTEST123".to_string()),
                ("alpaca_secret".to_string(), "alpaca-secret-x".to_string()),
            ]),
            ui: Some(UiConfig {
                default_view: Some("news".into()),
                news_layout: Some("stacked".into()),
                news_scope: None,
                borders: Some("plain".into()),
                news_min_score: Some(6),
                insider_min_score: Some(5),
                insider_chart: Some("12m".into()),
                alphai_ttl_secs: Some(120),
                quote_rail: Some(false),
                bare: Some(true),
            }),
            chart: Some(ChartConfig {
                style: Some("line".into()),
                sma_slow: Some(200),
                right_margin_pct: Some(25),
                presets: Some(vec![vec!["1d".into(), "5m".into()]]),
                ..Default::default()
            }),
            theme: Some(BTreeMap::from([(
                "accent".to_string(),
                "magenta".to_string(),
            )])),
            keybindings: Some(BTreeMap::from([
                ("quit".to_string(), KeysSpec::One("ctrl-q".into())),
                (
                    "open".to_string(),
                    KeysSpec::Many(vec!["enter".into(), "w".into()]),
                ),
            ])),
        };
        save_to(&p, &cfg).unwrap();
        let loaded = load_from(&p).unwrap().unwrap();
        assert_eq!(loaded, cfg);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn missing_file_is_none() {
        let p = Path::new("/nonexistent/alphai-tui/config.toml");
        assert!(load_from(p).unwrap().is_none());
    }

    #[test]
    fn partial_file_fills_defaults() {
        let cfg: Config = toml::from_str("source = \"yahoo\"").unwrap();
        assert_eq!(cfg.source.as_deref(), Some("yahoo"));
        assert!(cfg.watchlist.is_empty());
        assert!(cfg.keys.is_empty());
    }

    /// The exact `[keys]` shape written by pre-registry versions (and shown
    /// in the README) keeps parsing; those field names are frozen.
    #[test]
    fn old_keys_table_parses_verbatim() {
        let cfg: Config = toml::from_str(
            r#"
            source = "yahoo"
            [keys]
            alphai = "ak_live_x"
            finnhub = ""
            alpaca_key_id = "PK123"
            alpaca_secret = "sec"
            "#,
        )
        .unwrap();
        assert_eq!(
            cfg.keys.get("alphai").map(String::as_str),
            Some("ak_live_x")
        );
        assert_eq!(
            cfg.keys.get("alpaca_secret").map(String::as_str),
            Some("sec")
        );
        // A blank file value counts as unset at resolution time.
        assert_eq!(cfg.key_value(&TEST_FIELD), None);
    }

    #[test]
    fn key_value_reads_and_trims_file_values() {
        let cfg: Config = toml::from_str("[keys]\nfinnhub = \" fh-key \"").unwrap();
        assert_eq!(cfg.key_value(&TEST_FIELD).as_deref(), Some("fh-key"));
        assert_eq!(Config::default().key_value(&TEST_FIELD), None);
    }

    /// A `[keys]` entry this binary does not know must survive load -> save
    /// (a struct with named fields would silently drop it).
    #[test]
    fn unknown_key_survives_round_trip() {
        let cfg: Config = toml::from_str("[keys]\nnewsource = \"k\"").unwrap();
        let raw = toml::to_string_pretty(&cfg).unwrap();
        let again: Config = toml::from_str(&raw).unwrap();
        assert_eq!(again.keys.get("newsource").map(String::as_str), Some("k"));
    }

    /// Unknown sections and keys are tolerated on load: a typo never takes
    /// the whole file (and its API keys) down.
    #[test]
    fn unknown_sections_and_fields_are_tolerated() {
        let cfg: Config =
            toml::from_str("nonsense = 1\n[thme]\naccent = \"red\"").expect("must parse");
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn theme_section_resolves_and_stays_absent_by_default() {
        let cfg: Config = toml::from_str("[theme]\naccent = \"magenta\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.theme.accent, ratatui::style::Color::Magenta);

        let (_, warnings) = resolve(
            &toml::from_str::<Config>("[theme]\nup = \"banana\"").unwrap(),
            None,
        );
        assert_eq!(warnings.len(), 1, "{warnings:?}");

        // Absent sections must not serialize: Save would spray empty tables
        // into every config otherwise.
        let bare = toml::to_string_pretty(&Config::default()).unwrap();
        for section in ["[theme]", "[ui]", "[chart]", "[keybindings]"] {
            assert!(!bare.contains(section), "{bare}");
        }
    }

    /// --theme beats the file, like every other CLI value, and an unknown
    /// name warns instead of failing.
    #[test]
    fn cli_theme_overrides_the_config_preset() {
        let cfg: Config = toml::from_str("[theme]\npreset = \"nord\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.theme_name, "nord");

        let (resolved, warnings) = resolve(&cfg, Some("Dracula"));
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.theme_name, "dracula");

        let (resolved, warnings) = resolve(&cfg, Some("nosuchtheme"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("--theme"), "{warnings:?}");
        assert_eq!(resolved.theme_name, crate::theme::DEFAULT_PRESET);
    }

    #[test]
    fn borders_setting_resolves_onto_the_theme() {
        let cfg: Config = toml::from_str("[ui]\nborders = \"plain\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.theme.border_type, BorderType::Plain);

        // Unknown value warns and keeps the rounded default; so does no
        // section at all (silently).
        let cfg: Config = toml::from_str("[ui]\nborders = \"fancy\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert_eq!(resolved.theme.border_type, BorderType::Rounded);
        let (resolved, warnings) = resolve(&Config::default(), None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.theme.border_type, BorderType::Rounded);
    }

    #[test]
    fn keybindings_section_resolves_per_entry() {
        use crate::keymap::Action;
        use crossterm::event::{KeyCode, KeyEvent};

        // A bare string and a list both parse; the keymap follows.
        let cfg: Config =
            toml::from_str("[keybindings]\nrefresh = \"f5\"\nopen = [\"enter\", \"w\"]").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(
            resolved.keymap.resolve(&KeyEvent::from(KeyCode::F(5))),
            Some(Action::Refresh)
        );
        assert_eq!(
            resolved.keymap.resolve(&KeyEvent::from(KeyCode::Char('w'))),
            Some(Action::Open)
        );
        assert_eq!(
            resolved.keymap.resolve(&KeyEvent::from(KeyCode::Char('r'))),
            None
        );

        // A bad entry warns and keeps the default; the good one still lands.
        let cfg: Config = toml::from_str("[keybindings]\nquit = \"supr\"\ncard = \"u\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(warnings.len(), 2, "{warnings:?}");
        assert_eq!(
            resolved.keymap.resolve(&KeyEvent::from(KeyCode::Char('q'))),
            Some(Action::Quit)
        );
        assert_eq!(
            resolved.keymap.resolve(&KeyEvent::from(KeyCode::Char('u'))),
            Some(Action::Card)
        );

        // No section at all: the untouched defaults.
        let (resolved, warnings) = resolve(&Config::default(), None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(
            resolved.keymap.resolve(&KeyEvent::from(KeyCode::Char('q'))),
            Some(Action::Quit)
        );
    }

    #[test]
    fn chart_section_validates_per_entry() {
        let cfg: Config = toml::from_str(
            r#"
            [chart]
            style = "line"
            sma_fast = 50
            sma_slow = 9000
            rsi_period = 21
            presets = [["1d", "5m"], ["nope", "5m"], ["1y"]]
            "#,
        )
        .unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(resolved.chart.style, ChartStyle::Line);
        assert_eq!(resolved.chart.sma_fast, 50);
        // Out of range: warned, default kept.
        assert_eq!(resolved.chart.sma_slow, indicators::SMA_SLOW);
        assert_eq!(resolved.chart.rsi_period, 21);
        // One valid pair survives; the two bad ones warn.
        assert_eq!(resolved.chart.presets, vec![(Range::D1, Interval::M5)]);
        assert_eq!(warnings.len(), 3, "{warnings:?}");

        // All presets bad: fall back to the built-in cycle.
        let cfg: Config = toml::from_str("[chart]\npresets = [[\"x\", \"y\"]]").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(resolved.chart.presets, RANGE_PRESETS.to_vec());
        assert_eq!(warnings.len(), 2, "{warnings:?}");
    }

    /// The two panel switches and the average kind: a bad value warns and
    /// keeps the default, exactly like `style`.
    #[test]
    fn chart_panel_and_ma_type_validate_per_entry() {
        let cfg: Config = toml::from_str("[chart]\nvolume = false\nma_type = \"EMA\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert!(!resolved.chart.volume);
        assert_eq!(resolved.chart.ma_type, MaType::Ema);

        let cfg: Config = toml::from_str("[chart]\nma_type = \"wilder\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(resolved.chart.ma_type, MaType::Sma);
        assert_eq!(warnings.len(), 1, "{warnings:?}");

        // Absent section: panels on, averages simple.
        let (resolved, _) = resolve(&Config::default(), None);
        assert!(resolved.chart.volume);
        assert_eq!(resolved.chart.ma_type, MaType::Sma);
    }

    #[test]
    fn right_margin_pct_validates_per_entry() {
        // The full accepted span, including 0 (margin off).
        for (raw, want) in [("0", 0u16), ("20", 20), ("50", 50)] {
            let cfg: Config =
                toml::from_str(&format!("[chart]\nright_margin_pct = {raw}")).unwrap();
            let (resolved, warnings) = resolve(&cfg, None);
            assert!(warnings.is_empty(), "at {raw}: {warnings:?}");
            assert_eq!(resolved.chart.right_margin_pct, want, "at {raw}");
        }

        // Out of range (including negatives, which the raw i64 must survive):
        // warn and keep the default.
        for bad in ["-1", "51", "200"] {
            let cfg: Config =
                toml::from_str(&format!("[chart]\nright_margin_pct = {bad}")).expect("must parse");
            let (resolved, warnings) = resolve(&cfg, None);
            assert_eq!(
                resolved.chart.right_margin_pct, DEFAULT_RIGHT_MARGIN_PCT,
                "at {bad}"
            );
            assert_eq!(warnings.len(), 1, "at {bad}: {warnings:?}");
        }

        assert_eq!(
            ChartDefaults::default().right_margin_pct,
            DEFAULT_RIGHT_MARGIN_PCT
        );
    }

    #[test]
    fn ui_section_validates_per_entry() {
        let cfg: Config = toml::from_str(
            "[ui]\ndefault_view = \"News\"\nnews_layout = \"stacked\"\nnews_scope = \"market\"",
        )
        .unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.ui.view_idx, ui::view_index(ui::ViewId::News));
        assert_eq!(resolved.ui.news_layout, NewsLayout::Stacked);
        assert_eq!(resolved.ui.news_scope, NewsScope::Market);

        let cfg: Config = toml::from_str("[ui]\ndefault_view = \"nwes\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(resolved.ui.view_idx, ui::view_index(ui::ViewId::Split));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("nwes"), "{warnings:?}");
    }

    #[test]
    fn ui_insider_chart_window_parses_and_warns() {
        for (raw, want) in [
            ("off", InsiderChartWindow::Off),
            ("3m", InsiderChartWindow::M3),
            ("12M", InsiderChartWindow::M12),
        ] {
            let cfg: Config = toml::from_str(&format!("[ui]\ninsider_chart = \"{raw}\"")).unwrap();
            let (resolved, warnings) = resolve(&cfg, None);
            assert!(warnings.is_empty(), "{warnings:?}");
            assert_eq!(resolved.ui.insider_chart, want);
        }
        // Junk warns and keeps the default window.
        let cfg: Config = toml::from_str("[ui]\ninsider_chart = \"6m\"").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("insider_chart"), "{warnings:?}");
        assert_eq!(resolved.ui.insider_chart, InsiderChartWindow::M3);
    }

    #[test]
    fn ui_quote_rail_defaults_on_and_switches_off() {
        assert!(UiDefaults::default().quote_rail);
        let cfg: Config = toml::from_str("[ui]\nquote_rail = false").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert!(!resolved.ui.quote_rail);
    }

    #[test]
    fn ui_bare_defaults_off_and_switches_on() {
        assert!(!UiDefaults::default().bare);
        let cfg: Config = toml::from_str("[ui]\nbare = true").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert!(resolved.ui.bare);
    }

    #[test]
    fn news_min_score_validates_per_entry() {
        let cfg: Config =
            toml::from_str("[ui]\nnews_min_score = 4\ninsider_min_score = 8").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.ui.news_min_score, 4);
        assert_eq!(resolved.ui.insider_min_score, 8);

        // Out of range warns and keeps the default; a number outside u8 must
        // not fail the whole file (the raw field is i64 for exactly that).
        for bad in ["0", "11", "300", "-2"] {
            let cfg: Config =
                toml::from_str(&format!("[ui]\nnews_min_score = {bad}")).expect("must parse");
            let (resolved, warnings) = resolve(&cfg, None);
            assert_eq!(
                resolved.ui.news_min_score, DEFAULT_NEWS_MIN_SCORE,
                "at {bad}"
            );
            assert_eq!(warnings.len(), 1, "at {bad}: {warnings:?}");
        }

        let defaults = UiDefaults::default();
        assert_eq!(defaults.news_min_score, DEFAULT_NEWS_MIN_SCORE);
        assert_eq!(defaults.insider_min_score, DEFAULT_INSIDER_MIN_SCORE);
    }

    #[test]
    fn alphai_ttl_validates_per_entry() {
        let cfg: Config = toml::from_str("[ui]\nalphai_ttl_secs = 60").unwrap();
        let (resolved, warnings) = resolve(&cfg, None);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.ui.alphai_ttl, Duration::from_secs(60));

        // Below the budget floor, above a day, or negative: warn and keep
        // the default. "5" is the likely minutes-vs-seconds slip.
        for bad in ["5", "29", "86401", "-300"] {
            let cfg: Config =
                toml::from_str(&format!("[ui]\nalphai_ttl_secs = {bad}")).expect("must parse");
            let (resolved, warnings) = resolve(&cfg, None);
            assert_eq!(resolved.ui.alphai_ttl, alphai::CACHE_TTL, "at {bad}");
            assert_eq!(warnings.len(), 1, "at {bad}: {warnings:?}");
        }

        assert_eq!(UiDefaults::default().alphai_ttl, alphai::CACHE_TTL);
    }

    /// Every ```toml block in the README must parse as a Config and resolve
    /// without warnings, so the documentation cannot rot silently.
    #[test]
    fn readme_toml_examples_parse_and_resolve() {
        let readme = include_str!("../README.md");
        let mut in_block = false;
        let mut block = String::new();
        let mut checked = 0;
        for line in readme.lines() {
            if !in_block && line.trim_start().starts_with("```toml") {
                in_block = true;
                block.clear();
                continue;
            }
            if in_block && line.trim_start().starts_with("```") {
                in_block = false;
                let cfg: Config = toml::from_str(&block)
                    .unwrap_or_else(|e| panic!("README toml does not parse: {e}\n{block}"));
                let (_, warnings) = resolve(&cfg, None);
                assert!(
                    warnings.is_empty(),
                    "README example warns: {warnings:?}\n{block}"
                );
                checked += 1;
                continue;
            }
            if in_block {
                block.push_str(line);
                block.push('\n');
            }
        }
        assert!(
            checked >= 2,
            "expected at least two toml blocks in the README"
        );
    }
}