gregg 1.0.7

Compact keyboard-first terminal monitor that polls greggd endpoints and renders each system in a compact five-row base block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
//! CLI argument parsing and subcommand dispatch for `gregg`.
//!
//! Uses `clap` derive macros for structured argument parsing. Each
//! subcommand has a stable help message and returns a meaningful exit code.

use std::fmt;
use std::path::PathBuf;

use clap::{Parser, Subcommand};

use crate::config::{
    Config, ConfigError, ConfigStore, EggpoolEntry, EggpoolScheme, MAX_EGGPOOL_NAME_LEN,
    MAX_ENV_NAME_LEN,
};
use crate::eggpool_endpoint::{EggpoolEndpointError, EggpoolEndpointSpec};
use crate::endpoint::{EndpointError, EndpointSpec};

/// Compact keyboard-first terminal monitor for multiple remote systems.
#[derive(Parser)]
#[command(
    name = "gregg",
    version,
    about = "Compact terminal monitor for remote system metrics",
    long_about = "gregg polls configured greggd endpoints and renders each system \
                  in a compact five-row base block. Without a subcommand, it starts the TUI. \
                  Subcommands manage the persistent endpoint configuration."
)]
pub struct Cli {
    /// Path to the configuration file.
    #[arg(
        long,
        short = 'c',
        global = true,
        help = "Path to the TOML configuration file",
        value_name = "PATH"
    )]
    pub config: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Option<Command>,
}

/// Available subcommands.
#[derive(Subcommand)]
pub enum Command {
    /// Print the client version.
    Version,
    /// Add a monitored endpoint.
    ///
    /// Parses the endpoint, assigns a stable UUID, and appends it to the
    /// configuration. Exact duplicates are rejected unless `--replace` is set.
    ///
    /// # Examples
    ///
    /// ```text
    /// gregg add 192.168.1.8
    /// gregg add macmini.local:11310 --name "Mac Mini"
    /// gregg add 10.0.0.5:8080 --replace
    /// ```
    Add {
        /// Endpoint in host:port or HTTP URL form (default port 11310).
        endpoint: String,
        /// Optional display name for this endpoint.
        #[arg(long)]
        name: Option<String>,
        /// Replace an existing endpoint with the same host:port.
        #[arg(long)]
        replace: bool,
    },
    /// List all configured endpoints.
    ///
    /// Prints one endpoint per line in stable insertion order. With `--json`,
    /// emits a machine-readable JSON array.
    ///
    /// # Examples
    ///
    /// ```text
    /// gregg list
    /// gregg list --json
    /// ```
    List {
        /// Output in JSON format.
        #[arg(long)]
        json: bool,
    },
    /// Remove one or more monitored endpoints.
    ///
    /// Use host only to remove all entries for that host (regardless of port),
    /// or host:port to remove a specific endpoint.
    ///
    /// # Examples
    ///
    /// ```text
    /// gregg remove 192.168.1.8
    /// gregg remove 10.0.0.5:8080
    /// ```
    Remove {
        /// Endpoint to remove. Use host only to remove all entries for that host,
        /// or host:port to remove a specific endpoint.
        endpoint: String,
    },
    /// Set the global polling interval in seconds.
    ///
    /// Persists the interval to the configuration file. Does not trigger an
    /// immediate poll. Valid range is 1..=3600.
    ///
    /// # Examples
    ///
    /// ```text
    /// gregg refresh 5
    /// gregg refresh 30
    /// ```
    Refresh {
        /// Refresh interval in seconds (1-3600).
        seconds: u64,
    },
    /// Open the configuration file in an editor.
    ///
    /// Resolves the editor from `$VISUAL`, `$EDITOR`, then fallbacks.
    /// On Unix: `hx`, `vim`, `vi`. On Windows: `hx`, `code`, `notepad`.
    /// Validates the file after the editor exits.
    ///
    /// # Examples
    ///
    /// ```text
    /// gregg edit
    /// gregg --config /tmp/test.toml edit
    /// ```
    Edit,
    /// Manage the optional `EggPool` statistics endpoint.
    Eggpool {
        #[command(subcommand)]
        command: EggpoolCommand,
    },
}

/// `EggPool` configuration commands.
#[derive(Subcommand)]
pub enum EggpoolCommand {
    /// Add the one supported `EggPool` endpoint (default port 11300).
    Add {
        /// `EggPool` host, host:port, \[IPv6\]:port, or bare IPv6.
        endpoint: String,
        /// Optional display name (maximum 128 bytes).
        #[arg(long)]
        name: Option<String>,
        /// Use HTTPS instead of HTTP.
        #[arg(long)]
        https: bool,
        /// Environment-variable name containing the API key; only the name is stored.
        #[arg(long)]
        api_key_env: Option<String>,
        /// Replace the current `EggPool` entry.
        #[arg(long)]
        replace: bool,
    },
    /// List the configured `EggPool` endpoint, if present.
    List {
        /// Output a JSON array.
        #[arg(long)]
        json: bool,
    },
    /// Remove the configured `EggPool` endpoint.
    Remove {
        /// `EggPool` host or host:port. Host-only matching ignores the port.
        endpoint: String,
    },
}

/// Exit codes returned by gregg commands.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub enum ExitCode {
    Success = 0,
    /// Configuration error (invalid, missing, or unwritable).
    ConfigError = 1,
    /// Endpoint parse or validation error.
    EndpointError = 2,
    /// The requested operation could not be completed.
    OperationError = 3,
    /// The config file was not found.
    NotFound = 4,
    /// Editor could not be launched.
    EditorError = 5,
}

impl From<&ConfigError> for ExitCode {
    fn from(e: &ConfigError) -> Self {
        match e {
            ConfigError::Io { source, .. } if source.kind() == std::io::ErrorKind::NotFound => {
                Self::NotFound
            }
            ConfigError::Io { .. }
            | ConfigError::Parse { .. }
            | ConfigError::Validation(_)
            | ConfigError::AtomicWrite { .. } => Self::ConfigError,
            ConfigError::LockPoisoned | ConfigError::LockTimeout { .. } => Self::OperationError,
            ConfigError::EditorFailed { .. } => Self::EditorError,
        }
    }
}

impl From<&EndpointError> for ExitCode {
    fn from(_: &EndpointError) -> Self {
        Self::EndpointError
    }
}

impl From<&EggpoolEndpointError> for ExitCode {
    fn from(_: &EggpoolEndpointError) -> Self {
        Self::EndpointError
    }
}

/// Resolve the config path: explicit `--config` or platform default.
#[must_use]
pub fn resolve_config_path(explicit: Option<&PathBuf>) -> PathBuf {
    explicit.cloned().unwrap_or_else(Config::default_path)
}

/// Dispatch a subcommand.
///
/// # Errors
///
/// Returns a boxed error if the command fails.
pub fn dispatch(command: &Command, store: &ConfigStore) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        Command::Version => {
            println!("{}", version_string());
            Ok(())
        }
        Command::Add {
            endpoint,
            name,
            replace,
        } => cmd_add(store, endpoint, name.as_deref(), *replace),
        Command::List { json } => cmd_list(store, *json),
        Command::Remove { endpoint } => cmd_remove(store, endpoint),
        Command::Refresh { seconds } => cmd_refresh(store, *seconds),
        Command::Edit => cmd_edit(store),
        Command::Eggpool { command } => dispatch_eggpool(command, store),
    }
}

/// Return the compile-time version rendered for the client binary.
#[must_use]
pub fn version_string() -> String {
    format!("gregg {}", env!("CARGO_PKG_VERSION"))
}

fn dispatch_eggpool(
    command: &EggpoolCommand,
    store: &ConfigStore,
) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        EggpoolCommand::Add {
            endpoint,
            name,
            https,
            api_key_env,
            replace,
        } => cmd_eggpool_add(
            store,
            endpoint,
            name.as_deref(),
            *https,
            api_key_env.as_deref(),
            *replace,
        ),
        EggpoolCommand::List { json } => cmd_eggpool_list(store, *json),
        EggpoolCommand::Remove { endpoint } => cmd_eggpool_remove(store, endpoint),
    }
}

fn cmd_eggpool_add(
    store: &ConfigStore,
    endpoint_str: &str,
    name: Option<&str>,
    https: bool,
    api_key_env: Option<&str>,
    replace: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let spec = EggpoolEndpointSpec::parse(endpoint_str)?;
    if let Some(name) = name {
        validate_eggpool_name(name)?;
    }
    if let Some(value) = api_key_env {
        validate_eggpool_env(value)?;
    }
    let entry = EggpoolEntry {
        id: uuid::Uuid::new_v4().to_string(),
        host: spec.host,
        port: spec.port,
        scheme: if https {
            EggpoolScheme::Https
        } else {
            EggpoolScheme::Http
        },
        name: name.map(str::to_owned),
        api_key_env: api_key_env.map(str::to_owned),
    };
    store.mutate(|config| {
        if config.eggpool.is_some() && !replace {
            return Err(ConfigError::Validation(vec![
                crate::config::ConfigViolation::InvalidEggpoolName {
                    reason: "an EggPool endpoint is already configured; use --replace".to_string(),
                },
            ]));
        }
        config.eggpool = Some(entry);
        Ok(())
    })?;
    eprintln!("added EggPool endpoint");
    Ok(())
}

fn cmd_eggpool_list(store: &ConfigStore, json: bool) -> Result<(), Box<dyn std::error::Error>> {
    let config = store.load_or_default()?;
    if json {
        let entries = config.eggpool.into_iter().collect::<Vec<_>>();
        println!("{}", serde_json::to_string_pretty(&entries)?);
    } else if let Some(entry) = config.eggpool {
        let label = entry.name.as_deref().unwrap_or("EggPool");
        let auth = entry
            .api_key_env
            .as_deref()
            .map_or(String::new(), |env| format!("  auth-env={env}"));
        println!("{label}  {}{auth}", entry.display_address());
    }
    Ok(())
}

fn cmd_eggpool_remove(
    store: &ConfigStore,
    endpoint_str: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let spec = EggpoolEndpointSpec::parse(endpoint_str)?;
    let removed = store.mutate_with_result(|config| {
        let matches = config.eggpool.as_ref().is_some_and(|entry| {
            entry.host == spec.host && (!spec.port_was_explicit || entry.port == spec.port)
        });
        if matches {
            config.eggpool = None;
            Ok(true)
        } else {
            Ok(false)
        }
    })?;
    if removed {
        eprintln!("removed EggPool endpoint");
    } else {
        eprintln!("no matching EggPool endpoint found: {endpoint_str}");
    }
    Ok(())
}

fn validate_eggpool_name(name: &str) -> Result<(), ConfigError> {
    let trimmed = name.trim();
    let reason = if trimmed.is_empty() {
        Some("name is empty".to_string())
    } else if trimmed != name {
        Some("name must not have surrounding whitespace".to_string())
    } else if name.len() > MAX_EGGPOOL_NAME_LEN {
        Some(format!(
            "name exceeds maximum length of {MAX_EGGPOOL_NAME_LEN}"
        ))
    } else {
        None
    };
    reason.map_or(Ok(()), |reason| {
        Err(ConfigError::Validation(vec![
            crate::config::ConfigViolation::InvalidEggpoolName { reason },
        ]))
    })
}

fn validate_eggpool_env(value: &str) -> Result<(), ConfigError> {
    let valid = !value.is_empty()
        && value.len() <= MAX_ENV_NAME_LEN
        && value
            .as_bytes()
            .first()
            .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_');
    if valid {
        Ok(())
    } else {
        Err(ConfigError::Validation(vec![
            crate::config::ConfigViolation::InvalidEggpoolApiKeyEnv {
                value: value.to_string(),
                reason: "name must match [A-Za-z_][A-Za-z0-9_]* and be at most 128 bytes"
                    .to_string(),
            },
        ]))
    }
}

fn cmd_add(
    store: &ConfigStore,
    endpoint_str: &str,
    name: Option<&str>,
    replace: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    // Validate name early.
    if let Some(n) = name {
        crate::endpoint::validate_name(n)?;
    }

    let spec = EndpointSpec::parse_add_input(endpoint_str)?;

    let result = store.mutate_with_result(|config| {
        let resolved_port = if spec.port_was_explicit {
            spec.port
        } else {
            config.default_port
        };

        // Check for exact duplicate using the resolved port.
        let existing_idx = config
            .systems
            .iter()
            .position(|s| s.host == spec.host && s.port == resolved_port);

        if let Some(idx) = existing_idx {
            if replace {
                config.systems.remove(idx);
            } else {
                return Err(ConfigError::Validation(vec![
                    crate::config::ConfigViolation::DuplicateAddress {
                        address: crate::endpoint::display_address(&spec.host, resolved_port),
                    },
                ]));
            }
        }

        let entry = crate::config::SystemEntry {
            id: uuid::Uuid::new_v4().to_string(),
            host: spec.host.clone(),
            port: resolved_port,
            name: name.map(std::string::ToString::to_string),
        };
        config.systems.push(entry);

        Ok(())
    });

    match result {
        Ok(()) => {
            eprintln!("added endpoint {endpoint_str}");
            Ok(())
        }
        Err(e) => Err(Box::new(e)),
    }
}

fn cmd_list(store: &ConfigStore, json: bool) -> Result<(), Box<dyn std::error::Error>> {
    let config = store.load_or_default()?;

    if json {
        let output =
            serde_json::to_string_pretty(&config.systems).expect("systems serializes to JSON");
        println!("{output}");
    } else {
        if config.systems.is_empty() {
            // Print nothing for empty list.
            return Ok(());
        }
        for system in &config.systems {
            let ep = system.to_endpoint();
            println!("{ep}");
        }
    }

    Ok(())
}

fn cmd_remove(store: &ConfigStore, endpoint_str: &str) -> Result<(), Box<dyn std::error::Error>> {
    let spec = EndpointSpec::parse(endpoint_str)?;
    let exact_port = if spec.port_was_explicit {
        Some(spec.port)
    } else {
        None // Host-only removal
    };

    let result = store.mutate_with_result(|config| {
        let original_len = config.systems.len();

        if let Some(port) = exact_port {
            // Exact endpoint removal.
            config
                .systems
                .retain(|s| !(s.host == spec.host && s.port == port));
        } else {
            // Host-wide removal.
            config.systems.retain(|s| s.host != spec.host);
        }

        let removed = original_len - config.systems.len();
        Ok(removed)
    });

    match result {
        Ok(removed) => {
            if removed == 0 {
                eprintln!("no matching endpoint found: {endpoint_str}");
            } else {
                eprintln!("removed {removed} endpoint(s)");
            }
            Ok(())
        }
        Err(e) => Err(Box::new(e)),
    }
}

fn cmd_refresh(store: &ConfigStore, seconds: u64) -> Result<(), Box<dyn std::error::Error>> {
    store.mutate(|config| {
        config.refresh_seconds = seconds;
        Ok(())
    })?;
    eprintln!("refresh interval set to {seconds}s");
    Ok(())
}

fn cmd_edit(store: &ConfigStore) -> Result<(), Box<dyn std::error::Error>> {
    store.edit_transaction(|path| {
        // Resolve editor.
        let editor = resolve_editor().ok_or_else(|| ConfigError::EditorFailed {
            path: path.to_path_buf(),
            message: "no editor found; set $VISUAL or $EDITOR".to_string(),
        })?;

        // Launch editor on the temporary file (never the live file).
        let status = std::process::Command::new(&editor)
            .arg(path)
            .status()
            .map_err(|e| ConfigError::EditorFailed {
                path: path.to_path_buf(),
                message: format!("failed to launch editor: {e}"),
            })?;

        if !status.success() {
            return Err(ConfigError::EditorFailed {
                path: path.to_path_buf(),
                message: format!("editor exited with status: {status}"),
            });
        }

        Ok(())
    })?;

    eprintln!("configuration validated successfully");
    Ok(())
}

/// Resolve the editor to use, checking $VISUAL, $EDITOR, then fallbacks.
///
/// On Unix, fallbacks are `hx`, `vim`, `vi` found via `PATH`.
/// On Windows, fallbacks are `hx`, `code`, `notepad` found via `PATH`
/// and `PATHEXT` extension resolution.
#[must_use]
pub fn resolve_editor() -> Option<String> {
    if let Ok(visual) = std::env::var("VISUAL") {
        let trimmed = visual.trim().to_string();
        if !trimmed.is_empty() {
            return Some(trimmed);
        }
    }
    if let Ok(editor) = std::env::var("EDITOR") {
        let trimmed = editor.trim().to_string();
        if !trimmed.is_empty() {
            return Some(trimmed);
        }
    }
    // Check fallbacks.
    #[cfg(windows)]
    {
        for fallback in &["hx", "code", "notepad"] {
            if executable_exists(fallback) {
                return Some((*fallback).to_string());
            }
        }
    }
    #[cfg(not(windows))]
    {
        for fallback in &["hx", "vim", "vi"] {
            if executable_exists(fallback) {
                return Some((*fallback).to_string());
            }
        }
    }
    None
}

/// Check whether an executable is available in `PATH`.
///
/// On Unix, this uses the `which` command. On Windows, this searches
/// `PATH` entries directly and honours `PATHEXT` for extension resolution.
fn executable_exists(cmd: &str) -> bool {
    #[cfg(windows)]
    {
        executable_exists_windows(cmd)
    }
    #[cfg(not(windows))]
    {
        std::process::Command::new("which")
            .arg(cmd)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    }
}

/// Windows-specific executable lookup using `PATH` and `PATHEXT`.
#[cfg(windows)]
fn executable_exists_windows(cmd: &str) -> bool {
    use std::path::PathBuf;

    // If the command is an absolute path, check it directly.
    if std::path::Path::new(cmd).is_absolute() {
        return std::path::Path::new(cmd).exists();
    }

    let path_ext = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
    let extensions: Vec<String> = path_ext
        .split(';')
        .map(|e| e.trim().to_uppercase())
        .filter(|e| !e.is_empty())
        .collect();

    let Ok(path_var) = std::env::var("PATH") else {
        return false;
    };

    for dir in path_var.split(';') {
        let dir = dir.trim();
        if dir.is_empty() {
            continue;
        }
        let base = PathBuf::from(dir).join(cmd);

        // Check with each PATHEXT extension.
        for ext in &extensions {
            let candidate = format!("{}{}", base.display(), ext);
            if std::path::Path::new(&candidate).exists() {
                return true;
            }
        }
        // Also check the bare name (for commands already containing an extension).
        if base.exists() {
            return true;
        }
    }
    false
}

/// Error type wrapping config and endpoint errors.
#[derive(Debug)]
#[allow(dead_code)]
pub enum ClientError {
    Config(ConfigError),
    Endpoint(EndpointError),
}

impl fmt::Display for ClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Config(e) => write!(f, "{e}"),
            Self::Endpoint(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for ClientError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Config(e) => Some(e),
            Self::Endpoint(e) => Some(e),
        }
    }
}

impl From<ConfigError> for ClientError {
    fn from(e: ConfigError) -> Self {
        Self::Config(e)
    }
}

impl From<EndpointError> for ClientError {
    fn from(e: EndpointError) -> Self {
        Self::Endpoint(e)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use std::fs;

    fn tmp_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("gregg_cli_test_{name}"));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    // --- CLI parsing ---

    #[test]
    fn cli_parses_no_command() {
        let cli = Cli::try_parse_from(["gregg"]).unwrap();
        assert!(cli.command.is_none());
    }

    #[test]
    fn cli_parses_version_without_config() {
        let cli = Cli::try_parse_from(["gregg", "version"]).unwrap();
        assert!(matches!(cli.command, Some(Command::Version)));
        assert_eq!(
            version_string(),
            format!("gregg {}", env!("CARGO_PKG_VERSION"))
        );
    }

    #[test]
    fn cli_parses_add() {
        let cli = Cli::try_parse_from(["gregg", "add", "192.168.1.1"]).unwrap();
        match cli.command.unwrap() {
            Command::Add {
                endpoint,
                name,
                replace,
            } => {
                assert_eq!(endpoint, "192.168.1.1");
                assert!(name.is_none());
                assert!(!replace);
            }
            _ => panic!("expected Add command"),
        }
    }

    #[test]
    fn cli_parses_add_with_name() {
        let cli = Cli::try_parse_from(["gregg", "add", "192.168.1.1", "--name", "Server"]).unwrap();
        match cli.command.unwrap() {
            Command::Add { endpoint, name, .. } => {
                assert_eq!(endpoint, "192.168.1.1");
                assert_eq!(name.as_deref(), Some("Server"));
            }
            _ => panic!("expected Add command"),
        }
    }

    #[test]
    fn cli_parses_add_with_replace() {
        let cli = Cli::try_parse_from(["gregg", "add", "192.168.1.1", "--replace"]).unwrap();
        match cli.command.unwrap() {
            Command::Add { replace, .. } => {
                assert!(replace);
            }
            _ => panic!("expected Add command"),
        }
    }

    #[test]
    fn cli_parses_list() {
        let cli = Cli::try_parse_from(["gregg", "list"]).unwrap();
        assert!(matches!(
            cli.command.unwrap(),
            Command::List { json: false }
        ));
    }

    #[test]
    fn cli_parses_list_json() {
        let cli = Cli::try_parse_from(["gregg", "list", "--json"]).unwrap();
        assert!(matches!(cli.command.unwrap(), Command::List { json: true }));
    }

    #[test]
    fn cli_parses_remove() {
        let cli = Cli::try_parse_from(["gregg", "remove", "192.168.1.1"]).unwrap();
        match cli.command.unwrap() {
            Command::Remove { endpoint } => {
                assert_eq!(endpoint, "192.168.1.1");
            }
            _ => panic!("expected Remove command"),
        }
    }

    #[test]
    fn cli_parses_refresh() {
        let cli = Cli::try_parse_from(["gregg", "refresh", "30"]).unwrap();
        match cli.command.unwrap() {
            Command::Refresh { seconds } => {
                assert_eq!(seconds, 30);
            }
            _ => panic!("expected Refresh command"),
        }
    }

    #[test]
    fn cli_parses_edit() {
        let cli = Cli::try_parse_from(["gregg", "edit"]).unwrap();
        assert!(matches!(cli.command.unwrap(), Command::Edit));
    }

    #[test]
    fn cli_parses_eggpool_add_and_global_config() {
        let cli = Cli::try_parse_from([
            "gregg",
            "--config",
            "/tmp/test.toml",
            "eggpool",
            "add",
            "pool.local",
            "--https",
            "--name",
            "Main",
            "--api-key-env",
            "POOL_KEY",
            "--replace",
        ])
        .unwrap();
        assert_eq!(cli.config, Some(PathBuf::from("/tmp/test.toml")));
        match cli.command.unwrap() {
            Command::Eggpool {
                command:
                    EggpoolCommand::Add {
                        endpoint,
                        name,
                        https,
                        api_key_env,
                        replace,
                    },
            } => {
                assert_eq!(endpoint, "pool.local");
                assert_eq!(name.as_deref(), Some("Main"));
                assert!(https && replace);
                assert_eq!(api_key_env.as_deref(), Some("POOL_KEY"));
            }
            _ => panic!("expected EggPool add command"),
        }
    }

    #[test]
    fn cli_parses_config_flag() {
        let cli = Cli::try_parse_from(["gregg", "--config", "/tmp/test.toml", "list"]).unwrap();
        assert_eq!(cli.config, Some(PathBuf::from("/tmp/test.toml")));
    }

    // --- Add command ---

    #[test]
    fn add_first_endpoint() {
        let dir = tmp_dir("add_first");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 1);
        assert_eq!(config.systems[0].host, "192.168.1.1");
        assert_eq!(config.systems[0].port, 11310);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_named_endpoint() {
        let dir = tmp_dir("add_named");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1:8080", Some("My Server"), false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 1);
        assert_eq!(config.systems[0].host, "192.168.1.1");
        assert_eq!(config.systems[0].port, 8080);
        assert_eq!(config.systems[0].name.as_deref(), Some("My Server"));

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_duplicate_rejects() {
        let dir = tmp_dir("add_dup");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1", None, false).unwrap();
        let result = cmd_add(&store, "192.168.1.1", None, false);
        assert!(result.is_err());

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_replace_overwrites() {
        let dir = tmp_dir("add_replace");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1", Some("Old"), false).unwrap();
        cmd_add(&store, "192.168.1.1", Some("New"), true).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 1);
        assert_eq!(config.systems[0].name.as_deref(), Some("New"));

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_without_explicit_port_uses_default_port() {
        let dir = tmp_dir("add_default_port");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // Add without explicit port — should use default_port.
        cmd_add(&store, "192.168.1.1", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].port, 11310);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_http_url_persists_only_canonical_authority() {
        let dir = tmp_dir("add_http_url");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(
            &store,
            "http://192.168.183.143:11310/v2/status",
            None,
            false,
        )
        .unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].host, "192.168.183.143");
        assert_eq!(config.systems[0].port, 11310);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_http_url_without_port_uses_configured_default_and_keeps_explicit_80() {
        let dir = tmp_dir("add_http_ports");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        store
            .mutate(|config| {
                config.default_port = 11320;
                Ok(())
            })
            .unwrap();
        cmd_add(&store, "http://default.example/", None, false).unwrap();
        cmd_add(&store, "http://explicit.example:80/", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].port, 11320);
        assert_eq!(config.systems[1].port, 80);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_with_explicit_port_stores_port() {
        let dir = tmp_dir("add_explicit_port");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1:8080", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].port, 8080);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_with_explicit_default_port_stores_port() {
        let dir = tmp_dir("add_explicit_default");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // Explicitly specifying the default port should still store 11310.
        cmd_add(&store, "192.168.1.1:11310", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].port, 11310);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_portless_with_non_default_port_stores_configured_port() {
        let dir = tmp_dir("add_non_default_port");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // Set a non-default default_port.
        store
            .mutate(|config| {
                config.default_port = 12000;
                Ok(())
            })
            .unwrap();

        // Add without explicit port — should use the configured default_port.
        cmd_add(&store, "192.168.1.1", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].port, 12000);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_explicit_port_overrides_non_default_configured_port() {
        let dir = tmp_dir("add_explicit_override");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // Set a non-default default_port.
        store
            .mutate(|config| {
                config.default_port = 12000;
                Ok(())
            })
            .unwrap();

        // Add with explicit port — should store the explicit port, not the default.
        cmd_add(&store, "192.168.1.1:11310", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].port, 11310);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn duplicate_detection_uses_resolved_port() {
        let dir = tmp_dir("dup_resolved_port");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // Set a non-default default_port.
        store
            .mutate(|config| {
                config.default_port = 12000;
                Ok(())
            })
            .unwrap();

        // Add without explicit port — stores 12000.
        cmd_add(&store, "192.168.1.1", None, false).unwrap();

        // Adding the same host without explicit port should be a duplicate.
        let result = cmd_add(&store, "192.168.1.1", None, false);
        assert!(result.is_err(), "duplicate should be rejected");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn replace_uses_resolved_port() {
        let dir = tmp_dir("replace_resolved_port");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // Set a non-default default_port.
        store
            .mutate(|config| {
                config.default_port = 12000;
                Ok(())
            })
            .unwrap();

        // Add without explicit port — stores 12000.
        cmd_add(&store, "192.168.1.1", None, false).unwrap();

        // Replace with a name — should replace the resolved address.
        cmd_add(&store, "192.168.1.1", Some("Replaced"), true).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 1);
        assert_eq!(config.systems[0].name.as_deref(), Some("Replaced"));
        assert_eq!(config.systems[0].port, 12000);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn remove_without_explicit_port_removes_all_for_host() {
        let dir = tmp_dir("remove_host_all");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1:8080", None, false).unwrap();
        cmd_add(&store, "192.168.1.1:9090", None, false).unwrap();

        // Remove without explicit port — should remove both.
        cmd_remove(&store, "192.168.1.1").unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 0);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn remove_with_explicit_port_removes_only_exact_match() {
        let dir = tmp_dir("remove_exact_port");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1:8080", None, false).unwrap();
        cmd_add(&store, "192.168.1.1:9090", None, false).unwrap();

        // Remove with explicit port — should only remove 8080.
        cmd_remove(&store, "192.168.1.1:8080").unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 1);
        assert_eq!(config.systems[0].port, 9090);

        let _ = fs::remove_dir_all(&dir);
    }

    // --- List command ---

    #[test]
    fn list_empty_config() {
        let dir = tmp_dir("list_empty");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_list(&store, false).unwrap();
        // No output expected.

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn list_with_endpoints() {
        let dir = tmp_dir("list_endpoints");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1", Some("Server"), false).unwrap();
        cmd_add(&store, "10.0.0.1:8080", None, false).unwrap();

        // Just verify it doesn't panic.
        cmd_list(&store, false).unwrap();

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn list_json() {
        let dir = tmp_dir("list_json");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1", None, false).unwrap();

        // Just verify it doesn't panic.
        cmd_list(&store, true).unwrap();

        let _ = fs::remove_dir_all(&dir);
    }

    // --- Remove command ---

    #[test]
    fn remove_exact_endpoint() {
        let dir = tmp_dir("remove_exact");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1:8080", None, false).unwrap();
        cmd_add(&store, "192.168.1.1:9090", None, false).unwrap();

        cmd_remove(&store, "192.168.1.1:8080").unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 1);
        assert_eq!(config.systems[0].port, 9090);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn remove_host_wide() {
        let dir = tmp_dir("remove_host");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1:8080", None, false).unwrap();
        cmd_add(&store, "192.168.1.1:9090", None, false).unwrap();
        cmd_add(&store, "10.0.0.1", None, false).unwrap();

        cmd_remove(&store, "192.168.1.1").unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems.len(), 1);
        assert_eq!(config.systems[0].host, "10.0.0.1");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn remove_nonexistent_is_idempotent() {
        let dir = tmp_dir("remove_none");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // Should succeed (no error, just a warning).
        cmd_remove(&store, "192.168.1.1").unwrap();

        let _ = fs::remove_dir_all(&dir);
    }

    // --- Refresh command ---

    #[test]
    fn refresh_sets_interval() {
        let dir = tmp_dir("refresh");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_refresh(&store, 30).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.refresh_seconds, 30);

        let _ = fs::remove_dir_all(&dir);
    }

    // --- Config path resolution ---

    #[test]
    fn resolve_config_path_explicit() {
        let explicit = PathBuf::from("/custom/path.toml");
        let resolved = resolve_config_path(Some(&explicit));
        assert_eq!(resolved, explicit);
    }

    #[test]
    fn resolve_config_path_default() {
        let resolved = resolve_config_path(None);
        assert_eq!(resolved, Config::default_path());
    }

    // --- Editor resolution ---

    #[test]
    fn resolve_editor_returns_something() {
        // On most systems, at least 'vi' should be available.
        // We just verify the function doesn't panic.
        let _ = resolve_editor();
    }

    // --- Endpoint ordering preserved ---

    #[test]
    fn add_preserves_order() {
        let dir = tmp_dir("order");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1", None, false).unwrap();
        cmd_add(&store, "10.0.0.1", None, false).unwrap();
        cmd_add(&store, "172.16.0.1", None, false).unwrap();

        let config = store.load_existing().unwrap();
        assert_eq!(config.systems[0].host, "192.168.1.1");
        assert_eq!(config.systems[1].host, "10.0.0.1");
        assert_eq!(config.systems[2].host, "172.16.0.1");

        let _ = fs::remove_dir_all(&dir);
    }

    // --- IDs are stable ---

    #[test]
    fn endpoint_ids_are_stable() {
        let dir = tmp_dir("ids");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        cmd_add(&store, "192.168.1.1", None, false).unwrap();

        let config1 = store.load_existing().unwrap();
        let id1 = config1.systems[0].id.clone();

        // Reload and verify ID is stable.
        let config2 = store.load_existing().unwrap();
        assert_eq!(config2.systems[0].id, id1);

        let _ = fs::remove_dir_all(&dir);
    }

    // --- Non-TUI commands never initialize terminal ---

    #[test]
    fn subcommands_dont_panic() {
        let dir = tmp_dir("no_panic");
        let path = dir.join("config.toml");
        let store = ConfigStore::new(path);

        // These should all complete without error.
        cmd_add(&store, "192.168.1.1", None, false).unwrap();
        cmd_list(&store, false).unwrap();
        cmd_list(&store, true).unwrap();
        cmd_refresh(&store, 10).unwrap();

        let _ = fs::remove_dir_all(&dir);
    }
}