nika 0.35.4

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Settings View - Provider configuration, theme, preferences
//!
//! 5-section layout:
//!
//! ```text
//! ╭───────────────────────────────────────────────────────────────────────────────╮
//! │  SETTINGS                                                    [Esc] Back       │
//! ├───────────────────────────────────────────────────────────────────────────────┤
//! │                                                                               │
//! │  ┌─ 1. PROVIDERS ────────────────────────────────────────────────────────┐    │
//! │  │  LLM: 4/7 configured  |  MCP: 2/6 configured                          │    │
//! │  └───────────────────────────────────────────────────────────────────────┘    │
//! │                                                                               │
//! │  ┌─ 2. MCP SERVERS ──────────────────────────────────────────────────────┐    │
//! │  │  Active: novanet, perplexity                                          │    │
//! │  └───────────────────────────────────────────────────────────────────────┘    │
//! │                                                                               │
//! │  ┌─ 3. SECRETS ──────────────────────────────────────────────────────────┐    │
//! │  │  Source: daemon  |  Keychain: 5 entries                               │    │
//! │  └───────────────────────────────────────────────────────────────────────┘    │
//! │                                                                               │
//! │  ┌─ 4. PACKAGES ─────────────────────────────────────────────────────────┐    │
//! │  │  Installed: @nika/core@1.0                                            │    │
//! │  └───────────────────────────────────────────────────────────────────────┘    │
//! │                                                                               │
//! │  ┌─ 5. PREFERENCES ──────────────────────────────────────────────────────┐    │
//! │  │  Theme: Dark  |  [1] Light  [2] Dark  [3] Solarized                   │    │
//! │  └───────────────────────────────────────────────────────────────────────┘    │
//! │                                                                               │
//! ╰───────────────────────────────────────────────────────────────────────────────╯
//! ```

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
    Frame,
};

use super::view_trait::View;
use super::{CosmicVariant, TuiView, ViewAction};
use crate::tui::state::TuiState;
use crate::tui::theme::Theme;

/// Settings section for navigation (5 sections for SPN integration)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SettingsSection {
    #[default]
    Providers, // LLM + MCP status summary
    McpServers,  // Active MCP servers
    Secrets,     // Daemon status + keychain info
    Packages,    // Installed packages (future)
    Preferences, // Theme + shortcuts merged
}

impl SettingsSection {
    /// Get all sections in order
    pub const ALL: [SettingsSection; 5] = [
        SettingsSection::Providers,
        SettingsSection::McpServers,
        SettingsSection::Secrets,
        SettingsSection::Packages,
        SettingsSection::Preferences,
    ];

    /// Get next section
    pub fn next(&self) -> Self {
        match self {
            SettingsSection::Providers => SettingsSection::McpServers,
            SettingsSection::McpServers => SettingsSection::Secrets,
            SettingsSection::Secrets => SettingsSection::Packages,
            SettingsSection::Packages => SettingsSection::Preferences,
            SettingsSection::Preferences => SettingsSection::Providers,
        }
    }

    /// Get previous section
    pub fn prev(&self) -> Self {
        match self {
            SettingsSection::Providers => SettingsSection::Preferences,
            SettingsSection::McpServers => SettingsSection::Providers,
            SettingsSection::Secrets => SettingsSection::McpServers,
            SettingsSection::Packages => SettingsSection::Secrets,
            SettingsSection::Preferences => SettingsSection::Packages,
        }
    }

    /// Get section title
    pub fn title(&self) -> &'static str {
        match self {
            SettingsSection::Providers => "PROVIDERS",
            SettingsSection::McpServers => "MCP SERVERS",
            SettingsSection::Secrets => "SECRETS",
            SettingsSection::Packages => "PACKAGES",
            SettingsSection::Preferences => "PREFERENCES",
        }
    }

    /// Get section number (1-indexed for display)
    pub fn number(&self) -> u8 {
        match self {
            SettingsSection::Providers => 1,
            SettingsSection::McpServers => 2,
            SettingsSection::Secrets => 3,
            SettingsSection::Packages => 4,
            SettingsSection::Preferences => 5,
        }
    }
}

/// Secrets info for display
#[derive(Debug, Clone, Default)]
pub struct SecretsInfo {
    /// Source (nika-daemon or fallback)
    pub source: String,
    /// Number of keychain entries
    pub keychain_count: usize,
    /// Whether daemon is available
    pub daemon_available: bool,
}

/// Settings view state (5 sections for SPN integration)
pub struct SettingsView {
    /// Currently selected section
    pub section: SettingsSection,
    /// Provider name (cached for display)
    pub provider_name: String,
    /// Model name (cached for display)
    pub model_name: String,
    /// Current theme name
    pub theme_name: String,
    /// LLM providers configured count
    pub llm_configured: usize,
    /// MCP providers configured count
    pub mcp_configured: usize,
    /// Active MCP servers
    pub active_mcp_servers: Vec<String>,
    /// Secrets info
    pub secrets_info: SecretsInfo,
    /// Installed packages (future)
    pub installed_packages: Vec<String>,
}

impl SettingsView {
    /// Create a new SettingsView
    pub fn new() -> Self {
        Self {
            section: SettingsSection::Providers,
            provider_name: "Auto-detect".to_string(),
            model_name: "".to_string(),
            theme_name: "Dark".to_string(),
            llm_configured: 0,
            mcp_configured: 0,
            active_mcp_servers: Vec::new(),
            secrets_info: SecretsInfo {
                source: "checking...".to_string(),
                keychain_count: 0,
                daemon_available: false,
            },
            installed_packages: Vec::new(),
        }
    }

    /// Update provider info from state
    ///
    /// Called from App when provider changes.
    pub fn update_provider(&mut self, provider: &str, model: &str) {
        self.provider_name = provider.to_string();
        self.model_name = model.to_string();
    }

    /// Update theme name from theme mode
    ///
    /// Called from App when theme changes.
    pub fn update_theme_name(&mut self, name: &str) {
        self.theme_name = name.to_string();
    }

    /// Update provider counts
    pub fn update_provider_counts(&mut self, llm: usize, mcp: usize) {
        self.llm_configured = llm;
        self.mcp_configured = mcp;
    }

    /// Update active MCP servers
    pub fn update_mcp_servers(&mut self, servers: Vec<String>) {
        self.active_mcp_servers = servers;
    }

    /// Update secrets info
    pub fn update_secrets_info(&mut self, source: &str, count: usize, daemon_available: bool) {
        self.secrets_info = SecretsInfo {
            source: source.to_string(),
            keychain_count: count,
            daemon_available,
        };
    }

    /// Update installed packages
    pub fn update_packages(&mut self, packages: Vec<String>) {
        self.installed_packages = packages;
    }

    /// Refresh all settings data by checking environment and system state
    ///
    /// Called when entering Settings view to update:
    /// - LLM provider count (checks env vars)
    /// - MCP provider count (checks env vars)
    /// - Secrets/daemon status
    pub fn refresh_data(&mut self) {
        use crate::tui::providers::{env_var, llm_provider_ids, mcp_provider_ids};

        // Count LLM providers with configured API keys
        let llm_count = llm_provider_ids()
            .filter(|id| {
                let var = env_var(id);
                std::env::var(var).map(|v| !v.is_empty()).unwrap_or(false)
            })
            .count();

        // Count MCP providers with configured credentials
        let mcp_count = mcp_provider_ids()
            .filter(|id| {
                let var = env_var(id);
                std::env::var(var).map(|v| !v.is_empty()).unwrap_or(false)
            })
            .count();

        self.update_provider_counts(llm_count, mcp_count);

        // Check secrets/daemon status
        #[cfg(feature = "nika-daemon")]
        {
            // With nika-daemon feature, secrets go through daemon
            self.update_secrets_info("nika-daemon", llm_count + mcp_count, true);
        }
        #[cfg(not(feature = "nika-daemon"))]
        {
            // Without daemon, we use fallback (env vars only)
            self.update_secrets_info("env vars (fallback)", llm_count + mcp_count, false);
        }

        // MCP servers: Will be updated when a workflow is loaded
        // For now, show current state (from state if any)

        // Packages: Future feature
    }

    /// Render a settings section box
    fn render_section(
        &self,
        frame: &mut Frame,
        area: Rect,
        section: SettingsSection,
        content: Vec<Line<'_>>,
        theme: &Theme,
    ) {
        let is_selected = self.section == section;
        let border_style = if is_selected {
            Style::default()
                .fg(theme.highlight)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme.border_normal)
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style)
            .title(format!(" {} ", section.title()))
            .title_style(if is_selected {
                Style::default()
                    .fg(theme.highlight)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(theme.text_muted)
            });

        let paragraph = Paragraph::new(content)
            .block(block)
            .style(Style::default().fg(theme.text_primary));

        frame.render_widget(paragraph, area);
    }
}

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

impl View for SettingsView {
    fn render(&mut self, frame: &mut Frame, area: Rect, _state: &TuiState, theme: &Theme) {
        // Layout: 5 sections with compact heights
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .margin(1)
            .constraints([
                Constraint::Length(4), // 1. Providers section
                Constraint::Length(4), // 2. MCP Servers section
                Constraint::Length(4), // 3. Secrets section
                Constraint::Length(4), // 4. Packages section
                Constraint::Length(5), // 5. Preferences section (taller for shortcuts)
                Constraint::Min(0),    // Footer
            ])
            .split(area);

        // 1. PROVIDERS section - LLM + MCP status
        let providers_content = vec![
            Line::from(vec![
                Span::styled("  LLM: ", Style::default().fg(theme.text_muted)),
                Span::styled(
                    format!("{}/7", self.llm_configured),
                    Style::default()
                        .fg(if self.llm_configured > 0 {
                            theme.highlight
                        } else {
                            theme.text_muted
                        })
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    " configured  │  MCP: ",
                    Style::default().fg(theme.text_muted),
                ),
                Span::styled(
                    format!("{}/6", self.mcp_configured),
                    Style::default()
                        .fg(if self.mcp_configured > 0 {
                            theme.highlight
                        } else {
                            theme.text_muted
                        })
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(" configured", Style::default().fg(theme.text_muted)),
            ]),
            Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled("[Ctrl+P]", Style::default().fg(theme.highlight)),
                Span::styled(
                    " Configure providers",
                    Style::default().fg(theme.text_muted),
                ),
            ]),
        ];
        self.render_section(
            frame,
            chunks[0],
            SettingsSection::Providers,
            providers_content,
            theme,
        );

        // 2. MCP SERVERS section
        let mcp_servers_display = if self.active_mcp_servers.is_empty() {
            "none active".to_string()
        } else {
            self.active_mcp_servers.join(", ")
        };
        let mcp_content = vec![Line::from(vec![
            Span::styled("  Active: ", Style::default().fg(theme.text_muted)),
            Span::styled(
                mcp_servers_display,
                Style::default()
                    .fg(if self.active_mcp_servers.is_empty() {
                        theme.text_muted
                    } else {
                        theme.highlight
                    })
                    .add_modifier(if self.active_mcp_servers.is_empty() {
                        Modifier::empty()
                    } else {
                        Modifier::BOLD
                    }),
            ),
        ])];
        self.render_section(
            frame,
            chunks[1],
            SettingsSection::McpServers,
            mcp_content,
            theme,
        );

        // 3. SECRETS section
        let secrets_content = vec![Line::from(vec![
            Span::styled("  Source: ", Style::default().fg(theme.text_muted)),
            Span::styled(
                &self.secrets_info.source,
                Style::default()
                    .fg(if self.secrets_info.daemon_available {
                        theme.highlight
                    } else {
                        theme.text_muted
                    })
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("  │  Keychain: ", Style::default().fg(theme.text_muted)),
            Span::styled(
                format!("{} entries", self.secrets_info.keychain_count),
                Style::default().fg(theme.text_primary),
            ),
        ])];
        self.render_section(
            frame,
            chunks[2],
            SettingsSection::Secrets,
            secrets_content,
            theme,
        );

        // 4. PACKAGES section
        let packages_display = if self.installed_packages.is_empty() {
            "none installed".to_string()
        } else {
            self.installed_packages.join(", ")
        };
        let packages_content = vec![Line::from(vec![
            Span::styled("  Installed: ", Style::default().fg(theme.text_muted)),
            Span::styled(
                packages_display,
                Style::default().fg(if self.installed_packages.is_empty() {
                    theme.text_muted
                } else {
                    theme.text_primary
                }),
            ),
        ])];
        self.render_section(
            frame,
            chunks[3],
            SettingsSection::Packages,
            packages_content,
            theme,
        );

        // 5. PREFERENCES section - Theme + shortcuts
        let preferences_content = vec![
            Line::from(vec![
                Span::styled("  Theme: ", Style::default().fg(theme.text_muted)),
                Span::styled(
                    &self.theme_name,
                    Style::default()
                        .fg(theme.highlight)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled("", Style::default().fg(theme.text_muted)),
                Span::styled("[1]", Style::default().fg(theme.highlight)),
                Span::styled(" Light  ", Style::default().fg(theme.text_muted)),
                Span::styled("[2]", Style::default().fg(theme.highlight)),
                Span::styled(" Dark  ", Style::default().fg(theme.text_muted)),
                Span::styled("[3]", Style::default().fg(theme.highlight)),
                Span::styled(" Violet", Style::default().fg(theme.text_muted)),
            ]),
            Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled("[?]", Style::default().fg(theme.highlight)),
                Span::styled(" Help  ", Style::default().fg(theme.text_muted)),
                Span::styled("[Esc]", Style::default().fg(theme.highlight)),
                Span::styled(" Back", Style::default().fg(theme.text_muted)),
            ]),
        ];
        self.render_section(
            frame,
            chunks[4],
            SettingsSection::Preferences,
            preferences_content,
            theme,
        );

        // Footer with navigation hints
        if chunks[5].height > 0 {
            let footer = Paragraph::new(Line::from(vec![
                Span::styled("[Tab]", Style::default().fg(theme.highlight)),
                Span::styled(" Next  ", Style::default().fg(theme.text_muted)),
                Span::styled("[j/k]", Style::default().fg(theme.highlight)),
                Span::styled(" Navigate  ", Style::default().fg(theme.text_muted)),
                Span::styled("[1-3]", Style::default().fg(theme.highlight)),
                Span::styled(" Theme  ", Style::default().fg(theme.text_muted)),
                Span::styled("[Esc]", Style::default().fg(theme.highlight)),
                Span::styled(" Back", Style::default().fg(theme.text_muted)),
            ]))
            .style(Style::default().fg(theme.text_muted));
            frame.render_widget(footer, chunks[5]);
        }
    }

    fn handle_key(&mut self, key: KeyEvent, _state: &mut TuiState) -> ViewAction {
        match key.code {
            // Escape returns to Studio
            KeyCode::Esc | KeyCode::Char('q') => ViewAction::SwitchView(TuiView::Studio),

            // Tab/Shift+Tab cycles sections
            KeyCode::Tab => {
                if key.modifiers.contains(KeyModifiers::SHIFT) {
                    self.section = self.section.prev();
                } else {
                    self.section = self.section.next();
                }
                ViewAction::None
            }
            KeyCode::BackTab => {
                self.section = self.section.prev();
                ViewAction::None
            }

            // j/k for vim-style navigation
            KeyCode::Char('j') | KeyCode::Down => {
                self.section = self.section.next();
                ViewAction::None
            }
            KeyCode::Char('k') | KeyCode::Up => {
                self.section = self.section.prev();
                ViewAction::None
            }

            // Theme shortcuts - direct selection
            KeyCode::Char('1') => ViewAction::SetTheme(CosmicVariant::CosmicLight),
            KeyCode::Char('2') => ViewAction::SetTheme(CosmicVariant::CosmicDark),
            KeyCode::Char('3') => ViewAction::SetTheme(CosmicVariant::CosmicViolet),

            // ? falls through to app-level Help mode

            // Enter on Providers opens provider verification modal
            KeyCode::Enter if self.section == SettingsSection::Providers => {
                ViewAction::VerifyProviders
            }

            // 'w' launches the setup wizard
            KeyCode::Char('w') => ViewAction::LaunchWizard,

            _ => ViewAction::None,
        }
    }

    fn on_enter(&mut self, _state: &mut TuiState) {
        // Refresh provider data when entering Settings view
        // This ensures data is fresh every time the user switches to Settings
        self.refresh_data();
    }

    fn status_line(&self, _state: &TuiState) -> String {
        format!(
            "Control • {} selected | [1-3] Theme • [w] Wizard",
            self.section.title()
        )
    }
}

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

    // ═══════════════════════════════════════════════════════════════════════════════
    // SettingsView Basic Tests
    // ═══════════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_settings_view_new() {
        let view = SettingsView::new();
        assert_eq!(view.section, SettingsSection::Providers);
        assert_eq!(view.provider_name, "Auto-detect");
        assert_eq!(view.llm_configured, 0);
        assert_eq!(view.mcp_configured, 0);
    }

    #[test]
    fn test_section_next() {
        // 5-section cycle: Providers → McpServers → Secrets → Packages → Preferences → Providers
        assert_eq!(
            SettingsSection::Providers.next(),
            SettingsSection::McpServers
        );
        assert_eq!(SettingsSection::McpServers.next(), SettingsSection::Secrets);
        assert_eq!(SettingsSection::Secrets.next(), SettingsSection::Packages);
        assert_eq!(
            SettingsSection::Packages.next(),
            SettingsSection::Preferences
        );
        assert_eq!(
            SettingsSection::Preferences.next(),
            SettingsSection::Providers
        );
    }

    #[test]
    fn test_section_prev() {
        // Reverse cycle: Providers → Preferences → Packages → Secrets → McpServers → Providers
        assert_eq!(
            SettingsSection::Providers.prev(),
            SettingsSection::Preferences
        );
        assert_eq!(
            SettingsSection::Preferences.prev(),
            SettingsSection::Packages
        );
        assert_eq!(SettingsSection::Packages.prev(), SettingsSection::Secrets);
        assert_eq!(SettingsSection::Secrets.prev(), SettingsSection::McpServers);
        assert_eq!(
            SettingsSection::McpServers.prev(),
            SettingsSection::Providers
        );
    }

    #[test]
    fn test_section_titles() {
        assert_eq!(SettingsSection::Providers.title(), "PROVIDERS");
        assert_eq!(SettingsSection::McpServers.title(), "MCP SERVERS");
        assert_eq!(SettingsSection::Secrets.title(), "SECRETS");
        assert_eq!(SettingsSection::Packages.title(), "PACKAGES");
        assert_eq!(SettingsSection::Preferences.title(), "PREFERENCES");
    }

    #[test]
    fn test_section_numbers() {
        assert_eq!(SettingsSection::Providers.number(), 1);
        assert_eq!(SettingsSection::McpServers.number(), 2);
        assert_eq!(SettingsSection::Secrets.number(), 3);
        assert_eq!(SettingsSection::Packages.number(), 4);
        assert_eq!(SettingsSection::Preferences.number(), 5);
    }

    #[test]
    fn test_section_all_constant() {
        assert_eq!(SettingsSection::ALL.len(), 5);
        assert_eq!(SettingsSection::ALL[0], SettingsSection::Providers);
        assert_eq!(SettingsSection::ALL[4], SettingsSection::Preferences);
    }

    #[test]
    fn test_update_provider() {
        let mut view = SettingsView::new();
        view.update_provider("Claude", "claude-sonnet-4-6");
        assert_eq!(view.provider_name, "Claude");
        assert_eq!(view.model_name, "claude-sonnet-4-6");
    }

    #[test]
    fn test_update_theme_name() {
        let mut view = SettingsView::new();
        view.update_theme_name("Light");
        assert_eq!(view.theme_name, "Light");
        view.update_theme_name("Solarized");
        assert_eq!(view.theme_name, "Solarized");
    }

    #[test]
    fn test_update_provider_counts() {
        let mut view = SettingsView::new();
        view.update_provider_counts(4, 2);
        assert_eq!(view.llm_configured, 4);
        assert_eq!(view.mcp_configured, 2);
    }

    #[test]
    fn test_update_mcp_servers() {
        let mut view = SettingsView::new();
        view.update_mcp_servers(vec!["novanet".into(), "perplexity".into()]);
        assert_eq!(view.active_mcp_servers.len(), 2);
        assert!(view.active_mcp_servers.contains(&"novanet".to_string()));
    }

    #[test]
    fn test_update_secrets_info() {
        let mut view = SettingsView::new();
        view.update_secrets_info("nika-daemon", 5, true);
        assert_eq!(view.secrets_info.source, "nika-daemon");
        assert_eq!(view.secrets_info.keychain_count, 5);
        assert!(view.secrets_info.daemon_available);
    }

    #[test]
    fn test_update_packages() {
        let mut view = SettingsView::new();
        view.update_packages(vec!["@spn/core@1.0".into()]);
        assert_eq!(view.installed_packages.len(), 1);
    }

    #[test]
    fn test_status_line() {
        let view = SettingsView::new();
        let state = TuiState::new("test");
        assert!(view.status_line(&state).contains("PROVIDERS"));
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // Key Handling Tests
    // ═══════════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_handle_key_escape_returns_studio() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        let key = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        let action = view.handle_key(key, &mut state);
        assert!(matches!(action, ViewAction::SwitchView(TuiView::Studio)));
    }

    #[test]
    fn test_handle_key_tab_cycles_sections() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        assert_eq!(view.section, SettingsSection::Providers);

        let key = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);

        // Cycle through all 5 sections
        view.handle_key(key, &mut state);
        assert_eq!(view.section, SettingsSection::McpServers);

        view.handle_key(key, &mut state);
        assert_eq!(view.section, SettingsSection::Secrets);

        view.handle_key(key, &mut state);
        assert_eq!(view.section, SettingsSection::Packages);

        view.handle_key(key, &mut state);
        assert_eq!(view.section, SettingsSection::Preferences);

        // Wraps back to Providers
        view.handle_key(key, &mut state);
        assert_eq!(view.section, SettingsSection::Providers);
    }

    #[test]
    fn test_handle_key_shift_tab_cycles_backwards() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        let key = KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT);
        view.handle_key(key, &mut state);
        assert_eq!(view.section, SettingsSection::Preferences);
    }

    #[test]
    fn test_handle_key_question_does_nothing() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        let key = KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE);
        let action = view.handle_key(key, &mut state);
        assert!(matches!(action, ViewAction::None));
    }

    #[test]
    fn test_handle_key_vim_navigation() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");

        // j moves to next section
        let key_j = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
        view.handle_key(key_j, &mut state);
        assert_eq!(view.section, SettingsSection::McpServers);

        // k moves to previous section
        let key_k = KeyEvent::new(KeyCode::Char('k'), KeyModifiers::NONE);
        view.handle_key(key_k, &mut state);
        assert_eq!(view.section, SettingsSection::Providers);
    }

    #[test]
    fn test_handle_key_enter_on_providers() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        view.section = SettingsSection::Providers;
        let key = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
        let action = view.handle_key(key, &mut state);
        assert!(matches!(action, ViewAction::VerifyProviders));
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // Theme Shortcut Tests
    // ═══════════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_handle_key_1_sets_light_theme() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        let key = KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE);
        let action = view.handle_key(key, &mut state);
        assert!(matches!(
            action,
            ViewAction::SetTheme(CosmicVariant::CosmicLight)
        ));
    }

    #[test]
    fn test_handle_key_2_sets_dark_theme() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        let key = KeyEvent::new(KeyCode::Char('2'), KeyModifiers::NONE);
        let action = view.handle_key(key, &mut state);
        assert!(matches!(
            action,
            ViewAction::SetTheme(CosmicVariant::CosmicDark)
        ));
    }

    #[test]
    fn test_handle_key_3_sets_violet_theme() {
        let mut view = SettingsView::new();
        let mut state = TuiState::new("test");
        let key = KeyEvent::new(KeyCode::Char('3'), KeyModifiers::NONE);
        let action = view.handle_key(key, &mut state);
        assert!(matches!(
            action,
            ViewAction::SetTheme(CosmicVariant::CosmicViolet)
        ));
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // SecretsInfo Tests
    // ═══════════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_secrets_info_default() {
        let info = SecretsInfo::default();
        assert!(info.source.is_empty());
        assert_eq!(info.keychain_count, 0);
        assert!(!info.daemon_available);
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // refresh_data Tests
    // ═══════════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_refresh_data_updates_provider_counts() {
        let mut view = SettingsView::new();
        assert_eq!(view.llm_configured, 0, "Initial llm count should be 0");
        assert_eq!(view.mcp_configured, 0, "Initial mcp count should be 0");

        // refresh_data checks env vars - without any set, counts should remain 0
        view.refresh_data();

        // Without env vars, both should be 0
        // (actual count depends on what's in the environment)
        // Just verify it doesn't panic and updates secrets_info
        assert!(
            !view.secrets_info.source.is_empty(),
            "Source should be set after refresh"
        );
    }

    #[test]
    #[serial]
    fn test_refresh_data_with_env_var() {
        use std::env;

        let mut view = SettingsView::new();

        // Set a fake API key env var
        env::set_var("ANTHROPIC_API_KEY", "sk-ant-test-key");

        view.refresh_data();

        // Should detect at least 1 LLM provider
        assert!(view.llm_configured >= 1, "Should detect ANTHROPIC_API_KEY");

        // Clean up
        env::remove_var("ANTHROPIC_API_KEY");
    }

    #[test]
    fn test_refresh_data_sets_secrets_source() {
        let mut view = SettingsView::new();
        view.refresh_data();

        // Source should be set to either "nika-daemon" or "env vars (fallback)"
        #[cfg(feature = "nika-daemon")]
        assert_eq!(view.secrets_info.source, "nika-daemon");

        #[cfg(not(feature = "nika-daemon"))]
        assert_eq!(view.secrets_info.source, "env vars (fallback)");
    }
}