arf-console 0.3.4

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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
//! arf: A cross-platform R console written in Rust.

mod cli;
mod completion;
mod config;
mod console_mode;
mod editor;
mod external;
mod fuzzy;
mod highlighter;
mod history;
mod ipc;
mod pager;
pub(crate) mod r_parser;
mod repl;
mod traps;

#[cfg(test)]
mod test_utils;

use anyhow::{Context, Result};
use clap::{CommandFactory, Parser};
use cli::{Cli, Commands, ConfigAction, HistoryAction, ImportSource, IpcAction, RArgsBuilder};
use config::{
    Config, ConfigLoadError, ConfigStatus, RSource, RSourceMode, RSourceStatus, config_file_path,
    ensure_directories, init_config, load_config, load_config_from_path, mask_home_path,
};
use ipc::session::SessionInfo;
use reedline::Reedline;
use repl::Repl;
use serde::Serialize;
use std::fs;

/// JSON output for `arf headless --json`.
///
/// Contains session connection info and any warnings collected during startup.
/// All keys are always present in the JSON output; `r_version`, `log_file`,
/// and `history_session_id` may be `null`. `warnings` is an array that may be
/// empty.
#[derive(Debug, Serialize)]
struct HeadlessInfo {
    pid: u32,
    socket_path: String,
    r_version: Option<String>,
    cwd: String,
    started_at: String,
    log_file: Option<String>,
    history_session_id: Option<i64>,
    warnings: Vec<String>,
}

impl HeadlessInfo {
    fn from_session(session: &SessionInfo, warnings: Vec<String>) -> Self {
        // Normalize empty/whitespace-only R version to None so JSON shows null
        let r_version = session
            .r_version
            .as_deref()
            .filter(|s| !s.trim().is_empty())
            .map(|s| s.to_string());

        Self {
            pid: session.pid,
            socket_path: session.socket_path.clone(),
            r_version,
            cwd: session.cwd.clone(),
            started_at: session.started_at.clone(),
            log_file: session.log_file.clone(),
            history_session_id: session.history_session_id,
            warnings,
        }
    }
}
#[cfg(windows)]
use std::path::PathBuf;
use std::process::ExitCode;

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("Error: {:#}", e);
            ExitCode::FAILURE
        }
    }
}

/// Initialize logging.
///
/// When `log_file` is `Some`, log output is written to the specified file
/// instead of stderr. This is useful for daemon deployments where stderr
/// may not be monitored.
///
/// When `redirect_stderr` is `true` and a log file is provided, the process's
/// stderr file descriptor is also redirected to the log file via `dup2`. This
/// ensures that *all* stderr output — including `eprintln!()` calls, R's
/// `WriteConsoleEx` default output (e.g., from graphics device callbacks), and
/// any other code writing directly to fd 2 — goes to the log file instead of
/// the terminal.
fn init_logger(log_file: Option<&std::path::Path>, redirect_stderr: bool) {
    let mut builder = env_logger::Builder::from_default_env();
    if let Some(path) = log_file {
        let mut opts = std::fs::OpenOptions::new();
        opts.create(true).append(true);
        // Restrict log file permissions on Unix (logs may contain sensitive data)
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
            // Prevent following symlinks when opening the log file to avoid
            // appending logs to an unintended target via a symlink.
            opts.custom_flags(libc::O_NOFOLLOW);
        }
        match opts.open(path) {
            Ok(file) => {
                // Ensure restricted permissions even if the file already existed
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    let perms = std::fs::Permissions::from_mode(0o600);
                    // Use fd-based set_permissions (fchmod) to avoid TOCTOU
                    // symlink race with path-based std::fs::set_permissions.
                    if let Err(e) = file.set_permissions(perms) {
                        eprintln!(
                            "Warning: could not set permissions on log file {}: {e}",
                            path.display()
                        );
                    }
                }

                // Redirect process stderr to the log file so that all output
                // (not just log::* macros) is captured. This borrows `file`
                // before it is moved into env_logger, but the dup2'd fd is
                // independent of the original.
                if redirect_stderr {
                    redirect_stderr_to_file(&file);
                }

                builder.target(env_logger::Target::Pipe(Box::new(file)));
            }
            Err(e) => {
                eprintln!("Warning: could not open log file {}: {e}", path.display());
                eprintln!("         Falling back to stderr.");
            }
        }
    }
    builder.init();
}

/// Redirect the process's stderr file descriptor to the given file.
///
/// Uses `dup2` to make fd 2 (stderr) point to the same file description as
/// the provided file. After this call, `eprintln!()`, R's `WriteConsoleEx`
/// default output path, and any other code writing to stderr will write to
/// the file instead of the terminal.
#[cfg(unix)]
fn redirect_stderr_to_file(file: &std::fs::File) {
    use std::os::unix::io::AsRawFd;
    let fd = file.as_raw_fd();
    // Safety: dup2 is safe with valid file descriptors.
    let ret = unsafe { libc::dup2(fd, libc::STDERR_FILENO) };
    if ret == -1 {
        // Use eprintln! because this runs before the logger is initialized
        // (builder.init() hasn't been called yet). If dup2 failed, stderr
        // is still connected to the original terminal, so eprintln! works.
        eprintln!(
            "Warning: failed to redirect stderr to log file: {}",
            std::io::Error::last_os_error()
        );
    }
}

/// Redirect the C runtime's stderr fd (fd 2) to the given file.
///
/// The Win32 `STD_ERROR_HANDLE` is left unchanged; only the CRT fd used by
/// `eprintln!()` and similar Rust macros is redirected. Uses `DuplicateHandle`
/// to create an independent OS handle before handing it to the CRT.
#[cfg(windows)]
fn redirect_stderr_to_file(file: &std::fs::File) {
    use std::os::windows::io::AsRawHandle;

    // Duplicate the OS handle so the C runtime and the `File` object own
    // independent handles. Without this, `_open_osfhandle` transfers ownership
    // to the C runtime while `File` retains the same value, causing a
    // double-close when both are dropped.
    let mut dup_handle: windows_sys::Win32::Foundation::HANDLE = std::ptr::null_mut();
    let cur_proc = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcess() };
    let ok = unsafe {
        windows_sys::Win32::Foundation::DuplicateHandle(
            cur_proc,
            file.as_raw_handle() as _,
            cur_proc,
            &mut dup_handle,
            0,
            0, // not inheritable
            windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS,
        )
    };
    if ok == 0 {
        eprintln!(
            "Warning: failed to duplicate handle for stderr redirect: {}",
            std::io::Error::last_os_error()
        );
        return;
    }

    // Convert the duplicated OS handle to a C runtime fd.
    // Use O_WRONLY | O_APPEND to match the append-mode log file; omitting an
    // explicit access mode can leave fd 2 effectively read-only on some CRTs,
    // causing CRT writes to stderr to fail.
    // MSVC CRT: _O_WRONLY = 0x0001, _O_APPEND = 0x0008
    const O_WRONLY: libc::c_int = 0x0001;
    let new_fd =
        unsafe { libc::open_osfhandle(dup_handle as libc::intptr_t, O_WRONLY | libc::O_APPEND) };
    if new_fd == -1 {
        eprintln!("Warning: failed to convert handle for stderr redirect");
        // Clean up the duplicated handle since open_osfhandle failed.
        unsafe {
            windows_sys::Win32::Foundation::CloseHandle(dup_handle);
        }
        return;
    }

    // Redirect C runtime's fd 2 (stderr) to the new fd.
    if unsafe { libc::dup2(new_fd, 2) } == -1 {
        eprintln!(
            "Warning: failed to redirect stderr to log file: {}",
            std::io::Error::last_os_error()
        );
    }

    // Close new_fd — dup2 gave fd 2 its own reference to the underlying
    // handle, so new_fd is no longer needed.
    unsafe {
        libc::close(new_fd);
    }
}

/// Write the current process ID to a file.
///
/// The file is created with restricted permissions (0600 on Unix) and is
/// intended to be removed on shutdown by the caller.
fn write_pid_file(path: &std::path::Path) -> Result<()> {
    let pid = std::process::id().to_string();
    // Use create_new to fail if the file already exists, avoiding overwrite
    // of unrelated files or symlink-following attacks.
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(path)
            .with_context(|| format!("Failed to create PID file: {}", path.display()))?;
        file.write_all(pid.as_bytes())
            .with_context(|| format!("Failed to write PID file: {}", path.display()))?;
    }
    #[cfg(not(unix))]
    {
        // create_new on Windows also fails if the file exists
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)
            .and_then(|mut f| {
                use std::io::Write;
                f.write_all(pid.as_bytes())
            })
            .with_context(|| format!("Failed to create PID file: {}", path.display()))?;
    }
    log::info!("PID file written: {}", path.display());
    Ok(())
}

fn run() -> Result<()> {
    // Parse command-line arguments first, then initialize the logger exactly
    // once based on the parsed command. This avoids the fragile pre-parse
    // detection that could miss global options before the subcommand.
    let cli = Cli::parse();

    // Reject combinations of -f/--file or -e/--eval with a subcommand.
    // clap cannot enforce this via conflicts_with because subcommand fields are
    // not referenceable as argument IDs in the derive API.
    if (cli.eval.is_some() || cli.file.is_some()) && cli.command.is_some() {
        let flag = if cli.eval.is_some() {
            "--eval"
        } else {
            "--file"
        };
        let subcommand = match &cli.command {
            Some(Commands::Completions { .. }) => "completions",
            Some(Commands::Config { .. }) => "config",
            Some(Commands::History { .. }) => "history",
            Some(Commands::Ipc { .. }) => "ipc",
            Some(Commands::Headless { .. }) => "headless",
            None => unreachable!(),
        };
        Cli::command()
            .error(
                clap::error::ErrorKind::ArgumentConflict,
                format!("the argument '{flag}' cannot be used with subcommand '{subcommand}'"),
            )
            .exit();
    }

    // Extract log_file from headless command (if applicable) and initialize
    // the logger once. Non-headless modes use the default stderr target.
    // In headless mode, also redirect stderr to the log file so that all
    // output (R device callbacks, eprintln!, etc.) is captured.
    let (log_file, is_headless) = match &cli.command {
        Some(Commands::Headless { log_file, .. }) => (log_file.as_deref(), true),
        _ => (None, false),
    };
    init_logger(log_file, is_headless);

    // Install signal handlers for fatal signals (SIGSEGV, SIGILL, SIGBUS).
    // This prevents the process from hanging when R encounters a segmentation fault.
    // Must be called after init_logger so trap handlers can log.
    traps::register_trap_handlers();

    // Handle subcommands first
    match &cli.command {
        Some(Commands::Completions { shell }) => {
            Cli::print_completions(*shell);
            return Ok(());
        }
        Some(Commands::Config { action }) => {
            return handle_config_command(action);
        }
        Some(Commands::History { action }) => {
            return handle_history_command(action, cli.config.as_ref(), cli.history_dir.as_ref());
        }
        Some(Commands::Ipc { action }) => {
            handle_ipc_command(action);
            return Ok(());
        }
        Some(Commands::Headless {
            config,
            r_version,
            r_home,
            bind,
            pid_file,
            quiet,
            json,
            log_file,
            history_dir,
            no_history,
            vanilla,
            no_environ,
            no_site_file,
            no_init_file,
            max_connections,
            max_ppsize,
            min_nsize,
            min_vsize,
        }) => {
            let r_args_builder = RArgsBuilder {
                vanilla: *vanilla,
                no_environ: *no_environ,
                no_site_file: *no_site_file,
                no_init_file: *no_init_file,
                save: false,
                restore: false,
                max_connections: *max_connections,
                max_ppsize: *max_ppsize,
                min_nsize: min_nsize.as_deref(),
                min_vsize: min_vsize.as_deref(),
            };
            return run_headless(
                config.as_ref(),
                r_home.as_deref(),
                r_version.as_deref(),
                r_args_builder,
                bind.as_deref(),
                pid_file.as_deref(),
                *quiet,
                *json,
                log_file.as_deref(),
                history_dir.as_deref(),
                *no_history,
            );
        }
        None => {}
    }

    // Check if we're in script execution mode
    let script_mode = cli.eval.is_some() || cli.script_file().is_some();

    if script_mode {
        // Script execution mode - no REPL, just run code and exit
        return run_script(&cli);
    }

    log::info!("Starting arf");

    // Save the parent shell's console input mode before reedline/crossterm can
    // enable Windows VT input. R's quit() may bypass Rust destructors, so the
    // guard also registers an atexit fallback on Windows.
    let _console_mode_guard = console_mode::ConsoleModeGuard::install();

    // Ensure XDG directories exist
    ensure_directories()?;

    // Load configuration (from file or default)
    // Track the config path for :info command display
    let (mut config, config_path, config_status) = load_config_with_fallback(&cli);
    log::debug!("Loaded config: {:?}", config);

    // Apply CLI overrides
    if cli.reprex {
        config.startup.mode.reprex = true;
    }
    if cli.auto_format {
        if !external::formatter::is_formatter_available() {
            anyhow::bail!(
                "Cannot enable auto-format: Air CLI ('air' command) not found in PATH.\n\
                 Install Air CLI from https://github.com/posit-dev/air"
            );
        }
        config.startup.mode.autoformat = true;
    }
    if cli.no_banner {
        config.startup.show_banner = false;
    }
    if cli.no_auto_match {
        config.editor.auto_match = false;
    }
    if cli.no_completion {
        config.completion.enabled = false;
    }

    // History configuration: CLI flag overrides default XDG location
    if cli.no_history {
        config.history.disabled = true;
    } else if let Some(history_dir) = &cli.history_dir {
        config.history.dir = Some(history_dir.clone());
    }

    // Warn if auto-format is enabled (via config) but Air CLI is not available
    if config.startup.mode.autoformat
        && !cli.auto_format
        && !external::formatter::is_formatter_available()
    {
        eprintln!(
            "Warning: Auto-format is enabled in config but Air CLI ('air' command) not found in PATH."
        );
        eprintln!(
            "         Auto-format has been disabled. Install Air CLI from https://github.com/posit-dev/air"
        );
        config.startup.mode.autoformat = false;
    }

    // Set up R based on r_source config (with optional CLI override)
    let r_source_status = setup_r(
        &config.startup.r_source,
        cli.r_home.as_deref(),
        cli.r_version.as_deref(),
    )?;
    log::debug!("R source status: {:?}", r_source_status);

    // Ensure LD_LIBRARY_PATH includes R library directory.
    // This may re-exec the current process if the path needs updating.
    if let Err(e) = arf_libr::ensure_ld_library_path() {
        log::warn!("Could not set LD_LIBRARY_PATH: {}", e);
    }

    // Generate R initialization arguments from CLI flags
    let r_args = cli.r_args();
    let r_args_refs: Vec<&str> = r_args.iter().map(|s| s.as_str()).collect();
    log::debug!("R args: {:?}", r_args);

    // Initialize R with CLI-specified flags
    log::info!("Initializing R...");
    #[allow(unused_variables)]
    let r_initialized = unsafe {
        match arf_libr::initialize_r_with_args(&r_args_refs) {
            Ok(()) => {
                log::info!("R initialized successfully");
                true
            }
            Err(e) => {
                eprintln!("Warning: Failed to initialize R: {}", e);
                eprintln!("R evaluation will not be available.");
                eprintln!("Make sure R is installed and R_HOME is set correctly.\n");
                false
            }
        }
    };

    // Source R profile files after R initialization (Windows only)
    // On Windows, R's built-in profile loading is disabled during initialization
    // (load_init_file = R_FALSE in arf-libr/src/sys.rs), so we must manually
    // source .Rprofile files here. On Unix, R handles this automatically.
    #[cfg(windows)]
    if r_initialized {
        source_r_profiles(&r_args);
    }

    let session_id = create_session_id(&config);
    let session_id_raw = session_id.map(i64::from);

    // Register history DB path for IPC history queries.
    // Note: the DB file may not exist yet at this point (first run); that's OK
    // because SqliteBackedHistory::with_file creates it on open. In the REPL
    // path, reedline opens the DB later in Repl::run_*, which also creates it.
    if !config.history.disabled {
        let history_dir = config.history.dir.clone().or_else(config::history_dir);
        if let Some(dir) = history_dir {
            ipc::set_history_db_info(dir.join("r.db"), session_id);
        }
    }

    // Start IPC server if requested.
    //
    // NOTE: The IPC server is started before history databases are opened (which
    // happens inside `Repl::run_*`).  This means there is a brief window where
    // the on-disk session file advertises a non-null `history_session_id` even
    // though history has not been confirmed yet.  If history initialization later
    // fails, `clear_history_session_id()` is called to set it back to `null`.
    // In practice the window is negligibly short (milliseconds).
    if cli.with_ipc {
        match ipc::start_server(None, None, session_id_raw) {
            Ok(session) => {
                log::info!("IPC server started on {}", session.socket_path);
            }
            Err(e) => {
                eprintln!("Warning: Failed to start IPC server: {}", e);
            }
        }
    }

    // Create and run the REPL
    let mut repl = Repl::new(
        config,
        config_path,
        config_status,
        r_source_status,
        session_id,
    )?;
    let repl_result = repl.run();

    // Cleanup IPC server on exit (idempotent — also covers :ipc start).
    // Called before propagating repl errors to ensure socket/session cleanup.
    ipc::stop_server();

    repl_result
}

/// Load configuration with fallback to defaults on error.
///
/// Prints a warning to stderr if the config file has errors.
/// Returns `(config, config_path, config_status)`.
fn load_config_with_fallback(cli: &Cli) -> (Config, Option<std::path::PathBuf>, ConfigStatus) {
    let (result, config_path) = if let Some(path) = &cli.config {
        (load_config_from_path(path), Some(path.clone()))
    } else {
        let default_path = config_file_path();
        (load_config(), default_path)
    };

    match result {
        Ok(config) => (config, config_path, ConfigStatus::Ok),
        Err(e) => {
            let (raw_path, masked_path, source_msg, status) = match &e {
                ConfigLoadError::Read { path, source } => (
                    path.display().to_string(),
                    mask_home_path(path),
                    source.to_string(),
                    ConfigStatus::ReadError,
                ),
                ConfigLoadError::Parse { path, source } => (
                    path.display().to_string(),
                    mask_home_path(path),
                    source.to_string(),
                    ConfigStatus::ParseError,
                ),
            };
            eprintln!(
                "Warning: Failed to load config from {}: {}",
                masked_path, source_msg
            );
            eprintln!(
                "         Using default configuration. Run `arf config check` to see details."
            );
            // Log with unmasked path for debugging
            log::warn!("Config load error for {}: {}", raw_path, source_msg);
            (Config::default(), config_path, status)
        }
    }
}

/// Load config with a warning on error, falling back to defaults.
///
/// Used by subcommands (history, script) where config loading is not the
/// primary operation but errors should still be visible.
fn load_config_or_warn(config_path: Option<&std::path::PathBuf>) -> Config {
    let result = if let Some(path) = config_path {
        load_config_from_path(path)
    } else {
        load_config()
    };
    match result {
        Ok(config) => config,
        Err(e) => {
            let (path_display, source_msg) = match &e {
                ConfigLoadError::Read { path, source } => {
                    (mask_home_path(path), source.to_string())
                }
                ConfigLoadError::Parse { path, source } => {
                    (mask_home_path(path), source.to_string())
                }
            };
            eprintln!(
                "Warning: Failed to load config from {}: {}",
                path_display, source_msg
            );
            eprintln!("         Using default configuration.");
            Config::default()
        }
    }
}

/// Load config, collecting warnings into a buffer instead of printing to stderr.
///
/// Used by `--json` mode to include config warnings in the JSON output.
fn load_config_collecting_warnings(
    config_path: Option<&std::path::PathBuf>,
    warnings: &mut Vec<String>,
) -> Config {
    let result = if let Some(path) = config_path {
        load_config_from_path(path)
    } else {
        load_config()
    };
    match result {
        Ok(config) => config,
        Err(e) => {
            let (path_display, source_msg) = match &e {
                ConfigLoadError::Read { path, source } => {
                    (mask_home_path(path), source.to_string())
                }
                ConfigLoadError::Parse { path, source } => {
                    (mask_home_path(path), source.to_string())
                }
            };
            warnings.push(format!(
                "Failed to load config from {path_display}: {source_msg}. Using default configuration."
            ));
            Config::default()
        }
    }
}

/// Run in headless mode: R + IPC server, no interactive REPL.
///
/// Initializes R, starts the IPC server, and enters a polling loop.
/// The loop processes IPC requests and R events until interrupted
/// by Ctrl+C or a shutdown signal.
#[allow(clippy::too_many_arguments)]
fn run_headless(
    config_path: Option<&std::path::PathBuf>,
    r_home: Option<&std::path::Path>,
    r_version: Option<&str>,
    r_args_builder: RArgsBuilder<'_>,
    bind: Option<&str>,
    pid_file: Option<&std::path::Path>,
    quiet: bool,
    json: bool,
    log_file: Option<&std::path::Path>,
    cli_history_dir: Option<&std::path::Path>,
    no_history: bool,
) -> Result<()> {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    // --json implies --quiet: suppress status messages on stderr since
    // all relevant info is in the JSON output on stdout.
    let quiet = quiet || json;

    log::info!("Starting arf in headless mode");

    // Collect warnings for --json output instead of printing to stderr
    let mut warnings: Vec<String> = Vec::new();

    // Load config for r_source resolution
    let mut config = if json {
        load_config_collecting_warnings(config_path, &mut warnings)
    } else {
        load_config_or_warn(config_path)
    };

    // Set up R
    setup_r(&config.startup.r_source, r_home, r_version)?;

    // Ensure LD_LIBRARY_PATH includes R library directory
    if let Err(e) = arf_libr::ensure_ld_library_path() {
        log::warn!("Could not set LD_LIBRARY_PATH: {}", e);
    }

    // Generate R initialization arguments
    let r_args = r_args_builder.build();
    let r_args_refs: Vec<&str> = r_args.iter().map(|s| s.as_str()).collect();

    // Initialize R
    unsafe {
        arf_libr::initialize_r_with_args(&r_args_refs).context("Failed to initialize R")?;
    }

    // Source R profile files (Windows only)
    #[cfg(windows)]
    source_r_profiles(&r_args);

    // Configure R options for headless operation:
    // - Redirect pager output (help, file.show) to stdout so it gets captured
    //   by evaluate_with_capture instead of spawning an interactive pager (less)
    // - Force plain-text help (`options(help_type = "text")`) so help output
    //   is printable/capturable instead of opening HTML or other rich viewers
    // - Disable interactive browsers (`options(browser = ...)`) so R does not
    //   attempt to launch a GUI/web browser in headless environments
    // - Set default graphics device to file-based (png/pdf) instead of X11
    //   to avoid DISPLAY-related errors or hangs in headless environments
    configure_headless_r_options()?;

    // Set up shutdown flag (shared between Ctrl+C handler and IPC shutdown method)
    let shutdown = Arc::new(AtomicBool::new(false));
    ipc::set_headless_shutdown(shutdown.clone());

    // Apply CLI history overrides (same logic as the REPL path in main())
    if no_history {
        config.history.disabled = true;
    } else if let Some(history_dir) = cli_history_dir {
        config.history.dir = Some(history_dir.to_path_buf());
    }

    // Initialize history for headless mode (same SQLite database as the REPL).
    // Only advertise history_session_id to IPC if the backend was actually opened.
    let session_id = create_session_id(&config);
    let mut session_id_raw = None;
    if let Some(sid) = session_id {
        let history_path = {
            let dir = config.history.dir.clone().or_else(config::history_dir);
            dir.map(|d| d.join("r.db"))
        };
        if let Some(path) = history_path {
            match reedline::SqliteBackedHistory::with_file(
                path.clone(),
                Some(sid),
                Some(chrono::Utc::now()),
            ) {
                Ok(history) => {
                    ipc::set_headless_history(history);
                    ipc::set_history_db_info(path.clone(), Some(sid));
                    session_id_raw = Some(i64::from(sid));
                    log::info!("Headless history enabled: {}", path.display());
                }
                Err(e) => {
                    log::warn!("Failed to open history database {}: {}", path.display(), e);
                }
            }
        }
    }

    // Start IPC server (with optional custom bind path)
    let log_file_str = log_file.map(|p| {
        // Convert to absolute path so IPC clients can locate the file
        // regardless of their own working directory. Use std::path::absolute
        // instead of canonicalize because the file may not exist yet at this
        // point (the logger creates it).
        std::path::absolute(p)
            .unwrap_or_else(|_| p.to_path_buf())
            .display()
            .to_string()
    });
    let session = ipc::start_server(bind, log_file_str, session_id_raw)
        .context("Failed to start IPC server")?;
    if !quiet {
        eprintln!("IPC server listening on: {}", session.socket_path);
    }

    // Write PID file if requested
    if let Some(pid_path) = pid_file
        && let Err(e) = write_pid_file(pid_path)
    {
        // Do not attempt to remove the PID file here: write_pid_file uses
        // create_new and may have failed before creating it (e.g. AlreadyExists),
        // so pid_path may refer to a pre-existing user-managed file.

        // Stop IPC server to avoid leaving a stale socket/session behind.
        ipc::stop_server();

        return Err(e);
    }

    // Set up signal handler for graceful shutdown.
    // With the "termination" feature, ctrlc also handles SIGTERM and SIGHUP,
    // enabling clean shutdown from systemd stop, docker stop, nohup hangup, etc.
    let shutdown_signal = shutdown.clone();
    if let Err(e) = ctrlc::set_handler(move || {
        shutdown_signal.store(true, Ordering::Release);
    }) {
        log::warn!("Could not set Ctrl+C handler: {}", e);
    }

    // Mark R as ready for IPC requests
    ipc::set_r_at_prompt(true);

    if json {
        // Output session info as JSON to stdout
        let output = HeadlessInfo::from_session(&session, warnings);
        let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
        let json_str = if is_tty {
            serde_json::to_string_pretty(&output)
        } else {
            serde_json::to_string(&output)
        }
        .context("Failed to serialize session info")?;
        // Use writeln + flush instead of println to ensure the JSON is
        // delivered immediately when stdout is piped (non-TTY). This is the
        // readiness signal for CI scripts waiting on the output.
        use std::io::Write;
        let mut stdout = std::io::stdout().lock();
        writeln!(stdout, "{json_str}").context("Failed to write session info to stdout")?;
        stdout
            .flush()
            .context("Failed to flush session info to stdout")?;
    } else if !quiet {
        eprintln!("Headless mode ready. Press Ctrl+C to exit.");
    }

    // Main event loop
    while !shutdown.load(Ordering::Acquire) {
        // Process IPC requests
        let had_work = ipc::headless_poll_and_process();

        // Process R events (timers, background tasks, etc.)
        arf_libr::process_r_events();

        // Sleep to avoid busy loop — shorter if we had work (more may be coming)
        if had_work {
            std::thread::sleep(std::time::Duration::from_millis(1));
        } else {
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    }

    if !quiet {
        eprintln!("\nShutting down...");
    }
    ipc::stop_server();

    // Clean up PID file
    if let Some(pid_path) = pid_file
        && let Err(e) = std::fs::remove_file(pid_path)
    {
        log::debug!("Could not remove PID file {}: {}", pid_path.display(), e);
    }

    Ok(())
}

/// Configure R options for headless mode.
///
/// Sets up pager redirection and graphics device defaults so that commands
/// like `?mean` or `plot(1:10)` don't spawn interactive programs (less, X11)
/// that would block or corrupt the headless server.
///
/// The approach is based on [mcp-repl](https://github.com/t-kalinowski/mcp-repl)
/// (Apache-2.0), which uses the same pattern of custom pager and device
/// functions for non-interactive R sessions.
fn configure_headless_r_options() -> Result<()> {
    let code = r#"
local({
    # Force text-based help output (no HTML browser)
    options(help_type = "text")

    # Custom pager: dump file contents to stdout instead of spawning less/more.
    # Output goes through WriteConsoleEx callback, so evaluate_with_capture
    # picks it up automatically.
    .arf_headless_pager <- function(files, header = NULL, title = NULL,
                                    delete.file = FALSE, ...) {
        files <- as.character(files)
        if (length(files) == 0L) return(invisible(NULL))

        if (!is.null(title) && length(title) >= 1L && nzchar(title[[1L]])) {
            cat(title[[1L]], "\n", sep = "")
        }

        for (i in seq_along(files)) {
            path <- files[[i]]
            if (!nzchar(path) || !file.exists(path)) next

            if (!is.null(header) && length(header) >= i && nzchar(header[[i]])) {
                cat(header[[i]], "\n", sep = "")
            }

            tryCatch({
                lines <- readLines(path, warn = FALSE)
                cat(lines, sep = "\n")
                if (length(lines) > 0L) cat("\n")
            }, error = function(e) NULL)

            if (isTRUE(delete.file)) unlink(path, force = TRUE)
        }
        invisible(NULL)
    }

    options(pager = .arf_headless_pager)
    options(help.pager = .arf_headless_pager)

    # Suppress browseURL() — just print the URL
    options(browser = function(url, ...) { cat(url, "\n"); invisible(0L) })

    # Default graphics device: png with pdf fallback.
    # Prevents X11/quartz from being opened in headless environments.
    .arf_headless_device <- function(...) {
        # Ignore ... to avoid unit mismatch: dev.new() passes width/height
        # in inches, but png() interprets them as pixels by default.
        # Use sensible defaults; Stage 2 can add proper argument handling.
        path <- tempfile("arf-headless-plot-", fileext = ".png")
        ok <- FALSE
        tryCatch({
            grDevices::png(filename = path)
            ok <- TRUE
        }, error = function(e) NULL)

        if (!ok) {
            path <- tempfile("arf-headless-plot-", fileext = ".pdf")
            grDevices::pdf(file = path)
        }

        # Enable display list recording for potential future plot retrieval
        try(grDevices::dev.control(displaylist = "enable"), silent = TRUE)
        invisible(NULL)
    }

    options(device = .arf_headless_device)
})
"#;

    arf_harp::eval_string(code)
        .context("Failed to configure headless R options (pager, browser, graphics device)")?;
    log::info!("Headless R options configured (pager, browser, graphics device)");
    Ok(())
}

/// Handle config subcommands.
fn handle_config_command(action: &ConfigAction) -> Result<()> {
    match action {
        ConfigAction::Init { force } => {
            let path = init_config(*force)?;
            println!("Configuration file created at: {}", path.display());
            Ok(())
        }
        ConfigAction::Check { config: path } => handle_config_check(path.as_deref()),
    }
}

/// Handle `arf config check` — validate the config file and report errors.
fn handle_config_check(path: Option<&std::path::Path>) -> Result<()> {
    let config_path = if let Some(p) = path {
        p.to_path_buf()
    } else if let Some(p) = config_file_path() {
        p
    } else {
        anyhow::bail!("Could not determine config file path");
    };

    if !config_path.exists() {
        anyhow::bail!(
            "Config file not found: {}\nRun `arf config init` to create a default configuration file.",
            mask_home_path(&config_path)
        );
    }

    println!("Checking config file: {}", mask_home_path(&config_path));

    match load_config_from_path(&config_path) {
        Ok(_) => {
            println!("Config file is valid.");
            Ok(())
        }
        Err(ConfigLoadError::Parse { source, .. }) => {
            anyhow::bail!("Config file has errors:\n\n  {}", source);
        }
        Err(ConfigLoadError::Read { source, .. }) => {
            anyhow::bail!("Could not read config file: {}", source);
        }
    }
}

fn handle_history_command(
    action: &HistoryAction,
    config_path: Option<&std::path::PathBuf>,
    cli_history_dir: Option<&std::path::PathBuf>,
) -> Result<()> {
    match action {
        HistoryAction::Schema => {
            pager::history_schema::print_schema().context("Failed to display history schema")
        }
        HistoryAction::Import {
            from,
            file,
            hostname,
            dry_run,
            import_duplicates,
            unified,
            r_table,
            shell_table,
        } => handle_history_import(
            *from,
            file.as_ref(),
            hostname.as_deref(),
            *dry_run,
            !import_duplicates,
            *unified,
            r_table,
            shell_table,
            config_path,
            cli_history_dir,
        ),
        HistoryAction::Export {
            file,
            r_table,
            shell_table,
        } => handle_history_export(file, r_table, shell_table, config_path, cli_history_dir),
    }
}

fn handle_ipc_command(action: &IpcAction) {
    match action {
        IpcAction::List => ipc::client::cmd_list(),
        IpcAction::Eval {
            code,
            pid,
            visible,
            timeout,
        } => ipc::client::cmd_eval(code.as_deref(), *pid, *visible, *timeout),
        IpcAction::Send { code, pid } => ipc::client::cmd_send(code.as_deref(), *pid),
        IpcAction::Shutdown { pid } => ipc::client::cmd_shutdown(*pid),
        IpcAction::Session { pid } => ipc::client::cmd_session(*pid),
        IpcAction::History {
            limit,
            all_sessions,
            cwd,
            grep,
            since,
            pid,
        } => ipc::client::cmd_history(
            *pid,
            *limit,
            *all_sessions,
            cwd.as_deref(),
            grep.as_deref(),
            since.as_deref(),
        ),
    }
}

#[allow(clippy::too_many_arguments)]
fn handle_history_import(
    source: ImportSource,
    file: Option<&std::path::PathBuf>,
    hostname: Option<&str>,
    dry_run: bool,
    skip_duplicates: bool,
    unified: bool,
    r_table: &str,
    shell_table: &str,
    config_path: Option<&std::path::PathBuf>,
    cli_history_dir: Option<&std::path::PathBuf>,
) -> Result<()> {
    use history::import::{
        DedupSet, default_r_history_path, default_radian_path, import_entries,
        import_entries_dry_run, parse_arf_history, parse_r_history, parse_radian_history,
        parse_unified_arf_history,
    };
    use reedline::SqliteBackedHistory;

    // Load config (respecting --config flag if provided)
    let config = load_config_or_warn(config_path);

    // Resolve effective history directory (CLI --history-dir takes precedence)
    // Required for actual imports and for dry-run with dedup (needs DB access)
    let history_dir = cli_history_dir
        .cloned()
        .or(config.history.dir.clone())
        .or_else(config::history_dir);

    // Determine source file path
    // Note: --from arf requires --file to avoid self-import (source = target)
    let source_path = match (source, file) {
        (_, Some(path)) => path.clone(),
        (ImportSource::Radian, None) => default_radian_path(),
        (ImportSource::R, None) => default_r_history_path(),
        (ImportSource::Arf, None) => {
            anyhow::bail!(
                "The --file option is required when importing from arf format.\n\
                 Example: arf history import --from arf --file /path/to/backup/r.db"
            );
        }
    };

    // Check if source file exists
    if !source_path.exists() {
        anyhow::bail!(
            "Source history file not found: {}\nSpecify the path with --file",
            source_path.display()
        );
    }

    println!("Importing from: {}", source_path.display());

    // Parse entries from source
    let entries = match source {
        ImportSource::Radian => parse_radian_history(&source_path)?,
        ImportSource::R => parse_r_history(&source_path)?,
        ImportSource::Arf => {
            // Determine if this is a unified export file or a single-database file.
            // --unified flag forces unified mode; otherwise infer from filename.
            let is_unified = unified || {
                let filename = source_path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("");
                filename != "r.db" && filename != "shell.db"
            };

            if is_unified {
                // Unified export file - use table names to import both r and shell
                parse_unified_arf_history(&source_path, r_table, shell_table)?
            } else {
                // Traditional single-database import
                parse_arf_history(&source_path)?
            }
        }
    };

    println!("Found {} entries to import", entries.len());

    // In dry-run mode, simulate the import
    if dry_run {
        // Build dedup sets if duplicate skipping is enabled (requires DB access).
        // Each database is checked independently so dedup works even if only
        // one of the two target databases exists.
        let (r_dedup, shell_dedup) = if skip_duplicates {
            if let Some(ref history_dir) = history_dir {
                let r_path = history_dir.join("r.db");
                let shell_path = history_dir.join("shell.db");
                let r_dedup = if r_path.exists() {
                    Some(DedupSet::from_db(&r_path)?)
                } else {
                    None
                };
                let shell_dedup = if shell_path.exists() {
                    Some(DedupSet::from_db(&shell_path)?)
                } else {
                    None
                };
                (r_dedup, shell_dedup)
            } else {
                // history_dir could not be resolved (no config, no XDG default).
                // Dedup is silently skipped; warn the user so they know the
                // duplicate count is not available.
                eprintln!(
                    "Warning: Could not determine history directory; \
                     duplicate detection skipped in dry-run."
                );
                (None, None)
            }
        } else {
            (None, None)
        };

        let result = import_entries_dry_run(&entries, r_dedup.as_ref(), shell_dedup.as_ref());

        println!("\n[Dry run] Would import:");
        if let Some(h) = hostname {
            println!("  Hostname:       {}", h);
        }
        println!("  R commands:     {}", result.r_imported);
        println!("  Shell commands: {}", result.shell_imported);
        println!("  Skipped:        {}", result.skipped);
        if result.duplicates_skipped > 0 {
            println!(
                "  Duplicates:     {} (use --import-duplicates to import anyway)",
                result.duplicates_skipped
            );
        }

        if !result.warnings.is_empty() {
            println!("\nWarnings:");
            for warning in result.warnings.iter().take(10) {
                println!("  - {}", warning);
            }
            if result.warnings.len() > 10 {
                println!("  ... and {} more warnings", result.warnings.len() - 10);
            }
        }

        return Ok(());
    }

    // Determine target database paths (require history_dir for actual import)
    let history_dir =
        history_dir.ok_or_else(|| anyhow::anyhow!("Could not determine history directory"))?;
    let r_path = history_dir.join("r.db");
    let shell_path = history_dir.join("shell.db");

    // Prevent self-import when using `--from arf` with `--file` pointing at the
    // same database as the target, which would duplicate history entries.
    if matches!(source, ImportSource::Arf)
        && let Ok(source_canon) = fs::canonicalize(&source_path)
    {
        if fs::canonicalize(&r_path).is_ok_and(|r_canon| source_canon == r_canon) {
            anyhow::bail!(
                "Refusing to import from '{}' into itself (R history database). \
                 Please specify a different --file or history directory.",
                source_path.display()
            );
        }
        if fs::canonicalize(&shell_path).is_ok_and(|shell_canon| source_canon == shell_canon) {
            anyhow::bail!(
                "Refusing to import from '{}' into itself (shell history database). \
                 Please specify a different --file or history directory.",
                source_path.display()
            );
        }
    }

    // Ensure the history directory exists (config::ensure_directories only creates XDG base dirs,
    // not the history subdirectory or custom --history-dir paths)
    fs::create_dir_all(&history_dir).with_context(|| {
        format!(
            "Failed to create history directory: {}",
            history_dir.display()
        )
    })?;

    println!("Target databases:");
    println!("  R:     {}", r_path.display());
    println!("  Shell: {}", shell_path.display());

    let mut targets = history::import::ImportTargets {
        r_history: SqliteBackedHistory::with_file(r_path, None, None)
            .context("Failed to open R history database")?,
        shell_history: SqliteBackedHistory::with_file(shell_path, None, None)
            .context("Failed to open shell history database")?,
    };

    // Import entries
    let result = import_entries(&mut targets, entries, hostname, skip_duplicates)?;

    println!("\nImport complete:");
    if let Some(h) = hostname {
        println!("  Hostname:       {}", h);
    }
    println!("  R commands:     {}", result.r_imported);
    println!("  Shell commands: {}", result.shell_imported);
    println!("  Skipped:        {}", result.skipped);
    if result.duplicates_skipped > 0 {
        println!(
            "  Duplicates:     {} (use --import-duplicates to import anyway)",
            result.duplicates_skipped
        );
    }

    if !result.warnings.is_empty() {
        println!("\nWarnings:");
        for warning in result.warnings.iter().take(10) {
            println!("  - {}", warning);
        }
        if result.warnings.len() > 10 {
            println!("  ... and {} more warnings", result.warnings.len() - 10);
        }
    }

    Ok(())
}

fn handle_history_export(
    output_file: &std::path::Path,
    r_table: &str,
    shell_table: &str,
    config_path: Option<&std::path::PathBuf>,
    cli_history_dir: Option<&std::path::PathBuf>,
) -> Result<()> {
    use history::export::export_history;

    // Load config (respecting --config flag if provided)
    let config = load_config_or_warn(config_path);

    // Resolve effective history directory
    let history_dir = cli_history_dir
        .cloned()
        .or(config.history.dir.clone())
        .or_else(config::history_dir)
        .ok_or_else(|| anyhow::anyhow!("Could not determine history directory"))?;

    let r_path = history_dir.join("r.db");
    let shell_path = history_dir.join("shell.db");

    // Check if at least one database exists
    if !r_path.exists() && !shell_path.exists() {
        anyhow::bail!(
            "No history databases found in: {}\n\
             Expected r.db and/or shell.db",
            history_dir.display()
        );
    }

    println!("Exporting history to: {}", output_file.display());
    println!("Source databases:");
    if r_path.exists() {
        println!("  R:     {} (table: {})", r_path.display(), r_table);
    }
    if shell_path.exists() {
        println!("  Shell: {} (table: {})", shell_path.display(), shell_table);
    }

    let result = export_history(&r_path, &shell_path, output_file, r_table, shell_table)?;

    println!("\nExport complete:");
    println!("  R commands:     {}", result.r_exported);
    println!("  Shell commands: {}", result.shell_exported);

    Ok(())
}

/// Run in script execution mode (non-interactive).
fn run_script(cli: &Cli) -> Result<()> {
    // Load configuration (from file or default)
    let config = load_config_or_warn(cli.config.as_ref());

    // Set up R based on r_source config (with optional CLI override)
    setup_r(
        &config.startup.r_source,
        cli.r_home.as_deref(),
        cli.r_version.as_deref(),
    )?;

    // Ensure LD_LIBRARY_PATH includes R library directory
    if let Err(e) = arf_libr::ensure_ld_library_path() {
        log::warn!("Could not set LD_LIBRARY_PATH: {}", e);
    }

    // Generate R initialization arguments from CLI flags
    let r_args = cli.r_args();
    let r_args_refs: Vec<&str> = r_args.iter().map(|s| s.as_str()).collect();

    // Initialize R with CLI-specified flags
    unsafe {
        arf_libr::initialize_r_with_args(&r_args_refs).context("Failed to initialize R")?;
    }

    // Source R profile files (Windows only)
    #[cfg(windows)]
    source_r_profiles(&r_args);

    // Get the code to execute
    let code = if let Some(eval_code) = &cli.eval {
        eval_code.clone()
    } else if let Some(script_path) = cli.script_file() {
        if script_path == std::path::Path::new("-") {
            use std::io::Read;
            let mut buf = String::new();
            std::io::stdin()
                .read_to_string(&mut buf)
                .context("Failed to read from stdin")?;
            buf
        } else {
            fs::read_to_string(script_path)
                .with_context(|| format!("Failed to read script file: {}", script_path.display()))?
        }
    } else {
        // Should not happen - we checked script_mode earlier
        return Ok(());
    };

    // Evaluate the code - use reprex mode if enabled (CLI or config)
    let reprex_enabled = cli.reprex || config.startup.mode.reprex;
    if reprex_enabled {
        // In reprex mode, echo source code before each result
        match arf_harp::eval_string_reprex(&code, &config.mode.reprex.comment) {
            Ok(_) => Ok(()),
            Err(e) => {
                eprintln!("{}", e);
                Ok(())
            }
        }
    } else {
        // Normal script execution
        match arf_harp::eval_string(&code) {
            Ok(_) => Ok(()),
            Err(e) => {
                eprintln!("{}", e);
                Ok(())
            }
        }
    }
}

/// Set up R based on r_source configuration.
///
/// CLI options override config in this order:
/// 1. `cli_r_home` - explicit R_HOME path
/// 2. `cli_version` - rig version specification
/// 3. Config `r_source` setting
///
/// Returns an `RSourceStatus` describing how R was resolved (for display and feature gating).
fn setup_r(
    r_source: &RSource,
    cli_r_home: Option<&std::path::Path>,
    cli_version: Option<&str>,
) -> Result<RSourceStatus> {
    // CLI --r-home overrides everything
    if let Some(path) = cli_r_home {
        if !path.exists() {
            anyhow::bail!(
                "R_HOME path does not exist: {}\n\
                 Check your --r-home argument.",
                path.display()
            );
        }
        // Resolve R_HOME: if path looks like an installation prefix (has bin/R),
        // run `bin/R RHOME` to get the actual R_HOME directory
        let r_home = resolve_r_home_from_path(path)?;
        log::info!("Using R from --r-home: {}", r_home.display());
        // SAFETY: We're single-threaded at this point during startup
        unsafe { std::env::set_var("R_HOME", &r_home) };
        return Ok(RSourceStatus::ExplicitPath { path: r_home });
    }

    // CLI --with-r-version overrides config (uses rig)
    if let Some(version) = cli_version {
        return setup_r_via_rig(version);
    }

    match r_source {
        RSource::Mode(RSourceMode::Auto) => {
            // Auto mode: try rig if available, otherwise use PATH
            if external::rig::rig_available() {
                match external::rig::resolve_version("default") {
                    Ok(resolved) => {
                        log::info!("Using rig default R version: {}", resolved.version);
                        // SAFETY: We're single-threaded at this point during startup
                        unsafe { std::env::set_var("R_HOME", &resolved.r_home) };
                        return Ok(RSourceStatus::Rig {
                            version: resolved.version,
                        });
                    }
                    Err(e) => {
                        log::debug!("Could not get rig default version: {}", e);
                        log::info!("Using R from PATH");
                        // Fall through to use system R from PATH
                    }
                }
            } else {
                log::info!("Using R from PATH (rig not available)");
            }
            Ok(RSourceStatus::Path)
        }
        RSource::Mode(RSourceMode::Rig) => {
            // Rig mode: require rig
            if !external::rig::rig_available() {
                anyhow::bail!(
                    r#"r_source = "rig" but rig is not installed.
Install rig from https://github.com/r-lib/rig or use "auto"."#
                );
            }
            match external::rig::resolve_version("default") {
                Ok(resolved) => {
                    log::info!("Using rig default R version: {}", resolved.version);
                    // SAFETY: We're single-threaded at this point during startup
                    unsafe { std::env::set_var("R_HOME", &resolved.r_home) };
                    Ok(RSourceStatus::Rig {
                        version: resolved.version,
                    })
                }
                Err(e) => {
                    anyhow::bail!("Failed to get rig default R version: {}", e);
                }
            }
        }
        RSource::Path { path } => {
            // Explicit path mode
            if !path.exists() {
                anyhow::bail!(
                    "R_HOME path does not exist: {}\n\
                     Check your r_source configuration.",
                    path.display()
                );
            }
            log::info!("Using R from explicit path: {}", path.display());
            // SAFETY: We're single-threaded at this point during startup
            unsafe { std::env::set_var("R_HOME", path) };
            Ok(RSourceStatus::ExplicitPath { path: path.clone() })
        }
    }
}

/// Resolve R_HOME from a user-provided path.
///
/// The path can be either:
/// - An installation prefix (e.g., `/opt/R/4.5.2`) containing `bin/R`
/// - The actual R_HOME directory (e.g., `/opt/R/4.5.2/lib/R`)
///
/// If the path contains `bin/R`, we run it with `RHOME` to get the actual R_HOME.
fn resolve_r_home_from_path(path: &std::path::Path) -> Result<std::path::PathBuf> {
    // Check if this looks like an installation prefix (has bin/R)
    let r_binary = path.join("bin").join("R");
    if r_binary.exists() {
        // Run `bin/R RHOME` to get the actual R_HOME
        let output = std::process::Command::new(&r_binary)
            .arg("RHOME")
            .output()
            .with_context(|| format!("Failed to run {} RHOME", r_binary.display()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("{} RHOME failed: {}", r_binary.display(), stderr);
        }

        let r_home = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if r_home.is_empty() {
            anyhow::bail!("{} RHOME returned empty result", r_binary.display());
        }

        log::debug!(
            "Resolved R_HOME from installation prefix: {} -> {}",
            path.display(),
            r_home
        );
        return Ok(std::path::PathBuf::from(r_home));
    }

    // Assume the path is already R_HOME
    // Validate by checking for etc/Renviron
    let renviron = path.join("etc").join("Renviron");
    if !renviron.exists() {
        log::warn!(
            "Path {} does not look like R_HOME (missing etc/Renviron). \
             Consider providing the installation prefix instead.",
            path.display()
        );
    }

    Ok(path.to_path_buf())
}

/// Set up R via rig with a specific version (used for CLI --with-r-version).
fn setup_r_via_rig(version_spec: &str) -> Result<RSourceStatus> {
    if !external::rig::rig_available() {
        anyhow::bail!(
            "--with-r-version requires rig to be installed.\n\
             Install rig from https://github.com/r-lib/rig"
        );
    }

    match external::rig::resolve_version(version_spec) {
        Ok(resolved) => {
            log::info!(
                "Using R version {} from {}",
                resolved.version,
                resolved.r_home
            );
            // SAFETY: We're single-threaded at this point during startup
            unsafe { std::env::set_var("R_HOME", &resolved.r_home) };
            Ok(RSourceStatus::Rig {
                version: resolved.version,
            })
        }
        Err(e) => {
            anyhow::bail!("Failed to resolve R version '{}': {}", version_spec, e);
        }
    }
}

/// Source R profile files after R initialization.
///
/// This handles loading of:
/// - Site-level Rprofile.site (unless --no-site-file or --vanilla)
/// - User-level .Rprofile (unless --no-init-file or --vanilla)
///
/// On Windows, R's built-in profile loading is disabled during initialization
/// for compatibility with `globalCallingHandlers()`, so we must manually
/// source these files here.
#[cfg(windows)]
fn source_r_profiles(r_args: &[String]) {
    // Fix .Platform$GUI before any R profiles or packages are loaded.
    // See: https://github.com/eitsupi/arf/issues/168
    arf_harp::override_platform_gui();

    // Get R_HOME from environment (set earlier in setup_r)
    let r_home = match std::env::var("R_HOME") {
        Ok(path) => PathBuf::from(path),
        Err(_) => {
            log::warn!("R_HOME not set, skipping R profile sourcing");
            return;
        }
    };

    // Source site-level R profile unless --no-site-file or --vanilla
    if !arf_harp::should_ignore_site_r_profile(r_args) {
        arf_harp::source_site_r_profile(&r_home);
    } else {
        log::trace!("Skipping site R profile (--no-site-file or --vanilla)");
    }

    // Source user-level R profile unless --no-init-file or --vanilla
    if !arf_harp::should_ignore_user_r_profile(r_args) {
        arf_harp::source_user_r_profile();
    } else {
        log::trace!("Skipping user R profile (--no-init-file or --vanilla)");
    }

    // Call .First() then .First.sys() to match R's documented startup sequence
    // (see `?Startup`). After profiles are loaded:
    //   1. .First()     — user hook defined in .Rprofile (e.g. vscode-R session watcher)
    //   2. .First.sys() — base package hook that loads default packages (utils, grDevices, ...)
    // On Windows we source profiles manually (profiles disabled in setup_Rmainloop for
    // globalCallingHandlers compatibility), so we must call these hooks manually too.
    arf_harp::call_dot_first();
    arf_harp::call_dot_first_sys();
}

/// Generate a history session ID when history is enabled and a history directory
/// is available, or `None` otherwise.
///
/// This ensures IPC/session JSON does not misleadingly advertise history isolation
/// when no history backend is configured.
fn create_session_id(config: &Config) -> Option<reedline::HistorySessionId> {
    if config.history.disabled {
        return None;
    }
    // Check that a history directory is actually resolvable, matching the logic
    // in Repl::r_history_path() / shell_history_path().
    if config.history.dir.is_none() && config::history_dir().is_none() {
        return None;
    }
    Reedline::create_history_session_id()
}

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

    #[test]
    fn test_create_session_id_when_history_enabled() {
        let mut config = Config::default();
        // Ensure a history dir is available by setting it explicitly
        config.history.dir = Some(std::env::temp_dir());
        assert!(!config.history.disabled);
        let id = create_session_id(&config);
        assert!(
            id.is_some(),
            "should generate session ID when history is enabled"
        );
    }

    #[test]
    fn test_create_session_id_when_history_disabled() {
        let mut config = Config::default();
        config.history.disabled = true;
        let id = create_session_id(&config);
        assert!(id.is_none(), "should be None when history is disabled");
    }

    #[test]
    fn test_create_session_id_respects_default_history_dir() {
        // With default config (history.dir = None), session ID depends on
        // whether the platform provides a data directory via history_dir().
        let config = Config::default();
        assert!(!config.history.disabled);
        assert!(config.history.dir.is_none());
        let id = create_session_id(&config);
        // On most platforms history_dir() returns Some, so session ID is generated.
        // On exotic platforms where it returns None, session ID should be None.
        assert_eq!(id.is_some(), config::history_dir().is_some());
    }
}