arf-console 0.3.2

A cross-platform R console written in Rust
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
//! Command-line interface definition using clap.

use crate::external::rig;
use clap::builder::PossibleValuesParser;
use clap::builder::TypedValueParser;
use clap::{CommandFactory, Parser, Subcommand, ValueHint};
use clap_complete::{Shell, generate};
use std::io;
use std::path::PathBuf;

/// A cross-platform R console written in Rust.
#[derive(Parser, Debug)]
#[command(name = "arf")]
#[command(author, version, about, long_about = None)]
pub struct Cli {
    /// Evaluate R expression and exit
    #[arg(short = 'e', long = "eval")]
    pub eval: Option<String>,

    /// [R] Take input from FILE
    #[arg(short = 'f', long = "file", value_hint = ValueHint::FilePath, conflicts_with = "eval", hide_short_help = true)]
    pub file: Option<PathBuf>,

    /// Enable reprex mode (no prompt, output prefixed with #>)
    ///
    /// Config: startup.mode.reprex
    #[arg(long)]
    pub reprex: bool,

    /// Enable auto-formatting of R code in reprex mode (requires Air CLI)
    ///
    /// Config: startup.mode.autoformat
    #[arg(long)]
    pub auto_format: bool,

    /// Path to configuration file
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    pub config: Option<PathBuf>,

    /// Suppress the startup banner
    ///
    /// Config: show_banner
    #[arg(long)]
    pub no_banner: bool,

    /// R version to use via rig (overrides r_source config)
    ///
    /// Requires rig to be installed. Use "default" for rig's default,
    /// or specify a version like "4.5" or "release".
    #[arg(long = "with-r-version", conflicts_with = "r_home")]
    pub r_version: Option<String>,

    /// Explicit R_HOME path (overrides r_source config)
    ///
    /// Use this to specify a specific R installation directory.
    /// Mutually exclusive with --with-r-version.
    #[arg(long = "r-home", value_hint = ValueHint::DirPath, conflicts_with = "r_version")]
    pub r_home: Option<PathBuf>,

    // R-compatible flags (passed to R, for vscode-R and radian compatibility)
    // Hidden from short help (-h) but shown in long help (--help).
    /// Start R in vanilla mode (no init files, no save/restore)
    #[arg(long = "vanilla")]
    pub vanilla: bool,

    /// [R] Don't print R startup message
    #[arg(short = 'q', long = "quiet", alias = "silent", hide_short_help = true)]
    pub quiet: bool,

    /// [R] Don't save workspace at end of session (default)
    #[arg(long = "no-save", hide_short_help = true)]
    pub no_save: bool,

    /// [R] Save workspace at end of session
    #[arg(long = "save", conflicts_with = "no_save", hide_short_help = true)]
    pub save: bool,

    /// [R] Don't restore previously saved objects (default)
    #[arg(long = "no-restore", hide_short_help = true)]
    pub no_restore: bool,

    /// [R] Don't restore previously saved objects
    #[arg(long = "no-restore-data", hide_short_help = true)]
    pub no_restore_data: bool,

    /// [R] Restore previously saved objects
    #[arg(long = "restore-data", conflicts_with_all = ["no_restore", "no_restore_data"], hide_short_help = true)]
    pub restore_data: bool,

    /// [R] Don't read the site and user environment files
    #[arg(long = "no-environ", hide_short_help = true)]
    pub no_environ: bool,

    /// [R] Don't read the site-wide Rprofile
    #[arg(long = "no-site-file", hide_short_help = true)]
    pub no_site_file: bool,

    /// [R] Don't read the user's .Rprofile
    #[arg(long = "no-init-file", hide_short_help = true)]
    pub no_init_file: bool,

    /// [R] Force R to run interactively (no-op, always interactive)
    #[arg(long = "interactive", hide = true)]
    pub interactive: bool,

    /// [R] Don't echo input (no-op, arf controls its own echo)
    #[arg(long = "no-echo", hide_short_help = true)]
    pub no_echo: bool,

    /// [R] Combine --quiet --no-save --no-restore (deprecated in R 4.0, use --no-echo)
    #[arg(long = "slave", hide = true)]
    pub slave: bool,

    /// [R] Restore previously saved objects (opposite of --no-restore)
    #[arg(long = "restore", conflicts_with_all = ["no_restore", "no_restore_data"], hide = true)]
    pub restore: bool,

    /// [R] Print more information about progress (no-op)
    #[arg(long = "verbose", hide = true)]
    pub verbose: bool,

    /// [R] Specify encoding to be used for stdin (no-op)
    #[arg(long = "encoding", hide = true)]
    pub encoding: Option<String>,

    /// [R] Set max number of connections to N
    #[arg(long = "max-connections", hide = true)]
    pub max_connections: Option<u32>,

    /// [R] Set max size of protect stack to N
    #[arg(long = "max-ppsize", hide = true)]
    pub max_ppsize: Option<u32>,

    /// [R] Set min number of fixed size obj's ("cons cells") to N
    #[arg(long = "min-nsize", hide = true)]
    pub min_nsize: Option<String>,

    /// [R] Set vector heap minimum to N bytes; '4M' = 4 MegaB
    #[arg(long = "min-vsize", hide = true)]
    pub min_vsize: Option<String>,

    /// [R] Run R through debugger NAME (no-op)
    #[arg(short = 'd', long = "debugger", hide = true)]
    pub debugger: Option<String>,

    /// [R] Pass ARGS as arguments to the debugger (no-op)
    #[arg(long = "debugger-args", hide = true)]
    pub debugger_args: Option<String>,

    /// [R] Use TYPE as GUI (no-op)
    #[arg(short = 'g', long = "gui", hide = true)]
    pub gui: Option<String>,

    /// [R] Specify a sub-architecture (no-op)
    #[arg(long = "arch", hide = true)]
    pub arch: Option<String>,

    /// [R] In R, skip the rest of the command line.
    /// arf accepts this flag for compatibility but does NOT consume trailing arguments;
    /// unknown flags after --args will still cause a parse error.
    #[arg(long = "args", hide = true, num_args = 0)]
    pub r_args_marker: bool,

    /// [R] Don't use readline (no-op)
    #[arg(long = "no-readline", hide = true)]
    pub no_readline: bool,

    /// [R] Don't restore history (no-op)
    #[arg(long = "no-restore-history", hide = true)]
    pub no_restore_history: bool,

    /// Enable IPC server for external tool access (AI agents, vscode-R, etc.)
    ///
    /// Starts the IPC server alongside the interactive REPL, allowing
    /// external tools to call `arf ipc eval`, `arf ipc send`, etc.
    /// For headless (no REPL) usage, see `arf headless` instead.
    #[arg(long = "with-ipc")]
    pub with_ipc: bool,

    /// Disable auto-matching of brackets and quotes (for testing)
    #[arg(long = "no-auto-match", hide = true)]
    pub no_auto_match: bool,

    /// Disable completion menu (for testing)
    #[arg(long = "no-completion", hide = true)]
    pub no_completion: bool,

    /// Custom history directory (overrides default XDG location)
    ///
    /// R history will be stored at `{dir}/r.db`, Shell at `{dir}/shell.db`.
    ///
    /// Config: history.dir
    #[arg(
        long = "history-dir",
        value_hint = ValueHint::DirPath,
        env = "ARF_HISTORY_DIR",
        hide_short_help = true,
        value_parser = clap::builder::NonEmptyStringValueParser::new().map(PathBuf::from),
    )]
    pub history_dir: Option<PathBuf>,

    /// Disable history (no history saved or loaded)
    ///
    /// Config: history.disabled
    #[arg(long = "no-history", hide_short_help = true)]
    pub no_history: bool,

    /// Subcommands
    #[command(subcommand)]
    pub command: Option<Commands>,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Generate shell completion scripts
    Completions {
        /// The shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },
    /// Configuration management
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// History management
    History {
        #[command(subcommand)]
        action: HistoryAction,
    },
    /// Interact with a running arf session via IPC
    ///
    /// Evaluate R code, send user input, or query session info in a running
    /// arf instance. The target session must have IPC enabled — via
    /// `arf headless`, `arf --with-ipc`, or the `:ipc start` meta command.
    #[command(after_long_help = "\
Quick start:
  # 1. Start a headless session (or use --with-ipc with the REPL)
  $ arf headless &

  # 2. Check the session is running
  $ arf ipc list

  # 3. Evaluate R code and get structured JSON output
  $ arf ipc eval '1 + 1'

  # 4. Check session status (R version, loaded packages, etc.)
  $ arf ipc session

  # 5. Shut down when done
  $ arf ipc shutdown

All commands output JSON to stdout (pretty-printed on terminal, compact \
when piped). Errors are written to stderr as JSON. Exit codes: \
0 = success, 2 = transport error, 3 = session error, 4 = protocol error.

Session discovery:
  By default, sessions are discovered from the platform cache directory.
  Set ARF_IPC_SESSIONS_DIR to explicitly override the session metadata \
directory for all IPC writers (`arf headless`, `--with-ipc`, `:ipc start`) \
and `arf ipc` readers.")]
    Ipc {
        #[command(subcommand)]
        action: IpcAction,
    },
    /// Run R with IPC server only (no interactive REPL)
    ///
    /// Starts R and an IPC server without the interactive console.
    /// Useful for AI agents that only need IPC access, or for
    /// CI environments where a terminal is not available.
    /// Exit with Ctrl+C or `arf ipc shutdown`.
    #[command(after_long_help = "\
Examples:
  Start headless and evaluate R code:
    $ arf headless &
    # (wait for the server to be ready)
    $ arf ipc eval '1 + 1'

  CI usage with JSON output:
    $ arf headless --json | jq -r .socket_path

  Run with logging to a file:
    $ arf headless --log-file arf.log --pid-file arf.pid

  Use a custom socket path:
    $ arf headless --bind /tmp/my-arf.sock --pid-file arf.pid
    $ arf ipc eval --pid $(cat arf.pid) 'Sys.time()'

  Shut down a headless session:
    $ arf ipc shutdown")]
    Headless {
        /// Path to configuration file
        #[arg(short, long, value_hint = ValueHint::FilePath)]
        config: Option<PathBuf>,

        /// R version to use via rig (overrides r_source config)
        #[arg(long = "with-r-version", conflicts_with = "r_home")]
        r_version: Option<String>,

        /// Explicit R_HOME path (overrides r_source config)
        #[arg(long = "r-home", value_hint = ValueHint::DirPath, conflicts_with = "r_version")]
        r_home: Option<PathBuf>,

        /// Bind IPC socket to a specific path instead of the default.
        /// On Unix, ensure the parent directory is user-private (mode 0700)
        /// to avoid a brief permission window before the socket is restricted.
        ///
        /// Unix: filesystem path (e.g. /tmp/my-arf.sock)
        /// Windows: named pipe path (e.g. \\.\pipe\my-arf)
        // NOTE: FilePath is not ideal on Windows (named pipes aren't filesystem
        // paths), but using cfg_attr to vary the hint per platform would cause
        // shell completion snapshots to differ across machines.
        #[arg(long, value_hint = ValueHint::FilePath)]
        bind: Option<String>,

        /// Write server PID to a file (removed on shutdown)
        #[arg(long = "pid-file", value_hint = ValueHint::FilePath)]
        pid_file: Option<PathBuf>,

        /// Suppress status messages on stderr (IPC path, ready, shutdown)
        #[arg(long)]
        quiet: bool,

        /// Print session info as JSON to stdout when ready
        ///
        /// Outputs a JSON object with pid, socket_path, r_version, etc.
        /// Implies --quiet (suppresses status messages on stderr).
        /// Pretty-printed when stdout is a terminal, compact when piped.
        #[arg(long)]
        json: bool,

        /// Redirect log output to a file instead of stderr
        #[arg(long = "log-file", value_hint = ValueHint::FilePath)]
        log_file: Option<PathBuf>,

        /// Start R in vanilla mode (no init files, no save/restore)
        #[arg(long = "vanilla")]
        vanilla: bool,

        /// [R] Don't read the site and user environment files
        #[arg(long = "no-environ", hide_short_help = true)]
        no_environ: bool,

        /// [R] Don't read the site-wide Rprofile
        #[arg(long = "no-site-file", hide_short_help = true)]
        no_site_file: bool,

        /// [R] Don't read the user's .Rprofile
        #[arg(long = "no-init-file", hide_short_help = true)]
        no_init_file: bool,

        /// [R] Set max number of connections to N
        #[arg(long = "max-connections", hide = true)]
        max_connections: Option<u32>,

        /// [R] Set max size of protect stack to N
        #[arg(long = "max-ppsize", hide = true)]
        max_ppsize: Option<u32>,

        /// Custom history directory (overrides default XDG location)
        ///
        /// History will be stored at `{dir}/r.db`.
        ///
        /// Config: history.dir
        #[arg(
            long = "history-dir",
            value_hint = ValueHint::DirPath,
            env = "ARF_HISTORY_DIR",
            hide_short_help = true,
            value_parser = clap::builder::NonEmptyStringValueParser::new().map(PathBuf::from),
        )]
        history_dir: Option<PathBuf>,

        /// Disable history (no history saved)
        ///
        /// Config: history.disabled
        #[arg(long = "no-history", hide_short_help = true)]
        no_history: bool,

        /// [R] Set min number of fixed size obj's ("cons cells") to N
        #[arg(long = "min-nsize", hide = true)]
        min_nsize: Option<String>,

        /// [R] Set vector heap minimum to N bytes; '4M' = 4 MegaB
        #[arg(long = "min-vsize", hide = true)]
        min_vsize: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum IpcAction {
    /// List active arf sessions as JSON
    ///
    /// Returns a JSON object with a `sessions` array. Each entry contains
    /// pid, r_version, socket_path, cwd, started_at, log_file, and history_session_id.
    /// Returns `{"sessions": []}` when no sessions are running (exit 0).
    #[command(after_long_help = "\
Examples:
  List all sessions:
    $ arf ipc list

  Extract PIDs with jq:
    $ arf ipc list | jq '.sessions[].pid'")]
    List,
    /// Evaluate R code and return captured output as JSON
    ///
    /// Returns a JSON object with stdout, stderr, value, and error fields.
    /// All fields are always present (null when not applicable). In silent
    /// mode (the default), the printed result appears in value rather than
    /// stdout. R evaluation errors are included in the error field with
    /// exit code 0 — they are a normal response, not an IPC failure.
    #[command(after_long_help = "\
Examples:
  Evaluate an expression:
    $ arf ipc eval '1 + 1'

  Run code with a 10-second timeout:
    $ arf ipc eval --timeout 10000 'Sys.sleep(5); 42'

  Also show output in the session (REPL or headless stdout):
    $ arf ipc eval --visible 'cat(\"hello\\n\")'

  Target a specific session when multiple are running:
    $ arf ipc eval --pid 12345 'getwd()'

  Extract the value with jq:
    $ arf ipc eval '1 + 1' | jq -r '.value'")]
    Eval {
        /// R code to evaluate
        code: String,
        /// PID of the target arf session (optional if only one session is running)
        #[arg(long)]
        pid: Option<u32>,
        /// Also show output in the session (REPL or headless stdout)
        #[arg(long)]
        visible: bool,
        /// Timeout in milliseconds for waiting for the response (default: 300000 = 5 minutes).
        /// This does NOT cancel the R evaluation — long-running code keeps R busy after timeout.
        #[arg(long)]
        timeout: Option<u64>,
    },
    /// Send code as user input to a running session
    ///
    /// Unlike `eval`, the code is executed as if the user typed it at the
    /// prompt. Output goes to the session's output streams (the REPL
    /// terminal or headless stdout/log file) and is not captured in the
    /// IPC response. Returns JSON `{"accepted": true}` on success.
    #[command(after_long_help = "\
Examples:
  Send code that appears in the session output:
    $ arf ipc send 'library(dplyr)'

  Target a specific session:
    $ arf ipc send --pid 12345 'print(mtcars)'")]
    Send {
        /// R code to send
        code: String,
        /// PID of the target arf session (optional if only one session is running)
        #[arg(long)]
        pid: Option<u32>,
    },
    /// Get session information as JSON (arf + R environment)
    ///
    /// Returns structured session information including arf version, OS,
    /// log file path (if any), and R environment details (loaded namespaces,
    /// attached packages, library paths, locale, working directory, etc.).
    ///
    /// Unlike `eval "sessionInfo()"`, this returns machine-readable JSON
    /// that can be piped to jq or consumed by AI agents without parsing
    /// human-readable text output. When R is busy, arf-side information
    /// is still returned with `r` set to null and `r_unavailable_reason`
    /// / `hint` fields explaining the situation. The `log_file` field is
    /// null when no dedicated log file is configured (logging to stderr
    /// without redirection). The JSON shape is always consistent — check
    /// `r` for null to determine availability.
    ///
    /// Output is pretty-printed when writing to a terminal, and compact
    /// JSON when piped to another program.
    #[command(after_long_help = "\
Examples:
  Get session info (pretty-printed on terminal):
    $ arf ipc session

  Extract R version with jq:
    $ arf ipc session | jq -r '.r.version'

  Check loaded namespaces:
    $ arf ipc session | jq '.r.loaded_namespaces'")]
    Session {
        /// PID of the target arf session (optional if only one session is running)
        #[arg(long)]
        pid: Option<u32>,
    },
    /// Shut down a running arf headless session (returns JSON `{"accepted": true}`)
    #[command(after_long_help = "\
Examples:
  Shut down the only running session:
    $ arf ipc shutdown

  Shut down a specific session:
    $ arf ipc shutdown --pid 12345")]
    Shutdown {
        /// PID of the target arf session (optional if only one session is running)
        #[arg(long)]
        pid: Option<u32>,
    },
    /// Query command history from a running session
    ///
    /// Returns history entries as JSON, newest first. Output is
    /// pretty-printed when writing to a terminal and compact when piped.
    /// Only completed commands are recorded; a currently executing
    /// command will not appear until it finishes.
    #[command(after_long_help = "\
Examples:
  Show recent history (default 50 entries):
    $ arf ipc history

  Show last 10 entries:
    $ arf ipc history --limit 10

  Search for commands containing 'dplyr':
    $ arf ipc history --grep dplyr

  Filter by working directory:
    $ arf ipc history --cwd /path/to/project

  Show entries since a date:
    $ arf ipc history --since 2026-03-29

  Include history from all sessions (not just current):
    $ arf ipc history --all-sessions

  Combine filters:
    $ arf ipc history --grep 'library' --limit 20

  Extract commands with jq:
    $ arf ipc history | jq -r '.entries[].command'")]
    History {
        /// Maximum number of entries to return (must be positive)
        #[arg(long, default_value = "50", value_parser = clap::value_parser!(i64).range(1..))]
        limit: i64,
        /// Include entries from all sessions, not just the current one
        #[arg(long)]
        all_sessions: bool,
        /// Filter entries by exact working directory
        #[arg(long)]
        cwd: Option<String>,
        /// Filter entries whose command contains this substring
        #[arg(long)]
        grep: Option<String>,
        /// Only return entries after this timestamp (RFC 3339 or YYYY-MM-DD)
        #[arg(long)]
        since: Option<String>,
        /// PID of the target arf session (optional if only one session is running)
        #[arg(long)]
        pid: Option<u32>,
    },
}

#[derive(Subcommand, Debug)]
pub enum HistoryAction {
    /// Display history database schema and example R code
    Schema,
    /// Import history from another source (experimental)
    ///
    /// Import command history from radian, R's native .Rhistory, or another arf database.
    /// This is an experimental feature and the format may change in future versions.
    Import {
        /// Source format to import from
        #[arg(long, value_enum)]
        from: ImportSource,

        /// Path to the history file/database to import.
        /// Defaults: radian=~/.radian_history, r=.Rhistory, arf=history.dir/r.db
        #[arg(long, value_hint = ValueHint::FilePath)]
        file: Option<PathBuf>,

        /// Override hostname for imported entries.
        /// Marks entries to distinguish them from native arf history
        #[arg(long)]
        hostname: Option<String>,

        /// Perform a dry run without actually importing
        #[arg(long)]
        dry_run: bool,

        /// Import duplicate entries instead of skipping them.
        /// By default, entries that already exist in the target database
        /// are skipped (anti-join on command text and timestamp).
        #[arg(long)]
        import_duplicates: bool,

        /// Force unified export file mode (imports both R and shell history).
        ///
        /// By default, the file format is auto-detected by filename:
        ///   - 'r.db' or 'shell.db' → single-database mode (one history type)
        ///   - Other names (e.g., 'backup.db') → unified mode (both history types)
        ///
        /// Use this flag to force unified mode even for files named r.db/shell.db.
        #[arg(long)]
        unified: bool,

        /// Table name for R history when importing from unified export file
        #[arg(long, default_value = "r")]
        r_table: String,

        /// Table name for shell history when importing from unified export file
        #[arg(long, default_value = "shell")]
        shell_table: String,
    },
    /// Export history to a unified SQLite file (experimental)
    ///
    /// Export both R and shell history to a single SQLite file.
    /// This can be used as a backup or to transfer history between machines.
    Export {
        /// Path to the output SQLite file
        #[arg(long, value_hint = ValueHint::FilePath)]
        file: PathBuf,

        /// Table name for R history in the output file
        #[arg(long, default_value = "r")]
        r_table: String,

        /// Table name for shell history in the output file
        #[arg(long, default_value = "shell")]
        shell_table: String,
    },
}

/// Source format for history import.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ImportSource {
    /// radian history file (~/.radian_history)
    Radian,
    /// R native history file (.Rhistory)
    R,
    /// Another arf SQLite history database
    Arf,
}

#[derive(Subcommand, Debug)]
pub enum ConfigAction {
    /// Generate a default configuration file
    Init {
        /// Overwrite existing configuration file
        #[arg(long, short)]
        force: bool,
    },
    /// Validate the configuration file
    ///
    /// Check the config file for syntax errors and report any issues.
    /// Exit code 0 means valid, non-zero means file not found or has errors.
    Check {
        /// Path to configuration file to check (defaults to XDG config location)
        #[arg(short, long, value_hint = ValueHint::FilePath)]
        config: Option<PathBuf>,
    },
}

/// Builder for R initialization arguments, shared between REPL and headless modes.
///
/// Headless mode always uses `--no-save --no-restore-data` (save/restore are
/// only meaningful for interactive sessions), while REPL mode supports
/// `--save` and `--restore`.
pub struct RArgsBuilder<'a> {
    pub vanilla: bool,
    pub no_environ: bool,
    pub no_site_file: bool,
    pub no_init_file: bool,
    /// Use `--save` instead of `--no-save`. Only relevant for REPL mode.
    pub save: bool,
    /// Use `--restore` instead of `--no-restore-data`. Only relevant for REPL mode.
    pub restore: bool,
    pub max_connections: Option<u32>,
    pub max_ppsize: Option<u32>,
    pub min_nsize: Option<&'a str>,
    pub min_vsize: Option<&'a str>,
}

impl RArgsBuilder<'_> {
    /// Build the R initialization arguments vector.
    pub fn build(&self) -> Vec<String> {
        let mut args = Vec::new();

        // Always add --quiet (we handle our own banner)
        args.push("--quiet".to_string());

        // --vanilla combines: --no-environ --no-site-file --no-init-file --no-save --no-restore
        if self.vanilla {
            args.push("--no-environ".to_string());
            args.push("--no-site-file".to_string());
            args.push("--no-init-file".to_string());
            args.push("--no-save".to_string());
            args.push("--no-restore-data".to_string());
        } else {
            if self.no_environ {
                args.push("--no-environ".to_string());
            }
            if self.no_site_file {
                args.push("--no-site-file".to_string());
            }
            if self.no_init_file {
                args.push("--no-init-file".to_string());
            }

            // Save/restore flags
            // Default behavior is --no-save --no-restore (like radian)
            if self.save {
                args.push("--save".to_string());
            } else {
                args.push("--no-save".to_string());
            }

            if self.restore {
                args.push("--restore".to_string());
            } else {
                args.push("--no-restore-data".to_string());
            }
        }

        // Memory tuning flags - forward to R
        if let Some(n) = self.max_connections {
            args.push(format!("--max-connections={n}"));
        }
        if let Some(n) = self.max_ppsize {
            args.push(format!("--max-ppsize={n}"));
        }
        if let Some(n) = self.min_nsize {
            args.push(format!("--min-nsize={n}"));
        }
        if let Some(n) = self.min_vsize {
            args.push(format!("--min-vsize={n}"));
        }

        // Always interactive (Unix only - Windows uses Rstart.r_interactive)
        #[cfg(unix)]
        args.push("--interactive".to_string());

        args
    }
}

impl Cli {
    /// Print shell completions to stdout.
    ///
    /// If rig is available, this will include completion values for `--with-r-version`
    /// based on installed R versions.
    ///
    /// TODO: Migrate to dynamic completions using clap_complete's CompleteEnv
    /// when it stabilizes, so completions are generated at TAB-press time
    /// rather than requiring regeneration after installing new R versions.
    pub fn print_completions(shell: Shell) {
        let mut cmd = Cli::command();

        // Inject R version completions from rig if available
        if let Some(possible_values) = Self::get_r_version_completions() {
            // Leak memory for 'static lifetime - acceptable since completions run once and exit
            let leaked: &'static [String] = Box::leak(possible_values.into_boxed_slice());
            let refs: Vec<&'static str> = leaked.iter().map(|s| s.as_str()).collect();
            cmd = cmd.mut_arg("r_version", |arg| {
                arg.value_parser(PossibleValuesParser::new(refs))
            });
        }

        generate(shell, &mut cmd, "arf", &mut io::stdout());
    }

    /// Get possible R version values from rig for shell completion.
    ///
    /// Returns None if rig is unavailable or has no versions installed.
    fn get_r_version_completions() -> Option<Vec<String>> {
        if !rig::rig_available() {
            return None;
        }

        let versions = rig::list_versions().ok()?;
        if versions.is_empty() {
            return None;
        }

        let mut values = vec!["default".to_string()];

        for v in &versions {
            // Add version name (e.g., "4.5.2")
            values.push(v.name.clone());
            // Add aliases (e.g., "release", "oldrel")
            for alias in &v.aliases {
                if !values.contains(alias) {
                    values.push(alias.clone());
                }
            }
        }

        Some(values)
    }

    /// Returns the script file path from `-f`/`--file`.
    pub fn script_file(&self) -> Option<&PathBuf> {
        self.file.as_ref()
    }

    /// Generate R initialization arguments based on CLI flags.
    ///
    /// Returns a vector of R arguments like ["--quiet", "--no-save", "--no-restore"].
    pub fn r_args(&self) -> Vec<String> {
        RArgsBuilder {
            vanilla: self.vanilla,
            no_environ: self.no_environ,
            no_site_file: self.no_site_file,
            no_init_file: self.no_init_file,
            save: self.save,
            restore: self.restore_data || self.restore,
            max_connections: self.max_connections,
            max_ppsize: self.max_ppsize,
            min_nsize: self.min_nsize.as_deref(),
            min_vsize: self.min_vsize.as_deref(),
        }
        .build()
    }

    /// Generate shell completions as a string for testing.
    #[cfg(test)]
    fn generate_completions_string(shell: Shell) -> String {
        let mut cmd = Cli::command();
        let mut buf = Vec::new();
        generate(shell, &mut cmd, "arf", &mut buf);
        String::from_utf8(buf).expect("Completions should be valid UTF-8")
    }

    /// Generate help output for a subcommand path for testing.
    #[cfg(test)]
    fn generate_help_string(subcommand_path: &[&str]) -> String {
        let mut cmd = Cli::command();
        for &name in subcommand_path {
            cmd = cmd
                .find_subcommand(name)
                .expect("Subcommand not found")
                .clone();
        }
        cmd.render_long_help().to_string()
    }
}

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

    #[test]
    fn test_completions_bash_snapshot() {
        let completions = Cli::generate_completions_string(Shell::Bash);
        insta::assert_snapshot!("completions_bash", completions);
    }

    #[test]
    fn test_completions_zsh_snapshot() {
        let completions = Cli::generate_completions_string(Shell::Zsh);
        insta::assert_snapshot!("completions_zsh", completions);
    }

    #[test]
    fn test_completions_fish_snapshot() {
        let completions = Cli::generate_completions_string(Shell::Fish);
        insta::assert_snapshot!("completions_fish", completions);
    }

    #[test]
    fn test_completions_powershell_snapshot() {
        let completions = Cli::generate_completions_string(Shell::PowerShell);
        insta::assert_snapshot!("completions_powershell", completions);
    }

    #[test]
    fn test_help_history_import_snapshot() {
        let help = Cli::generate_help_string(&["history", "import"]);
        insta::assert_snapshot!("help_history_import", help);
    }

    #[test]
    fn test_help_history_export_snapshot() {
        let help = Cli::generate_help_string(&["history", "export"]);
        insta::assert_snapshot!("help_history_export", help);
    }

    #[test]
    fn test_help_long_snapshot() {
        let help = Cli::generate_help_string(&[]);
        insta::assert_snapshot!("help_long", help);
    }

    #[test]
    fn test_history_dir_rejects_empty_string() {
        let result = Cli::try_parse_from(["arf", "--history-dir", ""]);
        assert!(result.is_err(), "empty --history-dir should be rejected");
    }
}