domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
//! CLI parsing and command execution.
//!
//! CLI definition lives in the `domain_status_cli` crate (single source of truth
//! for build.rs completions and man page). We parse with that crate and convert to
//! [`Config`] and export types as needed.

use std::io;

use anyhow::{Context, Result};
use clap_complete::Shell;
use clap_mangen::Man;
use indicatif::{ProgressBar, ProgressStyle};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use clap::parser::ValueSource;
use clap::{FromArgMatches, Parser};
use domain_status_cli::ExportFormat as CliExportFormat;

use crate::config::{log_level_filter, FailOn, FileConfig, LogFormat, LogLevel};
use crate::export::{export_csv, ExportOptions};
use crate::initialization::{init_crypto_provider, init_logger_to_file, init_logger_with};
use crate::summary::{format_scan_summary, query_scan_summary, SummaryOptions};
use crate::utils::warn_if_world_readable;
use crate::{run_scan, Config, ScanReport};

// Re-export CLI types so existing tests and callers can use the same names.
pub use domain_status_cli::{CliCommand, ExportCommand, ExportFormat, ScanCommand, SummaryCommand};

fn config_from_scan_command(cli: ScanCommand) -> Config {
    // Prefer -v/-q when they differ from the Info baseline; otherwise use --log-level.
    let log_level_filter_override =
        Some(cli.verbosity.log_level_filter()).filter(|f| *f != log::LevelFilter::Info);
    let enable_whois = if cli.no_whois {
        false
    } else {
        cli.enable_whois
    };
    Config {
        file: cli.file,
        log_level: cli.log_level,
        log_format: cli.log_format,
        log_level_filter_override,
        db_path: cli.db_path,
        max_concurrency: cli.max_concurrency,
        timeout_seconds: cli.timeout_seconds,
        user_agent: cli.user_agent,
        rate_limit_rps: cli.rate_limit_rps,
        fingerprints: cli.fingerprints,
        allow_degraded_fingerprints: cli.allow_degraded_fingerprints,
        geoip: cli.geoip,
        status_port: cli.status_port,
        enable_whois,
        cache_dir: cli.cache_dir,
        scan_external_scripts: cli.scan_external_scripts,
        fail_on: cli.fail_on,
        fail_on_pct_threshold: cli.fail_on_pct_threshold,
        log_file: Some(cli.log_file),
        progress_callback: None,
        dependency_overrides: None,
        allow_localhost_for_tests: false,
        drain_timeout_secs: cli.drain_timeout_secs,
    }
}

/// Parse CLI arguments using the shared CLI definition.
///
/// # Errors
/// Returns `Err` when argument parsing fails (e.g. invalid or missing required options).
pub fn parse_cli_command_from<I, T>(args: I) -> Result<CliCommand, clap::Error>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    CliCommand::try_parse_from(args)
}

/// Loads optional TOML config file only.
///
/// `DOMAIN_STATUS_*` scan settings are applied via clap `env =` (not here), so env is
/// not double-bound. Precedence when merging later: CLI > env (clap) > file > defaults.
///
/// Returns `Ok(None)` when no config file is requested and cwd has no `domain_status.toml`.
///
/// # Errors
/// Fails when a requested config file is missing or invalid, or when file values
/// cannot be deserialized into [`FileConfig`] (invalid enums/bools).
fn load_file_config(explicit_config_path: Option<&Path>) -> Result<Option<FileConfig>> {
    // CLI `--config` wins over DOMAIN_STATUS_CONFIG_FILE (documented precedence).
    let config_name = explicit_config_path.map(Path::to_path_buf).or_else(|| {
        std::env::var("DOMAIN_STATUS_CONFIG_FILE")
            .ok()
            .map(std::path::PathBuf::from)
    });

    let file_source = if let Some(ref path) = config_name {
        warn_if_world_readable(path);
        let path_str = path.to_string_lossy();
        Some(config::File::with_name(path_str.as_ref()).required(true))
    } else if Path::new("domain_status.toml").exists() {
        Some(config::File::with_name("domain_status").required(false))
    } else {
        None
    };

    let Some(file_source) = file_source else {
        return Ok(None);
    };

    let settings = config::Config::builder()
        .add_source(file_source)
        .build()
        .map_err(|e| anyhow::anyhow!("Failed to load configuration: {e}"))?;
    let file_config = settings
        .try_deserialize::<FileConfig>()
        .map_err(|e| anyhow::anyhow!("Invalid configuration: {e}"))?;
    Ok(Some(file_config))
}

/// Scan CLI arg ids that correspond to config fields. Used to detect which values
/// were set by the user (command line or env) vs defaulted.
const SCAN_CONFIG_ARG_IDS: &[&str] = &[
    "file",
    "log_level",
    "log_format",
    "db_path",
    "max_concurrency",
    "timeout_seconds",
    "user_agent",
    "rate_limit_rps",
    "fingerprints",
    "geoip",
    "status_port",
    "enable_whois",
    "no_whois",
    "cache_dir",
    "scan_external_scripts",
    "fail_on",
    "fail_on_pct_threshold",
    "log_file",
    "drain_timeout_secs",
];

/// CLI-only scan arg ids (not [`FileConfig`] fields).
const SCAN_CONFIG_CLI_ONLY_ARG_IDS: &[&str] = &["no_whois"];

/// Compile-time inventory check — not a coverage gap; the `const` assert below
/// fails the build if this is wrong.
const fn keys_subset(subset: &[&str], superset: &[&str]) -> bool {
    let mut i = 0;
    while i < subset.len() {
        if !crate::const_str::slice_contains(superset, subset[i]) {
            return false;
        }
        i += 1;
    }
    true
}

/// Compile-time inventory check — not a coverage gap; the `const` assert below
/// fails the build if this is wrong.
const fn scan_config_ids_are_file_or_cli_only() -> bool {
    let mut i = 0;
    while i < SCAN_CONFIG_ARG_IDS.len() {
        let id = SCAN_CONFIG_ARG_IDS[i];
        if !crate::const_str::slice_contains(crate::config::FILE_CONFIG_OVERLAY_KEYS, id)
            && !crate::const_str::slice_contains(SCAN_CONFIG_CLI_ONLY_ARG_IDS, id)
        {
            return false;
        }
        i += 1;
    }
    true
}

const _: () = assert!(
    keys_subset(crate::config::FILE_CONFIG_OVERLAY_KEYS, SCAN_CONFIG_ARG_IDS),
    "FileConfig overlay key missing from SCAN_CONFIG_ARG_IDS"
);

const _: () = assert!(
    scan_config_ids_are_file_or_cli_only(),
    "SCAN_CONFIG_ARG_IDS entry is neither a FileConfig key nor documented CLI-only"
);

/// Returns config field names that were explicitly set (command line or env), not defaulted.
fn get_explicit_config_keys(scan_matches: &clap::ArgMatches) -> Vec<&'static str> {
    let mut keys = Vec::new();
    for id in SCAN_CONFIG_ARG_IDS {
        if let Some(src) = scan_matches.value_source(id) {
            if matches!(src, ValueSource::CommandLine | ValueSource::EnvVariable) {
                keys.push(*id);
            }
        }
    }
    // Verbosity (-v/-q) sets log_level_filter_override; check flattened verbosity args.
    for id in ["verbose", "quiet"] {
        if let Some(src) = scan_matches.value_source(id) {
            if matches!(src, ValueSource::CommandLine | ValueSource::EnvVariable) {
                keys.push("log_level_filter_override");
                break;
            }
        }
    }
    keys
}

/// Builds `Config` with precedence: CLI > env (clap) > config file > defaults.
/// When `scan_arg_matches` is `Some`, only fields explicitly set by the user (CLI or env)
/// overwrite the file overlay; others keep file values. When `None`, all CLI-derived
/// values overwrite (backward compatible).
fn build_config_from_scan_command(
    scan_cmd: ScanCommand,
    scan_arg_matches: Option<&clap::ArgMatches>,
) -> Result<Config> {
    let file = load_file_config(scan_cmd.config.as_deref())?;
    let cli_config = config_from_scan_command(scan_cmd);
    let cli_explicit = scan_arg_matches.map(get_explicit_config_keys);
    let explicit_slice = cli_explicit.as_deref();
    Ok(crate::config::merge_file_and_cli(
        file.as_ref(),
        cli_config,
        explicit_slice,
    ))
}

/// Loads environment variables from `.env` file if it exists.
pub fn load_environment() {
    if dotenvy::dotenv().is_err() {
        if let Ok(exe_path) = std::env::current_exe() {
            if let Some(exe_dir) = exe_path.parent() {
                let env_path = exe_dir.join(".env");
                if env_path.exists() {
                    if let Err(e) = dotenvy::from_path(&env_path) {
                        eprintln!("Warning: Failed to load {}: {e}", env_path.display());
                    }
                }
            }
        }
    }
}

fn init_scan_logging(
    log_level: &LogLevel,
    log_format: LogFormat,
    log_file: &Path,
    log_level_override: Option<log::LevelFilter>,
) -> Result<()> {
    let level = log_level_override.unwrap_or_else(|| log_level_filter(log_level));
    init_logger_to_file(level, log_format, log_file).context("Failed to initialize file logger")?;
    eprintln!("Logs: {}", log_file.display());
    log::info!("domain-status version {}", env!("DOMAIN_STATUS_VERSION"));
    Ok(())
}

/// Fixed `{bar:30}` plus `{wide_msg}` so counters truncate instead of wrapping on resize.
const PROGRESS_BAR_TEMPLATE: &str =
    "{spinner:.green} [{elapsed_precise}] {bar:30.cyan/blue} {wide_msg}";

/// Stdin (and any unknown-length input) has no `len`; a determinate `pos/0` bar is nonsense.
const PROGRESS_SPINNER_TEMPLATE: &str = "{spinner:.green} [{elapsed_precise}] {wide_msg}";

/// Hide the bar when the terminal is narrower than chrome + a few counter cells.
const MIN_PROGRESS_COLS: usize = 56;

#[cfg(test)]
const PROGRESS_BAR_WIDTH: usize = 30;

fn progress_status_message(completed: usize, failed: usize, skipped: usize) -> String {
    format!("o={completed} f={failed} s={skipped}")
}

fn progress_wide_message(
    completed: usize,
    failed: usize,
    skipped: usize,
    finished: u64,
    total: usize,
) -> String {
    let stats = progress_status_message(completed, failed, skipped);
    if total == 0 {
        format!("{finished} {stats}")
    } else {
        let percent = finished
            .saturating_mul(100)
            .checked_div(total as u64)
            .unwrap_or(0);
        format!("{finished}/{total} ({percent}%) {stats}")
    }
}

fn stderr_cols() -> usize {
    std::env::var("COLUMNS")
        .ok()
        .and_then(|s| s.parse().ok())
        .filter(|&n| n > 0)
        .unwrap_or(80)
}

/// Visible chrome before `{wide_msg}` (spinner + `[elapsed]` + bar).
#[cfg(test)]
fn estimate_progress_chrome_cols(elapsed_precise: &str) -> usize {
    1 + 1 + 1 + elapsed_precise.len() + 1 + 1 + PROGRESS_BAR_WIDTH + 1
}

/// Rendered columns at `term_cols`: chrome plus a `wide_msg` that never overflows.
#[cfg(test)]
fn estimate_progress_line_cols(
    elapsed_precise: &str,
    pos: u64,
    len: u64,
    msg: &str,
    term_cols: Option<usize>,
) -> usize {
    let chrome = estimate_progress_chrome_cols(elapsed_precise);
    let wide = if len == 0 {
        format!("{pos} {msg}")
    } else {
        let percent = pos.saturating_mul(100).checked_div(len).unwrap_or(0);
        format!("{pos}/{len} ({percent}%) {msg}")
    };
    let untruncated = chrome + wide.chars().count();
    term_cols.map_or(untruncated, |cols| untruncated.min(cols))
}

fn create_progress_bar() -> Result<Arc<ProgressBar>> {
    let pb = Arc::new(ProgressBar::new(0));
    pb.set_style(
        ProgressStyle::default_bar()
            .template(PROGRESS_BAR_TEMPLATE)
            .context("Failed to create progress bar template")?
            .progress_chars("##-"),
    );
    Ok(pb)
}

fn apply_unknown_length_progress_style(pb: &ProgressBar) {
    if let Ok(style) = ProgressStyle::default_spinner().template(PROGRESS_SPINNER_TEMPLATE) {
        pb.set_style(style);
    }
}

fn create_progress_callback(
    pb_slot: Arc<std::sync::Mutex<Option<Arc<ProgressBar>>>>,
) -> Arc<dyn Fn(usize, usize, usize, usize) + Send + Sync> {
    let unknown_length = AtomicBool::new(false);
    let length_set = AtomicBool::new(false);
    Arc::new(move |completed, failed, skipped, total| {
        let pb = {
            let mut slot = pb_slot.lock().unwrap_or_else(|e| e.into_inner());
            if slot.is_none() {
                if let Ok(pb) = create_progress_bar() {
                    *slot = Some(pb);
                }
            }
            slot.clone()
        };
        let Some(pb) = pb else {
            return;
        };
        let finished = (completed + failed + skipped) as u64;
        if total == 0 {
            if !unknown_length.swap(true, Ordering::Relaxed) {
                apply_unknown_length_progress_style(&pb);
            }
            pb.set_position(finished);
        } else {
            if !length_set.swap(true, Ordering::Relaxed) {
                pb.set_length(total as u64);
            }
            pb.set_position(finished);
        }
        pb.set_message(progress_wide_message(
            completed, failed, skipped, finished, total,
        ));
    })
}

fn should_show_progress_bar(no_progress: bool) -> bool {
    use std::io::IsTerminal;
    !no_progress && std::io::stderr().is_terminal() && stderr_cols() >= MIN_PROGRESS_COLS
}

async fn execute_scan_with_reporting(mut config: Config, no_progress: bool) -> Result<i32> {
    let log_file = config
        .log_file
        .as_ref()
        .context("Configuration error: log_file not set")?;
    init_scan_logging(
        &config.log_level,
        config.log_format,
        log_file,
        config.log_level_filter_override,
    )?;

    let progress_slot: Arc<std::sync::Mutex<Option<Arc<ProgressBar>>>> =
        Arc::new(std::sync::Mutex::new(None));
    if should_show_progress_bar(no_progress) {
        config.progress_callback = Some(create_progress_callback(Arc::clone(&progress_slot)));
    }
    init_crypto_provider();

    let report = run_scan(config.clone())
        .await
        .map_err(|e| anyhow::anyhow!("{e}"))?;

    if let Some(pb) = progress_slot
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .take()
    {
        pb.finish_and_clear();
    }

    eprintln!(
        "Processed {} URL{} ({} succeeded, {} failed, {} skipped) in {:.1}s",
        report.total_urls,
        if report.total_urls == 1 { "" } else { "s" },
        report.successful,
        report.failed,
        report.skipped,
        report.elapsed_seconds
    );
    eprintln!("Results saved in {}", report.db_path.display());

    Ok(evaluate_exit_code(
        &config.fail_on,
        config.fail_on_pct_threshold,
        &report,
    ))
}

async fn execute_export_command(export_cmd: ExportCommand) -> Result<i32> {
    init_logger_with(log_level_filter(&LogLevel::Info), LogFormat::Plain)
        .context("Failed to initialize logger")?;
    log::info!("domain-status version {}", env!("DOMAIN_STATUS_VERSION"));

    let output_path = if let Some(ref path_str) = export_cmd.output {
        if path_str == "-" {
            None
        } else {
            Some(PathBuf::from(path_str))
        }
    } else {
        let extension = match export_cmd.format {
            CliExportFormat::Csv => "csv",
            CliExportFormat::Jsonl => "jsonl",
            CliExportFormat::Parquet => "parquet",
        };
        Some(PathBuf::from(format!("domain_status_export.{extension}")))
    };

    let lib_format = match export_cmd.format {
        CliExportFormat::Csv => crate::export::ExportFormat::Csv,
        CliExportFormat::Jsonl => crate::export::ExportFormat::Jsonl,
        CliExportFormat::Parquet => crate::export::ExportFormat::Parquet,
    };

    let export_opts = ExportOptions {
        db_path: export_cmd.db_path.clone(),
        output: output_path.clone(),
        format: lib_format,
        run_id: export_cmd.run_id.clone(),
        domain: export_cmd.domain.clone(),
        status: export_cmd.status,
        since: export_cmd.since,
        include_implied_tech: export_cmd.include_implied_tech,
    };

    let (count, format_name) = match export_cmd.format {
        CliExportFormat::Csv => (
            export_csv(&export_opts)
                .await
                .context("Failed to export CSV")?,
            "CSV",
        ),
        CliExportFormat::Jsonl => (
            crate::export::export_jsonl(&export_opts)
                .await
                .context("Failed to export JSONL")?,
            "JSONL",
        ),
        CliExportFormat::Parquet => (
            crate::export::export_parquet(&export_opts)
                .await
                .context("Failed to export Parquet")?,
            "Parquet",
        ),
    };

    if let Some(ref path) = output_path {
        eprintln!("Exported {} records to {}", count, path.display());
    } else {
        eprintln!("Exported {count} records to {format_name}");
    }

    Ok(0)
}

async fn execute_summary_command(summary_cmd: SummaryCommand) -> Result<i32> {
    init_logger_with(log_level_filter(&LogLevel::Info), LogFormat::Plain)
        .context("Failed to initialize logger")?;

    let pool = crate::storage::init_db_pool_with_path(&summary_cmd.db_path, 5)
        .await
        .with_context(|| {
            format!(
                "Failed to open database at {}",
                summary_cmd.db_path.display()
            )
        })?;

    let options = SummaryOptions {
        run_id: summary_cmd.run_id.clone(),
        top_technologies: summary_cmd.top,
    };
    let summary = query_scan_summary(&pool, &options).await?;
    print!("{}", format_scan_summary(&summary));
    Ok(0)
}

/// Execute a parsed CLI command and return the intended process exit code.
///
/// When `scan_arg_matches` is `Some`, config merge only overwrites file overlay for fields
/// explicitly set by the user (CLI or env). When `None`, all CLI-derived values overwrite.
///
/// # Errors
/// Returns `Err` when scan, export, or summary execution fails (I/O, database, or runtime errors).
pub async fn run_cli_command(
    cli_command: CliCommand,
    scan_arg_matches: Option<&clap::ArgMatches>,
) -> Result<i32> {
    match cli_command {
        CliCommand::Scan(scan_cmd) => {
            let no_progress = scan_cmd.no_progress;
            let config = build_config_from_scan_command(scan_cmd, scan_arg_matches)?;
            execute_scan_with_reporting(config, no_progress).await
        }
        CliCommand::Export(export_cmd) => execute_export_command(export_cmd).await,
        CliCommand::Summary(summary_cmd) => execute_summary_command(summary_cmd).await,
    }
}

/// Load environment, parse CLI args, and execute the command.
///
/// # Errors
/// Returns `Err` when argument parsing fails or when the executed command fails.
///
/// # Panics
/// Panics if the CLI definition has no subcommand (violates `subcommand_required`).
pub async fn run_cli_from_args<I, T>(args: I) -> Result<i32>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    load_environment();
    let args: Vec<OsString> = args.into_iter().map(Into::into).collect();

    // Handle --print-completions <shell> and --print-manpage before normal parsing (single source: domain_status_cli)
    if let Some(pos) = args
        .iter()
        .position(|a| a.to_str() == Some("--print-completions"))
    {
        if let Some(shell_arg) = args.get(pos + 1).and_then(|s| s.to_str()) {
            if let Ok(shell) = shell_arg.parse::<Shell>() {
                let mut cmd = domain_status_cli::clap_command(env!("DOMAIN_STATUS_VERSION"));
                clap_complete::generate(shell, &mut cmd, "domain-status", &mut io::stdout());
                return Ok(0);
            }
        }
    }
    if args.iter().any(|a| a.to_str() == Some("--print-manpage")) {
        let cmd = domain_status_cli::clap_command(env!("DOMAIN_STATUS_VERSION"));
        let man = Man::new(cmd);
        man.render(&mut io::stdout())?;
        return Ok(0);
    }

    let matches = match domain_status_cli::clap_command(env!("DOMAIN_STATUS_VERSION"))
        .try_get_matches_from(&args)
    {
        Ok(m) => m,
        Err(e) => {
            let _ = e.print();
            return Ok(e.exit_code());
        }
    };
    let (sub_name, sub_matches) = matches
        .subcommand()
        .expect("subcommand_required and arg_required_else_help guarantee a subcommand");
    let cli_command = match sub_name {
        "scan" => CliCommand::Scan(
            ScanCommand::from_arg_matches(sub_matches).map_err(|e| anyhow::anyhow!("{e}"))?,
        ),
        "export" => CliCommand::Export(
            ExportCommand::from_arg_matches(sub_matches).map_err(|e| anyhow::anyhow!("{e}"))?,
        ),
        "summary" => CliCommand::Summary(
            SummaryCommand::from_arg_matches(sub_matches).map_err(|e| anyhow::anyhow!("{e}"))?,
        ),
        _ => unreachable!("only scan, export, and summary subcommands exist"),
    };
    let scan_matches = matches.subcommand_matches("scan");
    run_cli_command(cli_command, scan_matches).await
}

/// Evaluates the numeric exit code for a completed scan.
///
/// Return values:
///
/// - `0` for success
/// - `2` when the selected failure policy is exceeded
/// - `3` when `FailOn::PctGreaterThan` was selected but zero URLs were processed
///
/// Command/runtime failures that occur before a [`ScanReport`] exists are handled
/// elsewhere and typically surface as process exit code `1`.
///
/// # Examples
///
/// ```
/// use domain_status::{evaluate_exit_code, FailOn, ScanReport};
/// use std::path::PathBuf;
///
/// let report = ScanReport {
///     run_id: "run_1".to_string(),
///     total_urls: 10,
///     successful: 8,
///     failed: 2,
///     skipped: 0,
///     elapsed_seconds: 1.5,
///     db_path: PathBuf::from("./domain_status.db"),
/// };
///
/// assert_eq!(evaluate_exit_code(&FailOn::Never, 10, &report), 0);
/// assert_eq!(evaluate_exit_code(&FailOn::AnyFailure, 10, &report), 2);
/// assert_eq!(evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report), 2);
/// ```
#[must_use]
pub fn evaluate_exit_code(fail_on: &FailOn, pct_threshold: u8, report: &ScanReport) -> i32 {
    use crate::exit_codes::{EXIT_NO_URLS_PCT, EXIT_POLICY_FAILURE, EXIT_SUCCESS};
    match fail_on {
        FailOn::Never => EXIT_SUCCESS,
        FailOn::AnyFailure => {
            if report.failed > 0 {
                EXIT_POLICY_FAILURE
            } else {
                EXIT_SUCCESS
            }
        }
        FailOn::PctGreaterThan => {
            if report.total_urls == 0 {
                return EXIT_NO_URLS_PCT;
            }
            // URL counts are typically < 10M, well within f64 52-bit mantissa
            #[allow(clippy::cast_precision_loss)]
            let failure_pct = (report.failed as f64 / report.total_urls as f64) * 100.0;
            if failure_pct > f64::from(pct_threshold) {
                EXIT_POLICY_FAILURE
            } else {
                EXIT_SUCCESS
            }
        }
        // `FailOn` is non_exhaustive (defined in domain_status_cli).
        _ => EXIT_SUCCESS,
    }
}

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

    fn sample_report(total_urls: usize, successful: usize, failed: usize) -> ScanReport {
        ScanReport {
            total_urls,
            successful,
            failed,
            skipped: 0,
            elapsed_seconds: 1.0,
            db_path: PathBuf::from("test.db"),
            run_id: "test-run-1".to_string(),
        }
    }

    #[test]
    fn progress_line_width_is_stable_and_independent_of_terminal_cols() {
        let early_elapsed = "00:00:01";
        let late_elapsed = "7d 21:27:56";
        let early_msg = progress_status_message(0, 0, 0);
        let late_msg = progress_status_message(263_688, 139_233, 49);
        let chrome_early = estimate_progress_chrome_cols(early_elapsed);
        let chrome_late = estimate_progress_chrome_cols(late_elapsed);
        let early = estimate_progress_line_cols(early_elapsed, 1, 752_906, &early_msg, Some(80));
        let late_80 =
            estimate_progress_line_cols(late_elapsed, 402_970, 752_906, &late_msg, Some(80));
        let late_40 =
            estimate_progress_line_cols(late_elapsed, 402_970, 752_906, &late_msg, Some(40));
        assert!(
            chrome_early <= MIN_PROGRESS_COLS,
            "early chrome must stay under the hide-bar threshold (got {chrome_early})"
        );
        assert!(
            chrome_late <= MIN_PROGRESS_COLS,
            "late chrome must stay under the hide-bar threshold (got {chrome_late})"
        );
        assert_eq!(
            late_80, 80,
            "wide_msg must cap the rendered line at 80 cols"
        );
        assert_eq!(
            late_40, 40,
            "wide_msg must cap the rendered line at 40 cols"
        );
        assert!(early <= 80);
        ProgressStyle::default_bar()
            .template(PROGRESS_BAR_TEMPLATE)
            .expect("determinate template must parse");
    }

    #[test]
    fn unknown_length_progress_template_parses_and_fits_80_cols() {
        ProgressStyle::default_spinner()
            .template(PROGRESS_SPINNER_TEMPLATE)
            .expect("stdin spinner template must parse");
        let elapsed = "00:01:23";
        let chrome = 1 + 1 + 1 + elapsed.len() + 1;
        assert!(
            chrome <= 80,
            "unknown-length chrome should fit 80 cols (got {chrome})"
        );
    }

    #[test]
    fn load_file_config_reads_toml_only() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("cfg.toml");
        std::fs::write(&path, "max_concurrency = 7\nenable_whois = true\n").unwrap();

        // File loader must not consult DOMAIN_STATUS_* (clap owns env). Avoid set_var
        // here so parallel CLI parse tests are not poisoned.
        let loaded = load_file_config(Some(&path)).unwrap().expect("toml loaded");
        assert_eq!(loaded.max_concurrency, Some(7));
        assert_eq!(loaded.enable_whois, Some(true));
    }

    #[test]
    fn load_file_config_errors_on_missing_explicit_path() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("missing.toml");
        assert!(
            load_file_config(Some(&missing)).is_err(),
            "explicit missing config path must error"
        );
    }

    #[test]
    fn merge_explicit_cli_env_keys_override_toml_file() {
        let file = FileConfig {
            max_concurrency: Some(7),
            enable_whois: Some(true),
            ..Default::default()
        };
        let cli_config = Config {
            max_concurrency: 99,
            enable_whois: false,
            ..Config::default()
        };
        // Simulate clap marking env/CLI as explicit for these keys.
        let merged = crate::config::merge_file_and_cli(
            Some(&file),
            cli_config,
            Some(&["max_concurrency", "enable_whois"]),
        );
        assert_eq!(merged.max_concurrency, 99);
        assert!(!merged.enable_whois);

        let preserved = crate::config::merge_file_and_cli(
            Some(&file),
            Config {
                max_concurrency: 99,
                enable_whois: false,
                ..Config::default()
            },
            Some(&[]), // nothing explicit → keep TOML
        );
        assert_eq!(preserved.max_concurrency, 7);
        assert!(preserved.enable_whois);
    }

    #[test]
    fn scan_defaults_enable_whois_and_no_whois_disables() {
        let on = parse_cli_command_from(["domain-status", "scan", "urls.txt"]).unwrap();
        match on {
            CliCommand::Scan(cmd) => {
                assert!(cmd.enable_whois, "WHOIS should be on by default");
                assert!(!cmd.no_whois);
                assert!(!cmd.no_progress);
            }
            CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan"),
        }

        let off =
            parse_cli_command_from(["domain-status", "scan", "urls.txt", "--no-whois"]).unwrap();
        match off {
            CliCommand::Scan(cmd) => {
                let config = config_from_scan_command(cmd);
                assert!(!config.enable_whois, "--no-whois must disable WHOIS");
            }
            CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan"),
        }

        let legacy =
            parse_cli_command_from(["domain-status", "scan", "urls.txt", "--enable-whois"])
                .unwrap();
        match legacy {
            CliCommand::Scan(cmd) => {
                assert!(
                    cmd.enable_whois,
                    "legacy --enable-whois must still parse (hidden from help)"
                );
            }
            CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan"),
        }
    }

    #[test]
    fn test_parse_real_scan_command_defaults() {
        use domain_status_cli::FailOn as CliFailOn;

        let cli = parse_cli_command_from(["domain-status", "scan", "test.txt"]).unwrap();

        match cli {
            CliCommand::Scan(cmd) => {
                assert_eq!(cmd.file, PathBuf::from("test.txt"));
                assert_eq!(cmd.max_concurrency, 30);
                assert_eq!(cmd.fail_on, CliFailOn::Never);
                assert_eq!(cmd.db_path, PathBuf::from("./domain_status.db"));
            }
            CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan command"),
        }
    }

    #[test]
    fn test_parse_real_export_command_filters() {
        use domain_status_cli::ExportFormat as CliExportFormat;

        let cli = parse_cli_command_from([
            "domain-status",
            "export",
            "--format",
            "jsonl",
            "--run-id",
            "run_123",
            "--domain",
            "example.com",
            "--status",
            "200",
            "--output",
            "out.jsonl",
        ])
        .unwrap();

        match cli {
            CliCommand::Export(cmd) => {
                assert_eq!(cmd.run_id.as_deref(), Some("run_123"));
                assert_eq!(cmd.domain.as_deref(), Some("example.com"));
                assert_eq!(cmd.status, Some(200));
                assert_eq!(cmd.output.as_deref(), Some("out.jsonl"));
                assert!(matches!(cmd.format, CliExportFormat::Jsonl));
            }
            CliCommand::Scan(_) | CliCommand::Summary(_) => panic!("expected export command"),
        }
    }

    #[test]
    fn test_parse_summary_command_defaults() {
        let cli = parse_cli_command_from(["domain-status", "summary"]).unwrap();
        match cli {
            CliCommand::Summary(cmd) => {
                assert_eq!(cmd.db_path, PathBuf::from("./domain_status.db"));
                assert!(cmd.run_id.is_none());
                assert_eq!(cmd.top, 15);
            }
            CliCommand::Scan(_) | CliCommand::Export(_) => panic!("expected summary command"),
        }
    }

    #[test]
    fn test_scan_command_into_config_preserves_fields() {
        use domain_status_cli::{
            FailOn as CliFailOn, LogFormat as CliLogFormat, LogLevel as CliLogLevel,
        };

        let scan_cmd = ScanCommand {
            config: None,
            file: PathBuf::from("test.txt"),
            log_level: CliLogLevel::Debug,
            verbosity: clap_verbosity_flag::Verbosity::<clap_verbosity_flag::InfoLevel>::default(),
            log_format: CliLogFormat::Json,
            db_path: PathBuf::from("custom.db"),
            max_concurrency: 50,
            timeout_seconds: 20,
            user_agent: "Custom Agent".to_string(),
            rate_limit_rps: 25,
            fingerprints: Some("https://example.com/tech.json".to_string()),
            geoip: Some("/path/to/geoip.mmdb".to_string()),
            status_port: Some(8080),
            enable_whois: true,
            no_whois: false,
            no_progress: false,
            cache_dir: None,
            scan_external_scripts: true,
            fail_on: CliFailOn::AnyFailure,
            fail_on_pct_threshold: 15,
            log_file: PathBuf::from("domain_status.log"),
            drain_timeout_secs: 10,
            allow_degraded_fingerprints: false,
        };

        let config: Config = config_from_scan_command(scan_cmd);
        assert_eq!(config.file, PathBuf::from("test.txt"));
        assert_eq!(config.db_path, PathBuf::from("custom.db"));
        assert_eq!(config.max_concurrency, 50);
        assert_eq!(config.timeout_seconds, 20);
        assert_eq!(config.user_agent, "Custom Agent");
        assert_eq!(config.rate_limit_rps, 25);
        assert_eq!(
            config.fingerprints,
            Some("https://example.com/tech.json".to_string())
        );
        assert_eq!(config.geoip, Some("/path/to/geoip.mmdb".to_string()));
        assert_eq!(config.status_port, Some(8080));
        assert!(config.enable_whois);
        assert!(config.scan_external_scripts);
        assert_eq!(config.fail_on, FailOn::AnyFailure);
        assert_eq!(config.fail_on_pct_threshold, 15);
        assert!(!config.allow_degraded_fingerprints);
    }

    #[test]
    fn test_evaluate_exit_code_real_logic() {
        use crate::exit_codes::{EXIT_NO_URLS_PCT, EXIT_POLICY_FAILURE, EXIT_SUCCESS};
        assert_eq!(
            evaluate_exit_code(&FailOn::Never, 10, &sample_report(10, 5, 5)),
            EXIT_SUCCESS
        );
        assert_eq!(
            evaluate_exit_code(&FailOn::AnyFailure, 10, &sample_report(10, 5, 5)),
            EXIT_POLICY_FAILURE
        );
        assert_eq!(
            evaluate_exit_code(&FailOn::AnyFailure, 10, &sample_report(10, 10, 0)),
            EXIT_SUCCESS
        );
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &sample_report(0, 0, 0)),
            EXIT_NO_URLS_PCT
        );
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &sample_report(100, 95, 5)),
            EXIT_SUCCESS
        );
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &sample_report(100, 89, 11)),
            EXIT_POLICY_FAILURE
        );
    }

    #[test]
    fn test_evaluate_exit_code_large_counts_do_not_overflow() {
        use crate::exit_codes::EXIT_SUCCESS;
        let max_urls = usize::MAX;
        let report = sample_report(max_urls, max_urls.saturating_sub(1), 1);
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report),
            EXIT_SUCCESS
        );
    }

    /// Boundary: exactly at threshold must return 0 (condition is `>`, not `>=`).
    #[test]
    fn test_evaluate_exit_code_pct_exactly_at_threshold_returns_zero() {
        use crate::exit_codes::EXIT_SUCCESS;
        // 10% failed, threshold 10: 10.0 > 10 is false → exit 0
        let report = sample_report(100, 90, 10);
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report),
            EXIT_SUCCESS,
            "exactly 10% failed with threshold 10 must return 0 (>)"
        );
    }

    /// Boundary: just over threshold must return 2.
    #[test]
    fn test_evaluate_exit_code_pct_just_over_threshold_returns_two() {
        use crate::exit_codes::EXIT_POLICY_FAILURE;
        // 11% failed, threshold 10: 11.0 > 10 is true → exit 2
        let report = sample_report(100, 89, 11);
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report),
            EXIT_POLICY_FAILURE,
            "just over 10% failed with threshold 10 must return 2"
        );
    }

    /// Floating-point boundary: 1/10 and 2/20 are 10%; both must yield 0 for threshold 10.
    #[test]
    fn test_evaluate_exit_code_pct_float_boundary() {
        use crate::exit_codes::EXIT_SUCCESS;
        let report_1_10 = sample_report(10, 9, 1);
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report_1_10),
            EXIT_SUCCESS,
            "1/10 = 10% with threshold 10 must return 0"
        );
        let report_2_20 = sample_report(20, 18, 2);
        assert_eq!(
            evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report_2_20),
            EXIT_SUCCESS,
            "2/20 = 10% with threshold 10 must return 0"
        );
    }
}