lino-arguments 0.3.0

A unified configuration library combining environment variables and CLI arguments with a clear priority chain
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
//! lino-arguments - A unified configuration library
//!
//! Combines environment variables and CLI arguments into a single
//! easy-to-use configuration system with clear priority ordering.
//!
//! Works like a combination of [clap](https://docs.rs/clap) and
//! [dotenvy](https://docs.rs/dotenvy), but also with support for `.lenv` files
//! via [lino-env](https://docs.rs/lino-env).
//!
//! Priority (highest to lowest):
//! 1. CLI arguments (manually entered options)
//! 2. Environment variables (from process env)
//! 3. `.lenv` file (local environment overrides)
//! 4. `.env` file (standard dotenv, for compatibility)
//! 5. Default values
//!
//! # Drop-in Replacement for clap
//!
//! Just replace `use clap::Parser` with `use lino_arguments::Parser` —
//! everything else stays exactly the same. `.lenv` and `.env` files are
//! loaded automatically at startup before `main()` runs:
//!
//! ```rust,ignore
//! // Only change: import from lino_arguments instead of clap
//! use lino_arguments::Parser;
//!
//! #[derive(Parser, Debug)]
//! #[command(name = "my-app")]
//! struct Args {
//!     #[arg(long, env = "PORT", default_value = "3000")]
//!     port: u16,
//!
//!     #[arg(long, env = "API_KEY")]
//!     api_key: Option<String>,
//!
//!     #[arg(long, env = "VERBOSE")]
//!     verbose: bool,
//! }
//!
//! fn main() {
//!     let args = Args::parse(); // .lenv + .env already loaded
//!     println!("port = {}", args.port);
//! }
//! ```
//!
//! # Functional Usage (like the JavaScript API)
//!
//! ```rust,ignore
//! use lino_arguments::make_config;
//!
//! let config = make_config(|c| {
//!     c.lenv(".lenv")
//!      .env(".env")
//!      .option("port", "Server port", "3000")
//!      .option("api-key", "API key", "")
//!      .flag("verbose", "Enable verbose logging")
//! });
//!
//! let port: u16 = config.get("port").parse().unwrap();
//! let verbose: bool = config.get_bool("verbose");
//! ```
//!
//! # .lenv File Format
//!
//! The `.lenv` file format uses `: ` (colon-space) as the separator:
//!
//! ```text
//! PORT: 8080
//! API_KEY: my-secret-key
//! DEBUG: true
//! ```

use std::collections::HashMap;
use std::env;
use thiserror::Error;

// Re-export clap's Parser (derive macro + trait) so that `#[derive(Parser)]`
// and `Args::parse()` work as a true drop-in replacement for clap.
// The .lenv/.env files are loaded automatically at startup via the `ctor` crate,
// so `Args::parse()` sees the environment variables from these files without
// any extra `init()` call.
pub use clap::Parser;
pub use clap::{Args, Subcommand, ValueEnum};

// Re-export the arg attribute macro
pub use clap::arg;

// Re-export the command macro for #[command(...)] attribute
pub use clap::command;

// Re-export lino-env for direct file operations
pub use lino_env::{read_lino_env, write_lino_env, LinoEnv};

// ============================================================================
// Error Types
// ============================================================================

/// Errors that can occur during configuration
#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Environment variable error: {0}")]
    EnvError(String),

    #[error("Parse error: {0}")]
    ParseError(String),

    #[error("Configuration file error: {0}")]
    FileError(String),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

// ============================================================================
// Auto-initialization via ctor
// ============================================================================

/// Automatically load `.lenv` and `.env` files at program startup.
///
/// This runs before `main()`, so by the time `Args::parse()` is called,
/// all values from `.lenv` and `.env` are already in the process environment.
/// This is what makes the drop-in replacement work: just change the import
/// from `use clap::Parser` to `use lino_arguments::Parser` and everything
/// else stays the same.
#[ctor::ctor]
fn auto_init() {
    init();
}

// ============================================================================
// init() — Load .lenv and .env files into the process environment
// ============================================================================

/// Load `.lenv` and `.env` files into the process environment.
///
/// Loads `.lenv` first (higher priority), then `.env` (lower priority).
/// Neither overwrites existing environment variables.
///
/// This is called automatically at program startup. You only need to call
/// it manually if you want to reload files after the program has started,
/// or if you're using [`init_with()`] with custom paths.
pub fn init() {
    load_lenv_file(".lenv").ok();
    load_env_file(".env").ok();
}

/// Load specified `.lenv` and `.env` files into the process environment.
///
/// Like [`init()`], but with custom file paths.
///
/// ```rust,ignore
/// lino_arguments::init_with(Some("config/app.lenv"), Some(".env.local"));
/// let args = Args::parse();
/// ```
pub fn init_with(lenv_path: Option<&str>, env_path: Option<&str>) {
    if let Some(path) = lenv_path {
        load_lenv_file(path).ok();
    }
    if let Some(path) = env_path {
        load_env_file(path).ok();
    }
}

// ============================================================================
// LinoParser Trait — convenience extension for custom file paths
// ============================================================================

/// Extension trait for `clap::Parser` that provides methods for parsing
/// with custom `.lenv`/`.env` file paths.
///
/// Automatically implemented for any type that derives `Parser`.
///
/// For standard usage, you don't need this trait at all — just use
/// `Args::parse()` directly and `.lenv`/`.env` files are loaded
/// automatically at startup.
///
/// Use `LinoParser` methods only when you need custom file paths:
///
/// ```rust,ignore
/// use lino_arguments::{Parser, LinoParser};
///
/// #[derive(Parser, Debug)]
/// struct Args {
///     #[arg(long, env = "PORT", default_value = "3000")]
///     port: u16,
/// }
///
/// // Standard usage — just parse(), .lenv/.env already loaded:
/// let args = Args::parse();
///
/// // Custom file paths:
/// let args = Args::lino_parse_from_with(
///     ["app"], Some("custom.lenv"), Some("custom.env")
/// );
/// ```
pub trait LinoParser: Parser {
    /// Parse CLI arguments after loading `.lenv` and `.env` files.
    /// Equivalent to `Args::parse()` (since auto-init already loads files).
    fn lino_parse() -> Self {
        init();
        <Self as Parser>::parse()
    }

    /// Parse CLI arguments after loading specified `.lenv` and `.env` files.
    fn lino_parse_with(lenv_path: Option<&str>, env_path: Option<&str>) -> Self {
        init_with(lenv_path, env_path);
        <Self as Parser>::parse()
    }

    /// Parse from custom arguments after loading `.lenv` and `.env` files.
    /// Useful for testing.
    fn lino_parse_from<I, T>(args: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString> + Clone,
    {
        init();
        <Self as Parser>::parse_from(args)
    }

    /// Parse from custom arguments after loading specified config files.
    /// Useful for testing.
    fn lino_parse_from_with<I, T>(args: I, lenv_path: Option<&str>, env_path: Option<&str>) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString> + Clone,
    {
        init_with(lenv_path, env_path);
        <Self as Parser>::parse_from(args)
    }
}

/// Blanket implementation: any type that derives `clap::Parser`
/// automatically gets `LinoParser` methods.
impl<T: Parser> LinoParser for T {}

// ============================================================================
// .lenv File Loading
// ============================================================================

/// Load environment variables from a `.lenv` file.
///
/// This function reads a `.lenv` configuration file and sets the values
/// as environment variables. If the file doesn't exist, this function
/// returns Ok without setting any variables.
///
/// Note: Existing environment variables are NOT overwritten. This follows
/// the principle that environment variables have higher priority than
/// configuration files.
///
/// # Arguments
///
/// * `file_path` - Path to the `.lenv` file
///
/// # Examples
///
/// ```rust,ignore
/// use lino_arguments::load_lenv_file;
///
/// // Load from default .lenv file
/// load_lenv_file(".lenv").ok();
///
/// // Load from custom path
/// load_lenv_file("config/production.lenv")?;
/// ```
pub fn load_lenv_file(file_path: &str) -> Result<usize, ConfigError> {
    let lenv = read_lino_env(file_path)?;
    let mut loaded_count = 0;

    for key in lenv.keys() {
        // Only set if not already present in environment
        if env::var(&key).is_err() {
            if let Some(value) = lenv.get(&key) {
                env::set_var(&key, &value);
                loaded_count += 1;
            }
        }
    }

    Ok(loaded_count)
}

/// Load environment variables from a `.lenv` file, overwriting existing values.
///
/// Unlike `load_lenv_file`, this function will overwrite any existing
/// environment variables with the values from the file.
///
/// # Arguments
///
/// * `file_path` - Path to the `.lenv` file
///
/// # Examples
///
/// ```rust,ignore
/// use lino_arguments::load_lenv_file_override;
///
/// // Force load values, overwriting any existing env vars
/// load_lenv_file_override("config/override.lenv")?;
/// ```
pub fn load_lenv_file_override(file_path: &str) -> Result<usize, ConfigError> {
    let lenv = read_lino_env(file_path)?;
    let mut loaded_count = 0;

    for key in lenv.keys() {
        if let Some(value) = lenv.get(&key) {
            env::set_var(&key, &value);
            loaded_count += 1;
        }
    }

    Ok(loaded_count)
}

// ============================================================================
// .env File Loading (standard dotenv format, for compatibility)
// ============================================================================

/// Load environment variables from a `.env` file (standard `KEY=VALUE` format).
///
/// Uses the [dotenvy](https://docs.rs/dotenvy) crate under the hood.
/// Existing environment variables are NOT overwritten.
///
/// # Arguments
///
/// * `file_path` - Path to the `.env` file
///
/// # Examples
///
/// ```rust,ignore
/// use lino_arguments::load_env_file;
///
/// // Load from default .env file
/// load_env_file(".env").ok();
/// ```
pub fn load_env_file(file_path: &str) -> Result<usize, ConfigError> {
    let path = std::path::Path::new(file_path);
    if !path.exists() {
        return Ok(0);
    }

    let iter = dotenvy::from_path_iter(path)
        .map_err(|e| ConfigError::FileError(format!("Failed to read {}: {}", file_path, e)))?;

    let mut loaded_count = 0;
    for item in iter {
        match item {
            Ok((key, value)) => {
                // Only set if not already present in environment
                if env::var(&key).is_err() {
                    env::set_var(&key, &value);
                    loaded_count += 1;
                }
            }
            Err(_) => continue,
        }
    }

    Ok(loaded_count)
}

/// Load environment variables from a `.env` file, overwriting existing values.
///
/// # Arguments
///
/// * `file_path` - Path to the `.env` file
pub fn load_env_file_override(file_path: &str) -> Result<usize, ConfigError> {
    let path = std::path::Path::new(file_path);
    if !path.exists() {
        return Ok(0);
    }

    let iter = dotenvy::from_path_iter(path)
        .map_err(|e| ConfigError::FileError(format!("Failed to read {}: {}", file_path, e)))?;

    let mut loaded_count = 0;
    for item in iter {
        match item {
            Ok((key, value)) => {
                env::set_var(&key, &value);
                loaded_count += 1;
            }
            Err(_) => continue,
        }
    }

    Ok(loaded_count)
}

// ============================================================================
// Case Conversion Utilities
// ============================================================================

/// Convert string to UPPER_CASE (for environment variables)
///
/// # Examples
///
/// ```
/// use lino_arguments::to_upper_case;
///
/// assert_eq!(to_upper_case("apiKey"), "API_KEY");
/// assert_eq!(to_upper_case("my-variable-name"), "MY_VARIABLE_NAME");
/// ```
pub fn to_upper_case(s: &str) -> String {
    // If already all uppercase, just replace separators
    if s.chars().all(|c| c.is_uppercase() || c == '_' || c == '-') {
        return s.replace('-', "_");
    }

    let mut result = String::new();
    let chars: Vec<char> = s.chars().collect();

    for (i, c) in chars.iter().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('_');
        }
        if *c == '-' || *c == ' ' {
            result.push('_');
        } else {
            result.push(c.to_ascii_uppercase());
        }
    }

    // Remove leading underscore and double underscores
    result = result.trim_start_matches('_').to_string();
    while result.contains("__") {
        result = result.replace("__", "_");
    }

    result
}

/// Convert string to camelCase (for config object keys)
///
/// # Examples
///
/// ```
/// use lino_arguments::to_camel_case;
///
/// assert_eq!(to_camel_case("api-key"), "apiKey");
/// assert_eq!(to_camel_case("API_KEY"), "apiKey");
/// ```
pub fn to_camel_case(s: &str) -> String {
    let lower = s.to_lowercase();
    let mut result = String::new();
    let mut capitalize_next = false;

    for c in lower.chars() {
        if c == '-' || c == '_' || c == ' ' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    // Ensure first character is lowercase
    if let Some(first) = result.chars().next() {
        if first.is_uppercase() {
            result = first.to_lowercase().to_string() + &result[1..];
        }
    }

    result
}

/// Convert string to kebab-case (for CLI options)
///
/// # Examples
///
/// ```
/// use lino_arguments::to_kebab_case;
///
/// assert_eq!(to_kebab_case("apiKey"), "api-key");
/// assert_eq!(to_kebab_case("API_KEY"), "api-key");
/// ```
pub fn to_kebab_case(s: &str) -> String {
    // If already all uppercase with underscores, convert directly
    if s.chars().all(|c| c.is_uppercase() || c == '_') && s.contains('_') {
        return s.replace('_', "-").to_lowercase();
    }

    let mut result = String::new();
    let chars: Vec<char> = s.chars().collect();

    for (i, c) in chars.iter().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('-');
        }
        if *c == '_' || *c == ' ' {
            result.push('-');
        } else {
            result.push(c.to_ascii_lowercase());
        }
    }

    // Remove leading dash and double dashes
    result = result.trim_start_matches('-').to_string();
    while result.contains("--") {
        result = result.replace("--", "-");
    }

    result
}

/// Convert string to snake_case
///
/// # Examples
///
/// ```
/// use lino_arguments::to_snake_case;
///
/// assert_eq!(to_snake_case("apiKey"), "api_key");
/// assert_eq!(to_snake_case("API_KEY"), "api_key");
/// ```
pub fn to_snake_case(s: &str) -> String {
    // If already all uppercase with underscores, just lowercase
    if s.chars().all(|c| c.is_uppercase() || c == '_') && s.contains('_') {
        return s.to_lowercase();
    }

    let mut result = String::new();
    let chars: Vec<char> = s.chars().collect();

    for (i, c) in chars.iter().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('_');
        }
        if *c == '-' || *c == ' ' {
            result.push('_');
        } else {
            result.push(c.to_ascii_lowercase());
        }
    }

    // Remove leading underscore and double underscores
    result = result.trim_start_matches('_').to_string();
    while result.contains("__") {
        result = result.replace("__", "_");
    }

    result
}

/// Convert string to PascalCase
///
/// # Examples
///
/// ```
/// use lino_arguments::to_pascal_case;
///
/// assert_eq!(to_pascal_case("api-key"), "ApiKey");
/// assert_eq!(to_pascal_case("api_key"), "ApiKey");
/// ```
pub fn to_pascal_case(s: &str) -> String {
    let lower = s.to_lowercase();
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in lower.chars() {
        if c == '-' || c == '_' || c == ' ' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    result
}

// ============================================================================
// Environment Variable Helper
// ============================================================================

/// Get environment variable with default value and case conversion.
/// Tries multiple case formats to find the variable.
///
/// # Examples
///
/// ```
/// use lino_arguments::getenv;
///
/// // Try to get API_KEY, apiKey, api-key, etc.
/// let api_key = getenv("apiKey", "default-key");
/// let port = getenv("PORT", "3000");
/// ```
pub fn getenv(key: &str, default: &str) -> String {
    // Try different case formats
    let variants = [
        key.to_string(),
        to_upper_case(key),
        to_camel_case(key),
        to_kebab_case(key),
        to_snake_case(key),
        to_pascal_case(key),
    ];

    for variant in variants.iter() {
        if let Ok(value) = env::var(variant) {
            return value;
        }
    }

    default.to_string()
}

/// Get environment variable as integer with default value.
/// Tries multiple case formats to find the variable.
///
/// # Examples
///
/// ```
/// use lino_arguments::getenv_int;
///
/// let port = getenv_int("PORT", 3000);
/// ```
pub fn getenv_int(key: &str, default: i64) -> i64 {
    let value = getenv(key, "");
    if value.is_empty() {
        return default;
    }
    value.parse().unwrap_or(default)
}

/// Get environment variable as boolean with default value.
/// Tries multiple case formats to find the variable.
/// Accepts: "true", "false", "1", "0", "yes", "no" (case-insensitive)
///
/// # Examples
///
/// ```
/// use lino_arguments::getenv_bool;
///
/// let debug = getenv_bool("DEBUG", false);
/// ```
pub fn getenv_bool(key: &str, default: bool) -> bool {
    let value = getenv(key, "");
    if value.is_empty() {
        return default;
    }
    match value.to_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => true,
        "false" | "0" | "no" | "off" => false,
        _ => default,
    }
}

// ============================================================================
// Functional Configuration API (like JavaScript's makeConfig)
// ============================================================================

/// Resolved configuration values from the functional API.
///
/// Contains all parsed configuration values accessible by key name.
/// Values are stored as strings and can be retrieved with type conversion.
#[derive(Debug, Clone)]
pub struct Config {
    values: HashMap<String, String>,
}

impl Config {
    /// Get a configuration value as a string.
    /// Returns empty string if the key is not found.
    pub fn get(&self, key: &str) -> String {
        let camel = to_camel_case(key);
        self.values
            .get(&camel)
            .or_else(|| self.values.get(key))
            .cloned()
            .unwrap_or_default()
    }

    /// Get a configuration value as an integer.
    /// Returns the default if the key is not found or cannot be parsed.
    pub fn get_int(&self, key: &str, default: i64) -> i64 {
        let val = self.get(key);
        if val.is_empty() {
            return default;
        }
        val.parse().unwrap_or(default)
    }

    /// Get a configuration value as a boolean.
    /// Accepts: "true", "false", "1", "0", "yes", "no", "on", "off" (case-insensitive).
    /// Returns false if the key is not found.
    pub fn get_bool(&self, key: &str) -> bool {
        let val = self.get(key);
        matches!(val.to_lowercase().as_str(), "true" | "1" | "yes" | "on")
    }

    /// Check if a configuration key exists.
    pub fn has(&self, key: &str) -> bool {
        let camel = to_camel_case(key);
        self.values.contains_key(&camel) || self.values.contains_key(key)
    }
}

/// Option definition for the functional configuration API.
#[derive(Debug, Clone)]
struct OptionDef {
    name: String,
    description: String,
    default: String,
    is_flag: bool,
    short: Option<char>,
}

/// Builder for functional-style configuration.
///
/// Provides a chainable API for defining configuration options, similar to
/// the JavaScript `makeConfig` API.
///
/// # Example
///
/// ```rust,ignore
/// use lino_arguments::make_config;
///
/// let config = make_config(|c| {
///     c.lenv(".lenv")
///      .option("port", "Server port", "3000")
///      .option_short("api-key", 'k', "API key", "")
///      .flag("verbose", "Enable verbose logging")
/// });
/// ```
pub struct ConfigBuilder {
    options: Vec<OptionDef>,
    lenv_path: Option<String>,
    lenv_override: bool,
    env_path: Option<String>,
    env_override: bool,
    app_name: Option<String>,
    app_about: Option<String>,
    app_version: Option<String>,
}

impl ConfigBuilder {
    fn new() -> Self {
        ConfigBuilder {
            options: Vec::new(),
            lenv_path: None,
            lenv_override: false,
            env_path: None,
            env_override: false,
            app_name: None,
            app_about: None,
            app_version: None,
        }
    }

    /// Set the application name for help text.
    pub fn name(&mut self, name: &str) -> &mut Self {
        self.app_name = Some(name.to_string());
        self
    }

    /// Set the application description for help text.
    pub fn about(&mut self, about: &str) -> &mut Self {
        self.app_about = Some(about.to_string());
        self
    }

    /// Set the application version for --version flag.
    pub fn version(&mut self, version: &str) -> &mut Self {
        self.app_version = Some(version.to_string());
        self
    }

    /// Load a .lenv configuration file (without overriding existing env vars).
    pub fn lenv(&mut self, path: &str) -> &mut Self {
        self.lenv_path = Some(path.to_string());
        self.lenv_override = false;
        self
    }

    /// Load a .lenv configuration file, overriding existing env vars.
    pub fn lenv_override(&mut self, path: &str) -> &mut Self {
        self.lenv_path = Some(path.to_string());
        self.lenv_override = true;
        self
    }

    /// Load a .env configuration file (without overriding existing env vars).
    pub fn env(&mut self, path: &str) -> &mut Self {
        self.env_path = Some(path.to_string());
        self.env_override = false;
        self
    }

    /// Load a .env configuration file, overriding existing env vars.
    pub fn env_override(&mut self, path: &str) -> &mut Self {
        self.env_path = Some(path.to_string());
        self.env_override = true;
        self
    }

    /// Define a string/number option with a long name, description, and default value.
    pub fn option(&mut self, name: &str, description: &str, default: &str) -> &mut Self {
        self.options.push(OptionDef {
            name: name.to_string(),
            description: description.to_string(),
            default: default.to_string(),
            is_flag: false,
            short: None,
        });
        self
    }

    /// Define a string/number option with both short and long names.
    pub fn option_short(
        &mut self,
        name: &str,
        short: char,
        description: &str,
        default: &str,
    ) -> &mut Self {
        self.options.push(OptionDef {
            name: name.to_string(),
            description: description.to_string(),
            default: default.to_string(),
            is_flag: false,
            short: Some(short),
        });
        self
    }

    /// Define a boolean flag (defaults to false).
    pub fn flag(&mut self, name: &str, description: &str) -> &mut Self {
        self.options.push(OptionDef {
            name: name.to_string(),
            description: description.to_string(),
            default: String::new(),
            is_flag: true,
            short: None,
        });
        self
    }

    /// Define a boolean flag with a short name.
    pub fn flag_short(&mut self, name: &str, short: char, description: &str) -> &mut Self {
        self.options.push(OptionDef {
            name: name.to_string(),
            description: description.to_string(),
            default: String::new(),
            is_flag: true,
            short: Some(short),
        });
        self
    }

    /// Build the configuration from the defined options.
    ///
    /// This parses CLI arguments using clap and resolves values from:
    /// 1. CLI arguments (highest priority)
    /// 2. Environment variables
    /// 3. .lenv file
    /// 4. .env file
    /// 5. Default values (lowest priority)
    fn build(&self) -> Config {
        self.build_from(env::args_os().collect())
    }

    /// Build the configuration from custom arguments (for testing).
    fn build_from(&self, args: Vec<std::ffi::OsString>) -> Config {
        // Step 1: Load .lenv file if configured (higher priority than .env)
        if let Some(ref path) = self.lenv_path {
            if self.lenv_override {
                let _ = load_lenv_file_override(path);
            } else {
                let _ = load_lenv_file(path);
            }
        }

        // Step 2: Load .env file if configured (lower priority than .lenv)
        if let Some(ref path) = self.env_path {
            if self.env_override {
                let _ = load_env_file_override(path);
            } else {
                let _ = load_env_file(path);
            }
        }

        // Step 3: Build clap command dynamically
        let mut cmd =
            clap::Command::new(self.app_name.clone().unwrap_or_else(|| "app".to_string()));

        if let Some(ref about) = self.app_about {
            cmd = cmd.about(about.clone());
        }

        if let Some(ref version) = self.app_version {
            cmd = cmd.version(version.clone());
        }

        // Add --configuration option for dynamic .lenv loading
        cmd = cmd.arg(
            clap::Arg::new("configuration")
                .long("configuration")
                .short('c')
                .help("Path to configuration .lenv file")
                .value_name("PATH"),
        );

        // Add user-defined options
        for opt in &self.options {
            let kebab_name = to_kebab_case(&opt.name);
            let env_name = to_upper_case(&opt.name);

            let mut arg = clap::Arg::new(kebab_name.clone()).long(kebab_name.clone());

            // Set help text
            arg = arg.help(opt.description.clone());

            if let Some(short) = opt.short {
                arg = arg.short(short);
            }

            if opt.is_flag {
                arg = arg.action(clap::ArgAction::SetTrue);
            } else {
                // Use clap's env feature so it picks up values from env vars
                // (which now include .lenv and .env values we loaded above)
                arg = arg.env(env_name);
                if !opt.default.is_empty() {
                    arg = arg.default_value(opt.default.clone());
                }
            }

            cmd = cmd.arg(arg);
        }

        // Step 4: Parse arguments
        let matches = cmd.get_matches_from(args);

        // Step 5: Load --configuration file if provided
        if let Some(config_path) = matches.get_one::<String>("configuration") {
            let _ = load_lenv_file_override(config_path);
        }

        // Step 6: Collect values into Config
        let mut values = HashMap::new();

        for opt in &self.options {
            let kebab_name = to_kebab_case(&opt.name);
            let camel_name = to_camel_case(&opt.name);

            if opt.is_flag {
                let val = matches.get_flag(&kebab_name);
                values.insert(camel_name, val.to_string());
            } else if let Some(val) = matches.get_one::<String>(&kebab_name) {
                values.insert(camel_name, val.clone());
            }
        }

        Config { values }
    }
}

/// Create a unified configuration using a functional builder API.
///
/// This is the Rust equivalent of the JavaScript `makeConfig` function.
/// It combines .lenv file loading, .env file loading, environment variables,
/// and CLI argument parsing into a single configuration step.
///
/// Priority (highest to lowest):
/// 1. CLI arguments
/// 2. Environment variables
/// 3. .lenv file (via `--configuration` flag or builder `.lenv()`)
/// 4. .env file (via builder `.env()`)
/// 5. Default values
///
/// # Example
///
/// ```rust,ignore
/// use lino_arguments::make_config;
///
/// let config = make_config(|c| {
///     c.lenv(".lenv")
///      .env(".env")
///      .option("port", "Server port", "3000")
///      .option_short("api-key", 'k', "API key", "")
///      .flag("verbose", "Enable verbose logging")
/// });
///
/// let port: u16 = config.get("port").parse().unwrap();
/// let api_key = config.get("api-key");
/// let verbose = config.get_bool("verbose");
/// ```
pub fn make_config<F>(configure: F) -> Config
where
    F: FnOnce(&mut ConfigBuilder) -> &mut ConfigBuilder,
{
    let mut builder = ConfigBuilder::new();
    configure(&mut builder);
    builder.build()
}

/// Create a unified configuration using a functional builder API with custom arguments.
///
/// Same as `make_config` but accepts custom arguments for testing purposes.
///
/// # Example
///
/// ```rust,ignore
/// use lino_arguments::make_config_from;
///
/// let args = vec!["my-app", "--port", "9090", "--verbose"];
/// let config = make_config_from(args, |c| {
///     c.option("port", "Server port", "3000")
///      .flag("verbose", "Enable verbose logging")
/// });
///
/// assert_eq!(config.get("port"), "9090");
/// assert!(config.get_bool("verbose"));
/// ```
pub fn make_config_from<I, T, F>(args: I, configure: F) -> Config
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString>,
    F: FnOnce(&mut ConfigBuilder) -> &mut ConfigBuilder,
{
    let mut builder = ConfigBuilder::new();
    configure(&mut builder);
    builder.build_from(args.into_iter().map(|a| a.into()).collect())
}

// ============================================================================
// Tests
// ============================================================================

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

    mod case_conversion {
        use super::*;

        #[test]
        fn test_to_upper_case() {
            assert_eq!(to_upper_case("apiKey"), "API_KEY");
            assert_eq!(to_upper_case("myVariableName"), "MY_VARIABLE_NAME");
            assert_eq!(to_upper_case("api-key"), "API_KEY");
            assert_eq!(to_upper_case("API_KEY"), "API_KEY");
        }

        #[test]
        fn test_to_camel_case() {
            assert_eq!(to_camel_case("api-key"), "apiKey");
            assert_eq!(to_camel_case("API_KEY"), "apiKey");
            assert_eq!(to_camel_case("my_variable_name"), "myVariableName");
        }

        #[test]
        fn test_to_kebab_case() {
            assert_eq!(to_kebab_case("apiKey"), "api-key");
            assert_eq!(to_kebab_case("API_KEY"), "api-key");
            assert_eq!(to_kebab_case("MyVariableName"), "my-variable-name");
        }

        #[test]
        fn test_to_snake_case() {
            assert_eq!(to_snake_case("apiKey"), "api_key");
            assert_eq!(to_snake_case("api-key"), "api_key");
            assert_eq!(to_snake_case("API_KEY"), "api_key");
        }

        #[test]
        fn test_to_pascal_case() {
            assert_eq!(to_pascal_case("api-key"), "ApiKey");
            assert_eq!(to_pascal_case("api_key"), "ApiKey");
            assert_eq!(to_pascal_case("my-variable-name"), "MyVariableName");
        }
    }

    mod getenv_tests {
        use super::*;
        use std::env;

        #[test]
        fn test_getenv_with_default() {
            let result = getenv("NON_EXISTENT_VAR_12345", "default");
            assert_eq!(result, "default");
        }

        #[test]
        fn test_getenv_finds_var() {
            env::set_var("TEST_LINO_VAR", "test_value");
            let result = getenv("TEST_LINO_VAR", "default");
            assert_eq!(result, "test_value");
            env::remove_var("TEST_LINO_VAR");
        }

        #[test]
        fn test_getenv_int() {
            env::set_var("TEST_PORT", "8080");
            let result = getenv_int("TEST_PORT", 3000);
            assert_eq!(result, 8080);
            env::remove_var("TEST_PORT");
        }

        #[test]
        fn test_getenv_bool() {
            env::set_var("TEST_DEBUG", "true");
            let result = getenv_bool("TEST_DEBUG", false);
            assert!(result);
            env::remove_var("TEST_DEBUG");

            env::set_var("TEST_DEBUG", "1");
            let result = getenv_bool("TEST_DEBUG", false);
            assert!(result);
            env::remove_var("TEST_DEBUG");
        }
    }
}