scope-bca-cli 0.8.5

Scope Blockchain Analysis - Command-line interface library
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
//! # CLI Module
//!
//! This module defines the command-line interface using `clap` with derive macros.
//! It provides the main `Cli` struct and `Commands` enum that define all
//! available commands and their arguments.
//!
//! ## UX Features
//!
//! - **Progress indicators** — Spinners and step counters via the `progress` module
//! - **Help with examples** — `after_help` blocks with example invocations
//! - **Command grouping** — Commands ordered by task (entity lookup, token
//!   analysis, compliance, data/export, config)
//! - **Shell completion** — `scope completions bash|zsh|fish` via `clap_complete`
//! - **Typo suggestions** — Built-in clap fuzzy matching for misspelled commands
//!
//! ## Command Structure
//!
//! ```text
//! scope [OPTIONS] <COMMAND>
//!
//! Entity lookup:
//!   address      Analyze a blockchain address (alias: addr)
//!   tx           Analyze a transaction (alias: transaction)
//!   contract     Analyze a smart contract (alias: ct)
//!   insights     Auto-detect target type and run analyses (alias: insight)
//!
//! Token analysis:
//!   crawl        Crawl a token for DEX analytics (alias: token)
//!   token-health DEX analytics + optional order book (alias: health)
//!   discover     Browse trending/boosted tokens (alias: disc)
//!   monitor      Live TUI dashboard (alias: mon)
//!   market       Peg and order book health for stablecoins
//!   venues       Manage exchange venue descriptors (alias: ven)
//!
//! Compliance:
//!   compliance   Risk, trace, analyze, compliance-report
//!
//! Data & export:
//!   address-book Add, remove, list, summary (alias: ab, portfolio)
//!   export       Export to JSON/CSV
//!   report       Batch and combined reports
//!
//! Config & interactive:
//!   interactive  Full-screen TUI for every command (alias: tui, shell)
//!   setup        Configure API keys and preferences (alias: config)
//!   completions  Generate shell completions for bash/zsh/fish
//!
//! Options:
//!   --config <PATH>   Path to configuration file
//!   -v, --verbose...  Increase logging verbosity
//!   --ai              Markdown output for agent parsing
//!   --no-color        Disable colored output
//!   -h, --help        Print help (with examples)
//!   -V, --version     Print version
//! ```

pub mod address;
pub mod address_book;
pub mod address_report;
pub(crate) mod ansi;
pub mod candles;
pub mod charts;
pub mod compliance;
pub mod contract;
pub mod crawl;
pub mod discover;
pub mod dispatch;
pub mod errors;
pub mod export;
pub mod ghola_offer;
pub mod health_args;
pub mod insights;
pub mod interactive;
pub mod market;
pub mod monitor;
pub mod output;
pub(crate) mod plain;
pub mod progress;
pub mod prompt;
pub mod repeat;
pub mod report;
pub mod resolve;
pub(crate) mod screen;
pub mod setup;
pub(crate) mod textfit;
pub mod theme;
pub mod token_health;
pub(crate) mod token_pick;
pub mod tui;
pub mod tx;
pub mod venues;
pub mod watch;

use clap::{Parser, Subcommand};
use std::path::PathBuf;

pub use address::AddressArgs;
pub use address_book::AddressBookArgs;
pub use crawl::CrawlArgs;
pub use export::ExportArgs;
pub use interactive::InteractiveArgs;
pub use monitor::MonitorArgs;
pub use setup::SetupArgs;
pub use tx::TxArgs;

/// Blockchain Analysis CLI - A tool for blockchain data analysis.
///
/// Scope provides comprehensive blockchain analysis capabilities including
/// address investigation, transaction decoding, address book management, and
/// data export functionality.
#[derive(Debug, Parser)]
#[command(
    name = "scope",
    version,
    about = "Scope Blockchain Analysis - A tool for blockchain data analysis",
    long_about = format!(
        "Scope Blockchain Analysis v{}\n\n\
         A production-grade tool for blockchain data analysis, address management,\n\
         and transaction investigation.\n\n\
         Use --help with any subcommand for detailed usage information.",
        env!("CARGO_PKG_VERSION")
    ),
    after_help = "\x1b[1mExamples:\x1b[0m\n  \
                  scope address 0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2\n  \
                  scope address @main-wallet              \x1b[2m# address book shortcut\x1b[0m\n  \
                  scope contract 0xdAC17F958D2ee523a2206206994597C13D831ec7\n  \
                  scope crawl USDC --chain ethereum\n  \
                  scope insights 0xabc123...\n  \
                  scope monitor USDC\n  \
                  scope compliance risk 0x742d...\n  \
                  scope setup\n\n\
                  \x1b[2mTip: Use @label in any command to recall an address from the address book.\x1b[0m\n\n\
                  \x1b[1mDocumentation:\x1b[0m\n  \
                  https://github.com/robot-accomplice/scope-blockchain-analysis\n  \
                  Quickstart guide: docs/QUICKSTART.md"
)]
pub struct Cli {
    /// Subcommand to execute.
    #[command(subcommand)]
    pub command: Commands,

    /// Path to configuration file.
    ///
    /// Overrides the default location (~/.scope-bca/config.yaml).
    #[arg(long, global = true, value_name = "PATH")]
    pub config: Option<PathBuf>,

    /// Increase logging verbosity.
    ///
    /// Can be specified multiple times:
    /// -v    = INFO level
    /// -vv   = DEBUG level
    /// -vvv  = TRACE level
    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// Disable colored output.
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Output markdown to console for agent parsing.
    ///
    /// Forces all commands to emit markdown-formatted output to stdout
    /// instead of tables or JSON. Useful for LLM/agent consumption.
    #[arg(long, global = true)]
    pub ai: bool,
}

/// Available CLI subcommands.
#[derive(Debug, Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum Commands {
    // -- Entity lookup --------------------------------------------------------
    /// Analyze a blockchain address.
    ///
    /// Retrieves balance, transaction history, and token holdings
    /// for the specified address.
    #[command(visible_alias = "addr")]
    Address(AddressArgs),

    /// Analyze a transaction.
    ///
    /// Decodes transaction data, traces execution, and displays
    /// detailed information about the transaction.
    #[command(visible_alias = "transaction")]
    Tx(TxArgs),

    /// Unified insights: infer chain and type, run relevant analyses.
    ///
    /// Provide any target (address, tx hash, or token) and Scope will
    /// detect it, run the appropriate analyses, and present observations.
    #[command(visible_alias = "insight")]
    Insights(insights::InsightsArgs),

    /// Analyze a smart contract.
    ///
    /// Retrieves source code, detects proxy patterns, maps access control,
    /// scans for vulnerabilities, checks DeFi patterns, and gathers external
    /// intelligence (GitHub links, audit reports).
    #[command(visible_alias = "ct")]
    Contract(contract::ContractArgs),

    // -- Token analysis -------------------------------------------------------
    /// Crawl a token for analytics data.
    ///
    /// Retrieves comprehensive token information including top holders,
    /// volume statistics, price data, and liquidity. Displays results
    /// with ASCII charts and can generate markdown reports.
    #[command(visible_alias = "token")]
    Crawl(CrawlArgs),

    /// Token health suite: DEX analytics + optional order book (crawl + market).
    ///
    /// Combines liquidity, volume, and holder data with optional market/peg
    /// summary for stablecoins. Use --with-market for order book data.
    #[command(visible_alias = "health")]
    TokenHealth(token_health::TokenHealthArgs),

    /// Discover trending and boosted tokens from DexScreener.
    ///
    /// Browse featured token profiles, recently boosted tokens,
    /// or top boosted tokens by activity.
    #[command(visible_alias = "disc")]
    Discover(discover::DiscoverArgs),

    /// Monitor a market, token or address live: the monitor wizard in the TUI.
    ///
    /// Opens the TUI with the monitor wizard filled from the arguments: the
    /// targets, the checks (market health with a venue), the interval, the
    /// duration and the outputs. Its run shows each target's pass/fail state
    /// in a grid. `--dashboard` opens the old dashboard (deprecated).
    #[command(visible_alias = "mon")]
    Monitor(MonitorArgs),

    /// Peg and order book health for stablecoin markets.
    ///
    /// Fetches level-2 depth from exchange APIs and reports
    /// peg deviation, spread, depth, and configurable health checks.
    #[command(subcommand)]
    Market(market::MarketCommands),

    /// Manage exchange venue descriptors.
    ///
    /// List available venues, view the YAML schema, initialise the
    /// user venues directory, or validate custom descriptor files.
    #[command(subcommand, visible_alias = "ven")]
    Venues(venues::VenuesCommands),

    // -- Compliance -----------------------------------------------------------
    /// Compliance and risk analysis commands.
    ///
    /// Assess risk, trace taint, detect patterns, and generate
    /// compliance reports for blockchain addresses.
    #[command(subcommand)]
    Compliance(compliance::ComplianceCommands),

    // -- Data & export --------------------------------------------------------
    /// Address book management commands.
    ///
    /// Add, remove, and list watched addresses (wallets, contracts, tokens).
    /// View aggregated balances across multiple chains.
    /// Use `@label` in any command to recall a saved address.
    #[command(visible_alias = "ab", alias = "portfolio", alias = "port")]
    AddressBook(AddressBookArgs),

    /// Export analysis data.
    ///
    /// Export transaction history, balances, or analysis results
    /// to various formats (JSON, CSV).
    Export(ExportArgs),

    /// Batch and combined report generation.
    #[command(subcommand)]
    Report(report::ReportCommands),

    // -- Config & interactive -------------------------------------------------
    /// Full-screen TUI that runs every command, with preserved context.
    ///
    /// Every CLI command runs inside it with the same flags. Chain, format,
    /// and other settings persist between commands.
    #[command(visible_aliases = ["tui", "shell"])]
    Interactive(InteractiveArgs),

    /// Configure Scope settings and API keys.
    ///
    /// Run the setup wizard to configure API keys and preferences,
    /// or use --status to view current configuration.
    #[command(visible_alias = "config")]
    Setup(SetupArgs),

    /// Generate shell completions for bash, zsh, or fish.
    ///
    /// Output shell completion script to stdout for the specified shell.
    /// Source the output in your shell profile for tab completion.
    Completions(CompletionsArgs),

    /// Start the web UI server (localhost).
    ///
    /// Serves the same Scope features as the CLI via a local web interface
    /// at http://127.0.0.1:8080 (default). Use --daemon to run in the
    /// background, --stop to halt a running daemon.
    #[command(visible_alias = "serve")]
    Web(WebArgs),
}

impl Commands {
    /// Returns `true` for interactive/long-running commands that manage their
    /// own UI (TUI, live monitor, web server, setup wizard, shell completions).
    /// Non-interactive commands return `false` and get a version header.
    pub fn is_interactive(&self) -> bool {
        matches!(
            self,
            Commands::Interactive(_)
                | Commands::Monitor(_)
                | Commands::Setup(_)
                | Commands::Completions(_)
                | Commands::Web(_)
        )
    }
}

/// Arguments for the web server command.
#[derive(Debug, Clone, clap::Args)]
#[command(after_help = "\x1b[1mExamples:\x1b[0m
  scope web
  scope web --port 3000 --bind 0.0.0.0
  scope serve --daemon
  scope web --stop")]
pub struct WebArgs {
    /// Port to listen on.
    #[arg(long, short, default_value = "8080")]
    pub port: u16,

    /// Address to bind to.
    ///
    /// Use 127.0.0.1 for local-only (default) or 0.0.0.0 for LAN access.
    #[arg(long, default_value = "127.0.0.1")]
    pub bind: String,

    /// Run as a background daemon.
    #[arg(long, short)]
    pub daemon: bool,

    /// Stop a running daemon.
    #[arg(long)]
    pub stop: bool,
}

/// Arguments for the completions command.
#[derive(Debug, Clone, clap::Args)]
#[command(after_help = "\x1b[1mExamples:\x1b[0m
  scope completions bash >> ~/.bashrc
  scope completions zsh > ~/.zfunc/_scope
  scope completions fish > ~/.config/fish/completions/scope.fish")]
pub struct CompletionsArgs {
    /// The shell to generate completions for.
    #[arg(value_enum)]
    pub shell: clap_complete::Shell,
}

impl Cli {
    /// Parses CLI arguments from the environment.
    ///
    /// This is a convenience wrapper around `clap::Parser::parse()`.
    pub fn parse_args() -> Self {
        Self::parse()
    }

    /// Returns the log level based on verbosity flag.
    ///
    /// Maps the `-v` count to tracing log levels:
    /// - 0: WARN (default)
    /// - 1: INFO
    /// - 2: DEBUG
    /// - 3+: TRACE
    pub fn log_level(&self) -> tracing::Level {
        match self.verbose {
            0 => tracing::Level::WARN,
            1 => tracing::Level::INFO,
            2 => tracing::Level::DEBUG,
            _ => tracing::Level::TRACE,
        }
    }
}

// ============================================================================
// Unit Tests
// ============================================================================

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

    #[test]
    fn test_cli_parse_address_command() {
        let cli = Cli::try_parse_from([
            "scope",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert!(matches!(cli.command, Commands::Address(_)));
        assert!(cli.config.is_none());
        assert_eq!(cli.verbose, 0);
    }

    #[test]
    fn test_cli_parse_address_alias() {
        let cli = Cli::try_parse_from([
            "scope",
            "addr",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert!(matches!(cli.command, Commands::Address(_)));
    }

    #[test]
    fn test_cli_parse_tx_command() {
        let cli = Cli::try_parse_from([
            "scope",
            "tx",
            "0xabc123def456789012345678901234567890123456789012345678901234abcd",
        ])
        .unwrap();

        assert!(matches!(cli.command, Commands::Tx(_)));
    }

    #[test]
    fn test_cli_parse_tx_alias() {
        let cli = Cli::try_parse_from([
            "scope",
            "transaction",
            "0xabc123def456789012345678901234567890123456789012345678901234abcd",
        ])
        .unwrap();

        assert!(matches!(cli.command, Commands::Tx(_)));
    }

    #[test]
    fn test_cli_parse_address_book_command() {
        let cli = Cli::try_parse_from(["scope", "address-book", "list"]).unwrap();

        assert!(matches!(cli.command, Commands::AddressBook(_)));
    }

    #[test]
    fn test_cli_parse_address_book_portfolio_alias() {
        let cli = Cli::try_parse_from(["scope", "portfolio", "list"]).unwrap();

        assert!(matches!(cli.command, Commands::AddressBook(_)));
    }

    #[test]
    fn test_cli_parse_export_command() {
        let cli = Cli::try_parse_from([
            "scope",
            "export",
            "--address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
            "--output",
            "data.json",
        ])
        .unwrap();

        assert!(matches!(cli.command, Commands::Export(_)));
    }

    #[test]
    fn test_cli_parse_interactive_command() {
        let cli = Cli::try_parse_from(["scope", "interactive"]).unwrap();

        assert!(matches!(cli.command, Commands::Interactive(_)));
    }

    #[test]
    fn test_cli_parse_tui_alias() {
        // `scope tui` is the short name for interactive mode (#47).
        let cli = Cli::try_parse_from(["scope", "tui"]).unwrap();

        assert!(matches!(cli.command, Commands::Interactive(_)));
    }

    #[test]
    fn test_cli_parse_interactive_alias() {
        let cli = Cli::try_parse_from(["scope", "shell"]).unwrap();

        assert!(matches!(cli.command, Commands::Interactive(_)));
    }

    #[test]
    fn test_cli_parse_interactive_no_banner() {
        let cli = Cli::try_parse_from(["scope", "interactive", "--no-banner"]).unwrap();

        if let Commands::Interactive(args) = cli.command {
            assert!(args.no_banner);
        } else {
            panic!("Expected Interactive command");
        }
    }

    #[test]
    fn test_cli_verbose_flag_counting() {
        let cli = Cli::try_parse_from([
            "scope",
            "-vvv",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert_eq!(cli.verbose, 3);
    }

    #[test]
    fn test_cli_verbose_separate_flags() {
        let cli = Cli::try_parse_from([
            "scope",
            "-v",
            "-v",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert_eq!(cli.verbose, 2);
    }

    #[test]
    fn test_cli_global_config_option() {
        let cli = Cli::try_parse_from([
            "scope",
            "--config",
            "/custom/path.yaml",
            "tx",
            "0xabc123def456789012345678901234567890123456789012345678901234abcd",
        ])
        .unwrap();

        assert_eq!(cli.config, Some(PathBuf::from("/custom/path.yaml")));
    }

    #[test]
    fn test_cli_config_long_flag() {
        let cli = Cli::try_parse_from([
            "scope",
            "--config",
            "/custom/config.yaml",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert_eq!(cli.config, Some(PathBuf::from("/custom/config.yaml")));
    }

    #[test]
    fn test_cli_no_color_flag() {
        let cli = Cli::try_parse_from([
            "scope",
            "--no-color",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert!(cli.no_color);
    }

    #[test]
    fn test_cli_missing_required_args_fails() {
        let result = Cli::try_parse_from(["scope", "address"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_cli_invalid_subcommand_fails() {
        let result = Cli::try_parse_from(["scope", "invalid"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_cli_log_level_default() {
        let cli = Cli::try_parse_from([
            "scope",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert_eq!(cli.log_level(), tracing::Level::WARN);
    }

    #[test]
    fn test_cli_log_level_info() {
        let cli = Cli::try_parse_from([
            "scope",
            "-v",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert_eq!(cli.log_level(), tracing::Level::INFO);
    }

    #[test]
    fn test_cli_log_level_debug() {
        let cli = Cli::try_parse_from([
            "scope",
            "-vv",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert_eq!(cli.log_level(), tracing::Level::DEBUG);
    }

    #[test]
    fn test_cli_log_level_trace() {
        let cli = Cli::try_parse_from([
            "scope",
            "-vvvv",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        assert_eq!(cli.log_level(), tracing::Level::TRACE);
    }

    #[test]
    fn test_cli_debug_impl() {
        let cli = Cli::try_parse_from([
            "scope",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();

        let debug_str = format!("{:?}", cli);
        assert!(debug_str.contains("Cli"));
        assert!(debug_str.contains("Address"));
    }

    // ========================================================================
    // Monitor command tests
    // ========================================================================

    #[test]
    fn test_cli_parse_monitor_command() {
        let cli = Cli::try_parse_from([
            "scope",
            "monitor",
            "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
        ])
        .unwrap();

        assert!(matches!(cli.command, Commands::Monitor(_)));
    }

    #[test]
    fn test_cli_parse_monitor_alias_mon() {
        let cli = Cli::try_parse_from(["scope", "mon", "USDC"]).unwrap();

        assert!(matches!(cli.command, Commands::Monitor(_)));
        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.token, "USDC");
            assert_eq!(args.chain, "ethereum"); // default
            assert!(args.layout.is_none());
            assert!(args.refresh.is_none());
            assert!(args.scale.is_none());
            assert!(args.color_scheme.is_none());
            assert!(args.export.is_none());
        }
    }

    #[test]
    fn test_cli_parse_monitor_with_chain() {
        let cli = Cli::try_parse_from(["scope", "monitor", "USDC", "--chain", "solana"]).unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.token, "USDC");
            assert_eq!(args.chain, "solana");
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_chain_short_flag() {
        let cli = Cli::try_parse_from(["scope", "monitor", "PEPE", "-c", "ethereum"]).unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.token, "PEPE");
            assert_eq!(args.chain, "ethereum");
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_with_layout() {
        let cli =
            Cli::try_parse_from(["scope", "monitor", "USDC", "--layout", "chart-focus"]).unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.layout, Some(monitor::LayoutPreset::ChartFocus));
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_with_refresh() {
        let cli = Cli::try_parse_from(["scope", "monitor", "USDC", "--refresh", "3"]).unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.refresh, Some(3));
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_with_scale() {
        let cli = Cli::try_parse_from(["scope", "monitor", "USDC", "--scale", "log"]).unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.scale, Some(monitor::ScaleMode::Log));
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_with_color_scheme() {
        let cli =
            Cli::try_parse_from(["scope", "monitor", "USDC", "--color-scheme", "blue-orange"])
                .unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.color_scheme, Some(monitor::ColorScheme::BlueOrange));
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_with_export() {
        let cli =
            Cli::try_parse_from(["scope", "monitor", "USDC", "--export", "/tmp/out.csv"]).unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.export, Some(std::path::PathBuf::from("/tmp/out.csv")));
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_short_flags() {
        let cli = Cli::try_parse_from([
            "scope", "mon", "USDC", "-c", "solana", "-l", "compact", "-r", "10", "-s", "log", "-e",
            "data.csv",
        ])
        .unwrap();

        if let Commands::Monitor(args) = cli.command {
            assert_eq!(args.token, "USDC");
            assert_eq!(args.chain, "solana");
            assert_eq!(args.layout, Some(monitor::LayoutPreset::Compact));
            assert_eq!(args.refresh, Some(10));
            assert_eq!(args.scale, Some(monitor::ScaleMode::Log));
            assert_eq!(args.export, Some(std::path::PathBuf::from("data.csv")));
        } else {
            panic!("Expected Monitor command");
        }
    }

    #[test]
    fn test_cli_parse_monitor_missing_token_fails() {
        let result = Cli::try_parse_from(["scope", "monitor"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_cli_parse_monitor_invalid_layout_fails() {
        let result = Cli::try_parse_from(["scope", "monitor", "USDC", "--layout", "invalid"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_cli_parse_monitor_invalid_scale_fails() {
        let result = Cli::try_parse_from(["scope", "monitor", "USDC", "--scale", "quadratic"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_cli_parse_market_summary() {
        let cli = Cli::try_parse_from(["scope", "market", "summary"]).unwrap();
        assert!(matches!(cli.command, Commands::Market(_)));
    }

    #[test]
    fn test_cli_parse_market_summary_with_pair() {
        let cli = Cli::try_parse_from(["scope", "market", "summary", "DAI_USDT"]).unwrap();
        if let Commands::Market(market::MarketCommands::Summary(args)) = cli.command {
            assert_eq!(args.pair, "DAI_USDT");
        } else {
            panic!("Expected Market Summary command");
        }
    }

    #[test]
    fn test_cli_parse_report_batch() {
        let cli = Cli::try_parse_from([
            "scope",
            "report",
            "batch",
            "--addresses",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
            "--output",
            "report.md",
        ])
        .unwrap();
        assert!(matches!(cli.command, Commands::Report(_)));
    }

    #[test]
    fn test_cli_parse_market_summary_with_thresholds() {
        let cli = Cli::try_parse_from([
            "scope",
            "market",
            "summary",
            "--peg-range",
            "0.002",
            "--min-bid-ask-ratio",
            "0.1",
            "--max-bid-ask-ratio",
            "10",
        ])
        .unwrap();
        if let Commands::Market(market::MarketCommands::Summary(args)) = cli.command {
            assert_eq!(args.health.peg_range, Some(0.002));
            assert_eq!(args.health.min_bid_ask_ratio, Some(0.1));
            assert_eq!(args.health.max_bid_ask_ratio, Some(10.0));
        } else {
            panic!("Expected Market Summary command");
        }
    }

    #[test]
    fn test_cli_parse_token_health() {
        let cli = Cli::try_parse_from(["scope", "token-health", "USDC"]).unwrap();
        if let Commands::TokenHealth(args) = cli.command {
            assert_eq!(args.token, "USDC");
            assert!(!args.with_market);
        } else {
            panic!("Expected TokenHealth command");
        }
    }

    #[test]
    fn test_cli_parse_token_health_alias() {
        let cli = Cli::try_parse_from(["scope", "health", "USDC", "--with-market"]).unwrap();
        if let Commands::TokenHealth(args) = cli.command {
            assert_eq!(args.token, "USDC");
            assert!(args.with_market);
            assert_eq!(args.venue, "binance"); // default venue
        } else {
            panic!("Expected TokenHealth command");
        }
    }

    #[test]
    fn test_cli_parse_token_health_venue_biconomy() {
        let cli = Cli::try_parse_from([
            "scope",
            "token-health",
            "USDC",
            "--with-market",
            "--venue",
            "biconomy",
        ])
        .unwrap();
        if let Commands::TokenHealth(args) = cli.command {
            assert_eq!(args.venue, "biconomy");
        } else {
            panic!("Expected TokenHealth command");
        }
    }

    #[test]
    fn test_cli_parse_token_health_venue_eth() {
        let cli = Cli::try_parse_from([
            "scope",
            "token-health",
            "USDC",
            "--with-market",
            "--venue",
            "eth",
        ])
        .unwrap();
        if let Commands::TokenHealth(args) = cli.command {
            assert_eq!(args.venue, "eth");
        } else {
            panic!("Expected TokenHealth command");
        }
    }

    #[test]
    fn test_cli_parse_token_health_venue_solana() {
        let cli = Cli::try_parse_from([
            "scope",
            "token-health",
            "USDC",
            "--with-market",
            "--venue",
            "solana",
        ])
        .unwrap();
        if let Commands::TokenHealth(args) = cli.command {
            assert_eq!(args.venue, "solana");
        } else {
            panic!("Expected TokenHealth command");
        }
    }

    #[test]
    fn test_cli_parse_ai_flag() {
        let cli = Cli::try_parse_from([
            "scope",
            "--ai",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ])
        .unwrap();
        assert!(cli.ai);
    }
}