aranet-cli 0.2.0

Command-line interface for Aranet environmental sensors
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
//! Aranet CLI - Command-line interface for Aranet environmental sensors.
//!
//! This binary supports multiple feature configurations:
//! - `cli` feature: Provides command-line interface with subcommands
//! - `tui` feature: Provides interactive terminal dashboard
//! - Both features: CLI with `tui` subcommand to launch dashboard
//! - Neither feature: Compile error (at least one required)

// Ensure at least one feature is enabled
#[cfg(not(any(feature = "cli", feature = "tui")))]
compile_error!("At least one of 'cli' or 'tui' features must be enabled");

// CLI modules (conditionally compiled)
#[cfg(feature = "cli")]
mod cli;
#[cfg(feature = "cli")]
mod commands;
#[cfg(feature = "cli")]
mod format;
#[cfg(feature = "cli")]
mod style;
#[cfg(feature = "cli")]
mod util;

// Config is defined in lib.rs but re-exported for main.rs use
#[cfg(feature = "cli")]
use aranet_cli::config;

// TUI module (conditionally compiled)
#[cfg(feature = "tui")]
mod tui;

use anyhow::Result;

#[cfg(feature = "cli")]
use clap::{CommandFactory, Parser};
#[cfg(feature = "cli")]
use cli::{AliasSubcommand, Cli, Commands, ConfigAction, ConfigKey, OutputFormat, ReportFormat};
#[cfg(feature = "cli")]
use commands::{
    AliasAction, HistoryArgs, ServerArgs, SyncArgs, WatchArgs, cmd_alias, cmd_cache, cmd_doctor,
    cmd_history, cmd_info, cmd_read, cmd_report, cmd_scan, cmd_server, cmd_set, cmd_status,
    cmd_sync, cmd_watch,
};
#[cfg(feature = "cli")]
use config::{Config, get_device_source, resolve_alias_with_info, resolve_timeout};
#[cfg(feature = "cli")]
use format::FormatOptions;
#[cfg(feature = "cli")]
use std::io;
#[cfg(feature = "cli")]
use std::time::Duration;
#[cfg(feature = "cli")]
use tracing_subscriber::EnvFilter;

// =============================================================================
// Main Entry Point
// =============================================================================

/// TUI-only mode: Launch the dashboard directly
#[cfg(all(feature = "tui", not(feature = "cli")))]
#[tokio::main]
async fn main() -> Result<()> {
    tui::run().await
}

/// CLI mode (with or without TUI): Parse commands and dispatch
#[cfg(feature = "cli")]
#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Handle completions command early (before tracing init)
    if let Commands::Completions { shell } = cli.command {
        let mut cmd = Cli::command();
        clap_complete::generate(shell, &mut cmd, env!("CARGO_BIN_NAME"), &mut io::stdout());
        return Ok(());
    }

    // Handle config commands early
    if let Commands::Config { ref action } = cli.command {
        return handle_config_command(action);
    }

    // Handle alias commands early
    if let Commands::Alias { ref action } = cli.command {
        return handle_alias_command(action, cli.quiet);
    }

    // Handle server command early so it doesn't depend on the interactive CLI config.
    if let Commands::Server {
        ref config,
        ref bind,
        ref database,
        no_collector,
        daemon,
    } = cli.command
    {
        return cmd_server(ServerArgs {
            config: config.clone(),
            bind: bind.clone(),
            database: database.clone(),
            no_collector,
            daemon,
        })
        .await;
    }

    // Handle TUI command early (when both features enabled)
    #[cfg(feature = "tui")]
    if let Commands::Tui = cli.command {
        return tui::run().await;
    }

    // Handle GUI command early (when gui feature enabled)
    #[cfg(feature = "gui")]
    if let Commands::Gui = cli.command {
        return aranet_cli::gui::run();
    }

    // Load config for device resolution
    let config = Config::load_or_default()?;

    // Initialize tracing (write to stderr so stdout is clean for data)
    let filter = if cli.quiet {
        EnvFilter::new("warn")
    } else if cli.verbose {
        EnvFilter::new("debug")
    } else {
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn"))
    };

    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .init();

    let output = cli.output.as_ref();
    let no_color = cli.no_color || config.no_color || no_color_from_env();
    let quiet = cli.quiet;
    let compact = cli.compact;
    let style = cli.style;
    // Base fahrenheit from config (can be overridden per-command)
    let config_fahrenheit = config.fahrenheit;
    // Base bq from config (can be overridden per-command)
    let config_bq = config.bq;
    // Base inhg from config (can be overridden per-command)
    let config_inhg = config.inhg;
    // Parse config format (used as fallback when command format is default)
    let config_format = config.format.as_deref().and_then(parse_format);

    match cli.command {
        Commands::Scan {
            timeout,
            format,
            no_header,
            alias,
        } => {
            let format = resolve_format_with_config(cli.json, format, config_format);
            let timeout = resolve_timeout(timeout, &config, 10);
            let opts = FormatOptions::new(no_color, config_fahrenheit, style)
                .with_no_header(no_header)
                .with_compact(compact);
            cmd_scan(timeout, format, output, quiet, alias, &opts, &config).await?;
        }
        Commands::Examples => {
            print_examples();
        }
        Commands::Read {
            device,
            output: out,
            passive,
        } => {
            let format = resolve_format_with_config(cli.json, out.format, config_format);
            // If no devices specified, try last device before falling back to interactive
            let devices = if device.device.is_empty() {
                if let Some(dev) = resolve_device_with_hint(None, &config, quiet) {
                    vec![dev]
                } else {
                    vec![]
                }
            } else {
                resolve_devices_with_feedback(device.device, &config, quiet)
            };
            let timeout = Duration::from_secs(resolve_timeout(device.timeout, &config, 30));
            let opts =
                FormatOptions::new(no_color, out.resolve_fahrenheit(config_fahrenheit), style)
                    .with_no_header(out.no_header)
                    .with_compact(compact)
                    .with_bq(out.resolve_bq(config_bq))
                    .with_inhg(out.resolve_inhg(config_inhg));
            cmd_read(devices, timeout, format, output, quiet, passive, &opts).await?;
        }
        Commands::Status {
            device,
            output: out,
            brief,
        } => {
            let format = resolve_format_with_config(cli.json, out.format, config_format);
            let dev = resolve_device_with_hint(device.device, &config, quiet);
            let timeout = Duration::from_secs(resolve_timeout(device.timeout, &config, 30));
            let opts =
                FormatOptions::new(no_color, out.resolve_fahrenheit(config_fahrenheit), style)
                    .with_no_header(out.no_header)
                    .with_compact(compact)
                    .with_bq(out.resolve_bq(config_bq))
                    .with_inhg(out.resolve_inhg(config_inhg));
            cmd_status(dev, timeout, format, output, &opts, brief).await?;
        }
        Commands::History {
            device,
            output: out,
            count,
            since,
            until,
            cache,
        } => {
            let format = resolve_format_with_config(cli.json, out.format, config_format);
            let dev = resolve_device_with_hint(device.device, &config, quiet);
            // History uses a longer default timeout (60s)
            let timeout = Duration::from_secs(resolve_timeout(device.timeout, &config, 30));
            let opts =
                FormatOptions::new(no_color, out.resolve_fahrenheit(config_fahrenheit), style)
                    .with_no_header(out.no_header)
                    .with_compact(compact)
                    .with_bq(out.resolve_bq(config_bq))
                    .with_inhg(out.resolve_inhg(config_inhg));
            cmd_history(HistoryArgs {
                device: dev,
                count,
                since,
                until,
                timeout,
                format,
                output,
                quiet,
                opts: &opts,
                cache,
            })
            .await?;
        }
        Commands::Info {
            device,
            format,
            no_header,
        } => {
            let format = resolve_format_with_config(cli.json, format, config_format);
            let dev = resolve_device_with_hint(device.device, &config, quiet);
            let timeout = Duration::from_secs(resolve_timeout(device.timeout, &config, 30));
            let opts = FormatOptions::new(no_color, config_fahrenheit, style)
                .with_no_header(no_header)
                .with_compact(compact);
            cmd_info(dev, timeout, format, output, quiet, &opts).await?;
        }
        Commands::Set {
            device,
            setting,
            force,
        } => {
            let dev = resolve_device_with_hint(device.device, &config, quiet);
            let timeout = Duration::from_secs(resolve_timeout(device.timeout, &config, 30));
            cmd_set(dev, timeout, setting, quiet, force).await?;
        }
        Commands::Watch {
            device,
            output: out,
            interval,
            count,
            passive,
        } => {
            let format = resolve_format_with_config(cli.json, out.format, config_format);
            // For passive mode without explicit device, don't resolve to last device
            // This allows watching ALL devices via advertisements
            let dev = if passive && device.device.is_none() {
                None
            } else {
                resolve_device_with_hint(device.device, &config, quiet)
            };
            let timeout = Duration::from_secs(resolve_timeout(device.timeout, &config, 30));
            let opts =
                FormatOptions::new(no_color, out.resolve_fahrenheit(config_fahrenheit), style)
                    .with_no_header(out.no_header)
                    .with_compact(compact)
                    .with_bq(out.resolve_bq(config_bq))
                    .with_inhg(out.resolve_inhg(config_inhg));
            cmd_watch(WatchArgs {
                device: dev,
                interval,
                count,
                timeout,
                format,
                output,
                passive,
                opts: &opts,
            })
            .await?;
        }
        Commands::Doctor => {
            cmd_doctor(cli.verbose, no_color).await?;
        }
        Commands::Sync {
            device,
            format,
            full,
            all,
        } => {
            let format = resolve_format_with_config(cli.json, format, config_format);
            cmd_sync(
                SyncArgs {
                    device,
                    format,
                    full,
                    all,
                },
                &config,
            )
            .await?;
        }
        Commands::Cache { action } => {
            cmd_cache(action, &config)?;
        }
        Commands::Report {
            device,
            all,
            period,
            format,
            output: out,
        } => {
            let format = format.or(if cli.json {
                Some(ReportFormat::Json)
            } else {
                None
            });
            let device = if all {
                None
            } else {
                resolve_device_with_hint(device, &config, quiet)
            };
            cmd_report(device, all, period, format, out, &config)?;
        }
        Commands::Server { .. } => unreachable!(), // Handled above
        Commands::Config { .. } => unreachable!(),
        Commands::Alias { .. } => unreachable!(),
        Commands::Completions { .. } => unreachable!(),
        #[cfg(feature = "tui")]
        Commands::Tui => unreachable!(), // Handled above
        #[cfg(feature = "gui")]
        Commands::Gui => unreachable!(), // Handled above
    }

    Ok(())
}

#[cfg(feature = "cli")]
fn handle_alias_command(action: &AliasSubcommand, quiet: bool) -> Result<()> {
    let alias_action = match action {
        AliasSubcommand::List => AliasAction::List,
        AliasSubcommand::Set { name, address } => AliasAction::Set {
            name: name.clone(),
            address: address.clone(),
        },
        AliasSubcommand::Remove { name } => AliasAction::Remove { name: name.clone() },
    };
    cmd_alias(alias_action, quiet)
}

#[cfg(feature = "cli")]
fn handle_config_command(action: &ConfigAction) -> Result<()> {
    match action {
        ConfigAction::Path => {
            println!("{}", Config::path().display());
        }
        ConfigAction::Show => {
            let config = Config::load_or_default()?;
            println!("{}", toml::to_string_pretty(&config)?);
        }
        ConfigAction::Init => {
            let path = Config::path();
            if path.exists() {
                eprintln!("Config file already exists: {}", path.display());
            } else {
                Config::default().save()?;
                println!("Created config file: {}", path.display());
            }
        }
        ConfigAction::Get { key } => {
            let config = Config::load_or_default()?;
            let value = match key {
                ConfigKey::Device => config.device.unwrap_or_default(),
                ConfigKey::Format => config.format.unwrap_or_else(|| "text".to_string()),
                ConfigKey::Timeout => config.timeout.map(|t| t.to_string()).unwrap_or_default(),
                ConfigKey::NoColor => config.no_color.to_string(),
                ConfigKey::Fahrenheit => config.fahrenheit.to_string(),
                ConfigKey::Inhg => config.inhg.to_string(),
                ConfigKey::Bq => config.bq.to_string(),
            };
            println!("{}", value);
        }
        ConfigAction::Set { key, value } => {
            let mut config = Config::load_or_default()?;
            match key {
                ConfigKey::Device => config.device = Some(value.clone()),
                ConfigKey::Format => {
                    // Validate format value
                    match value.to_lowercase().as_str() {
                        "text" | "json" | "csv" => config.format = Some(value.to_lowercase()),
                        _ => anyhow::bail!(
                            "Invalid format: {}. Valid values: text, json, csv",
                            value
                        ),
                    }
                }
                ConfigKey::Timeout => {
                    let seconds: u64 = value.parse().map_err(|_| {
                        anyhow::anyhow!(
                            "Invalid timeout value: {}. Must be a positive integer (seconds).",
                            value
                        )
                    })?;
                    config.timeout = Some(seconds);
                }
                ConfigKey::NoColor => {
                    config.no_color = parse_bool(value).map_err(|_| {
                        anyhow::anyhow!("Invalid no_color value: {}. Use 'true' or 'false'.", value)
                    })?;
                }
                ConfigKey::Fahrenheit => {
                    config.fahrenheit = parse_bool(value).map_err(|_| {
                        anyhow::anyhow!(
                            "Invalid fahrenheit value: {}. Use 'true' or 'false'.",
                            value
                        )
                    })?;
                }
                ConfigKey::Inhg => {
                    config.inhg = parse_bool(value).map_err(|_| {
                        anyhow::anyhow!("Invalid inhg value: {}. Use 'true' or 'false'.", value)
                    })?;
                }
                ConfigKey::Bq => {
                    config.bq = parse_bool(value).map_err(|_| {
                        anyhow::anyhow!("Invalid bq value: {}. Use 'true' or 'false'.", value)
                    })?;
                }
            }
            config.save()?;
            println!("Set {:?} = {}", key, value);
        }
        ConfigAction::Unset { key } => {
            let mut config = Config::load_or_default()?;
            match key {
                ConfigKey::Device => config.device = None,
                ConfigKey::Format => config.format = None,
                ConfigKey::Timeout => config.timeout = None,
                ConfigKey::NoColor => config.no_color = false,
                ConfigKey::Fahrenheit => config.fahrenheit = false,
                ConfigKey::Inhg => config.inhg = false,
                ConfigKey::Bq => config.bq = false,
            }
            config.save()?;
            println!("Unset {:?}", key);
        }
    }
    Ok(())
}

/// Parse a boolean value from a string, supporting common representations.
#[cfg(feature = "cli")]
fn parse_bool(s: &str) -> std::result::Result<bool, ()> {
    match s.to_lowercase().as_str() {
        "true" | "yes" | "on" | "1" => Ok(true),
        "false" | "no" | "off" | "0" => Ok(false),
        _ => Err(()),
    }
}

/// Parse an output format from a config string.
#[cfg(feature = "cli")]
fn parse_format(s: &str) -> Option<OutputFormat> {
    match s.to_lowercase().as_str() {
        "text" => Some(OutputFormat::Text),
        "json" => Some(OutputFormat::Json),
        "csv" => Some(OutputFormat::Csv),
        _ => None,
    }
}

/// Resolve output format with config fallback.
/// Priority: --json flag > --format arg (if not default) > config format > default (text)
#[cfg(feature = "cli")]
fn resolve_format_with_config(
    cli_json: bool,
    cmd_format: Option<OutputFormat>,
    config_format: Option<OutputFormat>,
) -> OutputFormat {
    if cli_json {
        OutputFormat::Json
    } else if let Some(cmd_format) = cmd_format {
        cmd_format
    } else {
        config_format.unwrap_or(OutputFormat::Text)
    }
}

/// Respect the de-facto NO_COLOR standard, which is enabled by presence.
#[cfg(feature = "cli")]
fn no_color_from_env() -> bool {
    std::env::var_os("NO_COLOR").is_some()
}

/// Resolve multiple devices with alias feedback.
/// Shows a message when aliases are resolved to device addresses.
#[cfg(feature = "cli")]
fn resolve_devices_with_feedback(
    devices: Vec<String>,
    config: &Config,
    quiet: bool,
) -> Vec<String> {
    devices
        .into_iter()
        .map(|d| {
            let (resolved, was_alias, alias_name) = resolve_alias_with_info(&d, config);
            if !quiet
                && was_alias
                && let Some(alias) = alias_name
            {
                eprintln!("Using alias '{}' -> {}", alias, resolved);
            }
            resolved
        })
        .collect()
}

/// Show a message about which device source is being used.
/// Returns the resolved device identifier.
#[cfg(feature = "cli")]
fn resolve_device_with_hint(
    device: Option<String>,
    config: &Config,
    quiet: bool,
) -> Option<String> {
    let (resolved, source) = get_device_source(device.as_deref(), config);

    // Show hint about device source (unless quiet mode)
    if !quiet
        && let Some(source) = source
        && let Some(ref dev) = resolved
    {
        let name = config
            .last_device_name
            .as_deref()
            .filter(|_| source == "last");
        match (source, name) {
            ("last", Some(name)) => {
                eprintln!("Using last connected device: {} ({})", name, dev);
            }
            ("last", None) => {
                eprintln!("Using last connected device: {}", dev);
            }
            ("store", _) => {
                eprintln!("Using known device from database: {}", dev);
            }
            ("default", _) => {
                // Don't show message for default device - user explicitly configured it
            }
            _ => {}
        }
    }

    resolved
}

/// Print common usage examples.
#[cfg(feature = "cli")]
fn print_examples() {
    use owo_colors::OwoColorize;

    println!("{}", "Aranet CLI Examples".bold().underline());
    println!();
    println!("{}", "Getting Started:".bold());
    println!("  aranet scan                      # Find nearby Aranet devices");
    println!("  aranet scan --alias              # Scan and save device aliases interactively");
    println!("  aranet doctor                    # Check Bluetooth connectivity");
    println!();
    println!("{}", "Reading Data:".bold());
    println!("  aranet read                      # Read from default/last device");
    println!("  aranet read -d living-room       # Read using device alias");
    println!("  aranet status                    # Quick one-line status");
    println!("  aranet status --brief            # Super-compact status for scripting");
    println!();
    println!("{}", "Monitoring:".bold());
    println!("  aranet watch                     # Continuously monitor (60s intervals)");
    println!("  aranet watch -i 30               # Monitor every 30 seconds");
    println!("  aranet watch -n 5                # Take 5 readings then exit");
    println!();
    println!("{}", "History & Export:".bold());
    println!("  aranet history                   # Show all stored readings");
    println!("  aranet history --since 2024-01-01");
    println!("  aranet history -f csv > data.csv # Export to CSV file");
    println!("  aranet history -f json           # Export as JSON");
    println!("  aranet report --period weekly    # Summarize cached history");
    println!();
    println!("{}", "Device Management:".bold());
    println!("  aranet alias list                # Show saved aliases");
    println!("  aranet alias set office <uuid>   # Create an alias");
    println!("  aranet config set device <uuid>  # Set default device");
    println!("  aranet config show               # Show current configuration");
    println!();
    println!("{}", "Output Options:".bold());
    println!("  aranet read --json               # Output as JSON");
    println!("  aranet read --fahrenheit         # Use Fahrenheit for temperature");
    println!("  aranet read --bq                 # Use Bq/m3 for radon (instead of pCi/L)");
    println!("  aranet read --no-color           # Disable colored output");
    println!();
}

// ============================================================================
// CLI Tests
// ============================================================================

#[cfg(all(test, feature = "cli"))]
mod tests {
    use super::*;

    // ========================================================================
    // resolve_format_with_config tests
    // ========================================================================

    #[test]
    fn test_resolve_format_json_flag_overrides_text() {
        let result = resolve_format_with_config(true, None, None);
        assert!(matches!(result, OutputFormat::Json));
    }

    #[test]
    fn test_resolve_format_json_flag_overrides_csv() {
        let result = resolve_format_with_config(true, Some(OutputFormat::Csv), None);
        assert!(matches!(result, OutputFormat::Json));
    }

    #[test]
    fn test_resolve_format_json_flag_overrides_config() {
        let result = resolve_format_with_config(true, None, Some(OutputFormat::Csv));
        assert!(matches!(result, OutputFormat::Json));
    }

    #[test]
    fn test_resolve_format_explicit_csv_used() {
        let result = resolve_format_with_config(false, Some(OutputFormat::Csv), None);
        assert!(matches!(result, OutputFormat::Csv));
    }

    #[test]
    fn test_resolve_format_explicit_json_used() {
        let result = resolve_format_with_config(false, Some(OutputFormat::Json), None);
        assert!(matches!(result, OutputFormat::Json));
    }

    #[test]
    fn test_resolve_format_config_fallback() {
        let result = resolve_format_with_config(false, None, Some(OutputFormat::Json));
        assert!(matches!(result, OutputFormat::Json));
    }

    #[test]
    fn test_resolve_format_default_text() {
        let result = resolve_format_with_config(false, None, None);
        assert!(matches!(result, OutputFormat::Text));
    }

    #[test]
    fn test_resolve_format_explicit_text_overrides_config() {
        let result =
            resolve_format_with_config(false, Some(OutputFormat::Text), Some(OutputFormat::Json));
        assert!(matches!(result, OutputFormat::Text));
    }

    // ========================================================================
    // parse_bool tests
    // ========================================================================

    #[test]
    fn test_parse_bool_true_variants() {
        assert_eq!(parse_bool("true"), Ok(true));
        assert_eq!(parse_bool("True"), Ok(true));
        assert_eq!(parse_bool("TRUE"), Ok(true));
        assert_eq!(parse_bool("yes"), Ok(true));
        assert_eq!(parse_bool("on"), Ok(true));
        assert_eq!(parse_bool("1"), Ok(true));
    }

    #[test]
    fn test_parse_bool_false_variants() {
        assert_eq!(parse_bool("false"), Ok(false));
        assert_eq!(parse_bool("False"), Ok(false));
        assert_eq!(parse_bool("FALSE"), Ok(false));
        assert_eq!(parse_bool("no"), Ok(false));
        assert_eq!(parse_bool("off"), Ok(false));
        assert_eq!(parse_bool("0"), Ok(false));
    }

    #[test]
    fn test_parse_bool_invalid() {
        assert!(parse_bool("invalid").is_err());
        assert!(parse_bool("maybe").is_err());
        assert!(parse_bool("").is_err());
    }

    // ========================================================================
    // parse_format tests
    // ========================================================================

    #[test]
    fn test_parse_format_valid() {
        assert!(matches!(parse_format("text"), Some(OutputFormat::Text)));
        assert!(matches!(parse_format("Text"), Some(OutputFormat::Text)));
        assert!(matches!(parse_format("json"), Some(OutputFormat::Json)));
        assert!(matches!(parse_format("JSON"), Some(OutputFormat::Json)));
        assert!(matches!(parse_format("csv"), Some(OutputFormat::Csv)));
        assert!(matches!(parse_format("CSV"), Some(OutputFormat::Csv)));
    }

    #[test]
    fn test_parse_format_invalid() {
        assert!(parse_format("xml").is_none());
        assert!(parse_format("").is_none());
        assert!(parse_format("invalid").is_none());
    }
}