op-loader 0.5.0

TUI for configuring 1password secrets for injection into your shell environment
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
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
use anyhow::{Context, Result};
#[cfg(target_os = "macos")]
use base64::Engine;
use clap::{Parser, Subcommand};
use log::{debug, info};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;

#[cfg(target_os = "macos")]
use rand_core::RngCore;

use crate::app::{InjectVarConfig, OpLoadConfig, TemplatedFile};
#[cfg(target_os = "macos")]
use crate::cache::cache_file_for_account;
use crate::cache::{
    CacheKind, CacheRemoval, cache_dir, ensure_cache_dir, lock_path_for_account,
    remove_cache_for_account,
};
#[cfg(target_os = "macos")]
use crate::keychain::{assert_keychain_available, delete_key, get_or_create_key};

#[derive(Debug, Default, Serialize, Deserialize)]
struct LegacyOpLoadConfig {
    #[serde(default)]
    inject_vars: std::collections::HashMap<String, String>,
    #[serde(default)]
    default_account_id: Option<String>,
    #[serde(default)]
    default_vault_per_account: std::collections::HashMap<String, String>,
    #[serde(default)]
    templated_files: std::collections::HashMap<String, TemplatedFile>,
}

#[derive(Parser)]
#[command(version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,

    #[command(flatten)]
    pub verbosity: clap_verbosity_flag::Verbosity,
}

#[derive(Subcommand)]
pub enum Command {
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    Env {
        #[command(subcommand)]
        action: EnvAction,
    },
    Cache {
        #[command(subcommand)]
        action: CacheAction,
    },
    Template {
        #[command(subcommand)]
        action: TemplateAction,
    },
}

#[derive(Subcommand, Debug)]
pub enum EnvAction {
    Inject {
        /// Cache op inject output per account for this duration (e.g. 30s, 10m, 1h, 2d)
        #[arg(long, value_name = "DURATION")]
        cache_ttl: Option<String>,
        /// Max time to wait on another process populating the cache (e.g. 5s, 30s, 1m)
        #[arg(long, value_name = "DURATION", default_value = "5s")]
        cache_lock_wait: String,
    },
    /// Unset all managed environment variables
    Unset,
}

#[derive(Subcommand, Debug)]
pub enum ConfigAction {
    Get {
        #[arg(short, long)]
        key: String,
    },
    Path,
}

#[derive(Subcommand, Debug)]
pub enum TemplateAction {
    /// Add a file to be managed as a template
    Add {
        /// Path to the file to manage (e.g., ~/.npmrc)
        path: String,
    },
    /// List all managed template files
    List,
    /// Stop managing a file as a template
    Remove {
        /// Path to the managed file
        path: String,
    },
    /// Render all templates (substituting variables)
    Render,
}

#[derive(Subcommand, Debug)]
pub enum CacheAction {
    /// Clear cached op inject output
    Clear {
        /// Clear cached output for a specific account ID
        #[arg(long)]
        account: Option<String>,
    },
}

pub fn handle_config_action(action: ConfigAction) -> Result<()> {
    handle_config_action_with_path(action, None)
}

fn handle_config_action_with_path(action: ConfigAction, config_path: Option<&Path>) -> Result<()> {
    debug!("Handling config action: {action:?}");

    match action {
        ConfigAction::Get { key } => {
            info!("Getting config key: {key}");

            let config: OpLoadConfig = if let Some(path) = config_path {
                confy::load_path(path).context("Failed to load configuration")?
            } else {
                confy::load("op_loader", None).context("Failed to load configuration")?
            };
            debug!("Config loaded successfully");

            match key.as_str() {
                "default_account_id" => match &config.default_account_id {
                    Some(preferred_account) => println!("{preferred_account}"),
                    None => println!("(not set)"),
                },
                _ => anyhow::bail!("Unknown config key: '{key}'."),
            }
            Ok(())
        }
        ConfigAction::Path => {
            info!("Getting config path");

            if let Some(path) = config_path {
                debug!("Config path (provided): {}", path.display());
                println!("{}", path.display());
            } else {
                let resolved_path = confy::get_configuration_file_path("op_loader", None)
                    .context("Failed to get config path")?
                    .display()
                    .to_string();

                debug!("Config path resolved to: {resolved_path}");
                println!("{resolved_path}");
            }
            Ok(())
        }
    }
}

pub fn handle_env_action(action: EnvAction) -> Result<()> {
    match action {
        EnvAction::Inject {
            cache_ttl,
            cache_lock_wait,
        } => handle_env_injection(cache_ttl.as_deref(), Some(cache_lock_wait.as_str())),
        EnvAction::Unset => handle_env_unset(),
    }
}

pub fn handle_env_unset() -> Result<()> {
    info!("Unsetting managed environment variables");

    let config: OpLoadConfig =
        confy::load("op_loader", None).context("Failed to load configuration")?;
    debug!("Config loaded successfully");

    if config.inject_vars.is_empty() {
        info!("No managed environment variables configured");
        return Ok(());
    }

    info!(
        "Found {} managed environment variables",
        config.inject_vars.len()
    );

    let keys: Vec<&String> = config.inject_vars.keys().collect();

    let output = format_unsets(keys);

    print!("{output}");

    info!("Finished unsetting env var mappings");

    Ok(())
}

fn format_unsets(keys: Vec<&String>) -> String {
    let mut output = String::new();
    for key in keys {
        output.push_str("unset ");
        output.push_str(key);
        output.push('\n');
    }
    output
}

pub fn handle_env_injection(cache_ttl: Option<&str>, cache_lock_wait: Option<&str>) -> Result<()> {
    info!("Loading environment variable mappings");

    let mut config: OpLoadConfig =
        confy::load("op_loader", None).context("Failed to load configuration")?;
    debug!("Config loaded successfully");

    if config.inject_vars.is_empty() {
        let legacy: LegacyOpLoadConfig =
            confy::load("op_loader", None).context("Failed to load configuration")?;

        if legacy.inject_vars.is_empty() {
            info!("No environment variables configured");
            eprintln!("No environment variables configured. Use the TUI to add mappings.");
            return Ok(());
        }

        eprintln!(
            "Warning: Legacy inject_vars format detected. Please re-add your environment variable mappings in the TUI."
        );
        config.inject_vars.clear();
        confy::store("op_loader", None, &config).context("Failed to save configuration")?;
    }

    if config.inject_vars.is_empty() {
        return Ok(());
    }

    info!("Processing {} env var mappings", config.inject_vars.len());

    let vars_by_account = group_vars_by_account(&config.inject_vars);

    #[cfg(not(target_os = "macos"))]
    if cache_ttl.is_some() {
        anyhow::bail!("Cache is only supported on macOS.");
    }

    let cache_ttl = cache_ttl.map(parse_duration).transpose()?.unwrap_or(None);
    let cache_lock_wait =
        parse_duration(cache_lock_wait.unwrap_or("5s"))?.unwrap_or_else(|| Duration::from_secs(5));

    // Build the input string for each account up front (cheap, no I/O).
    let account_inputs: Vec<(&str, String)> = vars_by_account
        .into_iter()
        .map(|(account_id, vars)| {
            let mut input = String::new();
            for (env_var_name, var_config) in vars {
                use std::fmt::Write;
                writeln!(input, "{env_var_name}: {}", var_config.op_reference)
                    .expect("write to String cannot fail");
            }
            (account_id, input)
        })
        .collect();

    // Resolve all accounts in parallel — each thread acquires its own
    // per-account lock, so different accounts never block each other.
    let results: Vec<(String, Result<std::collections::HashMap<String, String>>)> =
        std::thread::scope(|s| {
            let handles: Vec<_> = account_inputs
                .iter()
                .map(|(account_id, input)| {
                    let account_id = *account_id;
                    s.spawn(move || {
                        let result =
                            load_resolved_vars(account_id, input, cache_ttl, cache_lock_wait);
                        (account_id.to_string(), result)
                    })
                })
                .collect();

            handles
                .into_iter()
                .map(|h| h.join().expect("account resolver thread panicked"))
                .collect()
        });

    let mut combined_output = String::new();
    let mut resolved_vars_by_account: std::collections::HashMap<
        String,
        std::collections::HashMap<String, String>,
    > = std::collections::HashMap::new();

    for (account_id, result) in results {
        match result {
            Ok(resolved) => {
                combined_output.push_str(&format_exports(&resolved));
                resolved_vars_by_account.insert(account_id, resolved);
            }
            Err(err) => {
                eprintln!("# Warning: Failed to inject secrets for account {account_id}: {err}");
            }
        }
    }

    print!("{combined_output}");

    info!("Finished processing env var mappings");

    if !config.templated_files.is_empty() {
        info!("Rendering {} template files", config.templated_files.len());
        render_templates(&config, &resolved_vars_by_account)?;
    }

    Ok(())
}

fn run_op_inject(account_id: &str, input: &str) -> Result<String> {
    use std::process::{Command, Stdio};

    let mut child = Command::new("op")
        .args(["inject", "--account", account_id])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("Failed to run `op inject --account {account_id}`"))?;

    if let Some(mut stdin) = child.stdin.take() {
        use std::io::Write;
        stdin
            .write_all(input.as_bytes())
            .with_context(|| "Failed to write to op inject stdin")?;
    }

    let output = child
        .wait_with_output()
        .with_context(|| "Failed to read op inject output")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("op inject failed: {stderr}");
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

fn parse_duration(input: &str) -> Result<Option<Duration>> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }

    if trimmed.len() < 2 {
        anyhow::bail!("Invalid duration '{input}'. Use a number followed by s, m, h, or d.");
    }

    let (value, unit) = trimmed.split_at(trimmed.len().saturating_sub(1));
    let amount: u64 = value
        .parse()
        .with_context(|| format!("Invalid duration value: {input}"))?;

    let seconds = match unit {
        "s" => amount,
        "m" => amount.saturating_mul(60),
        "h" => amount.saturating_mul(60 * 60),
        "d" => amount.saturating_mul(60 * 60 * 24),
        _ => anyhow::bail!("Invalid duration unit in '{input}'. Use s, m, h, or d."),
    };

    Ok(Some(Duration::from_secs(seconds)))
}

#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
enum CacheReadOutcome {
    Hit(String),
    Miss,
    Expired,
}

#[cfg(not(target_os = "macos"))]
fn read_cached_output(
    _account_id: &str,
    _kind: CacheKind,
    _ttl: Duration,
) -> Result<CacheReadOutcome> {
    anyhow::bail!("Cache is only supported on macOS.");
}

#[cfg(target_os = "macos")]
fn read_cached_output(
    account_id: &str,
    kind: CacheKind,
    ttl: Duration,
) -> Result<CacheReadOutcome> {
    read_cached_output_macos(account_id, kind, ttl)
}

#[cfg(target_os = "macos")]
fn read_cached_output_macos(
    account_id: &str,
    kind: CacheKind,
    ttl: Duration,
) -> Result<CacheReadOutcome> {
    let path = cache_file_for_account(account_id, kind)?;
    let metadata = match std::fs::metadata(&path) {
        Ok(meta) => meta,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(CacheReadOutcome::Miss);
        }
        Err(err) => {
            return Err(err)
                .with_context(|| format!("Failed to read cache metadata: {}", path.display()));
        }
    };

    let modified = metadata
        .modified()
        .with_context(|| format!("Failed to read cache mtime: {}", path.display()))?;

    let age = modified
        .elapsed()
        .unwrap_or_else(|_| Duration::from_secs(0));
    if age > ttl {
        return Ok(CacheReadOutcome::Expired);
    }

    let contents = std::fs::read_to_string(&path)
        .with_context(|| format!("Failed to read cache file: {}", path.display()))?;
    match decrypt_cache(&contents) {
        Ok(decrypted) => {
            let rendered = String::from_utf8_lossy(&decrypted).to_string();
            Ok(CacheReadOutcome::Hit(rendered))
        }
        Err(err) => {
            eprintln!("# Warning: Failed to decrypt cache for account {account_id}: {err}");
            if let Err(remove_err) = std::fs::remove_file(&path) {
                eprintln!(
                    "# Warning: Failed to remove corrupt cache file {}: {remove_err}",
                    path.display()
                );
            }
            Ok(CacheReadOutcome::Miss)
        }
    }
}

fn read_cached_output_if_fresh(
    account_id: &str,
    kind: CacheKind,
    ttl: Duration,
) -> Result<Option<String>> {
    match read_cached_output(account_id, kind, ttl)? {
        CacheReadOutcome::Hit(cached) => Ok(Some(cached)),
        CacheReadOutcome::Expired | CacheReadOutcome::Miss => Ok(None),
    }
}

fn try_log_cache_state(account_id: &str, kind: CacheKind, ttl: Duration) {
    let prefix = match kind {
        CacheKind::ResolvedVars => "Cache",
    };

    match read_cached_output(account_id, kind, ttl) {
        Ok(CacheReadOutcome::Hit(_)) => info!("{prefix} hit for account {account_id}"),
        Ok(CacheReadOutcome::Expired) => info!("{prefix} expired for account {account_id}"),
        Ok(CacheReadOutcome::Miss) => info!("{prefix} miss for account {account_id}"),
        Err(err) => eprintln!("# Warning: Failed to read cache for account {account_id}: {err}"),
    }
}

#[cfg(target_os = "macos")]
fn encrypt_cache(plaintext: &[u8]) -> Result<String> {
    use aes_gcm::aead::{Aead, KeyInit};
    use aes_gcm::{Aes256Gcm, Key, Nonce};

    assert_keychain_available()?;
    let key = get_or_create_key()?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key));

    let mut nonce_bytes = [0u8; 12];
    rand_core::OsRng.fill_bytes(&mut nonce_bytes);
    let nonce = Nonce::from_slice(&nonce_bytes);

    let ciphertext = cipher
        .encrypt(nonce, plaintext)
        .map_err(|err| anyhow::anyhow!("Failed to encrypt cache: {err}"))?;

    let mut payload = Vec::with_capacity(1 + nonce_bytes.len() + ciphertext.len());
    payload.push(1u8);
    payload.extend_from_slice(&nonce_bytes);
    payload.extend_from_slice(&ciphertext);

    Ok(base64::engine::general_purpose::STANDARD.encode(payload))
}

#[cfg(target_os = "macos")]
fn decrypt_cache(encoded: &str) -> Result<Vec<u8>> {
    use aes_gcm::aead::{Aead, KeyInit};
    use aes_gcm::{Aes256Gcm, Key, Nonce};

    assert_keychain_available()?;
    let key = get_or_create_key()?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key));

    let payload = base64::engine::general_purpose::STANDARD
        .decode(encoded)
        .context("Failed to decode cache base64")?;

    if payload.len() < 1 + 12 {
        anyhow::bail!("Invalid cache payload length");
    }

    if payload[0] != 1u8 {
        anyhow::bail!("Unsupported cache payload version");
    }

    let nonce = Nonce::from_slice(&payload[1..13]);
    let ciphertext = &payload[13..];

    cipher
        .decrypt(nonce, ciphertext)
        .map_err(|err| anyhow::anyhow!("Failed to decrypt cache: {err}"))
}

#[cfg(not(target_os = "macos"))]
fn write_cached_output(_account_id: &str, _kind: CacheKind, _output: &str) -> Result<()> {
    anyhow::bail!("Cache is only supported on macOS.");
}

#[cfg(target_os = "macos")]
fn write_cached_output(account_id: &str, kind: CacheKind, output: &str) -> Result<()> {
    write_cached_output_macos(account_id, kind, output)
}

fn load_resolved_vars(
    account_id: &str,
    input: &str,
    cache_ttl: Option<Duration>,
    cache_lock_wait: Duration,
) -> Result<std::collections::HashMap<String, String>> {
    if let Some(ttl) = cache_ttl {
        // Fast path: check cache before acquiring any lock.
        if let Ok(Some(cached)) =
            read_cached_output_if_fresh(account_id, CacheKind::ResolvedVars, ttl)
        {
            info!("Cache hit for account {account_id}");
            return parse_cached_vars(&cached);
        }

        try_log_cache_state(account_id, CacheKind::ResolvedVars, ttl);

        // Acquire per-account exclusive lock with timeout.
        let lock_file = open_lock_file_for_account(account_id)?;
        let acquired = lock_exclusive_with_timeout(&lock_file, cache_lock_wait)?;
        if !acquired {
            anyhow::bail!(
                "Cache lock for account {account_id} not acquired within {}s",
                cache_lock_wait.as_secs()
            );
        }

        // Double-check: another process may have populated the cache while
        // we were waiting on the lock.
        if let Ok(Some(cached)) =
            read_cached_output_if_fresh(account_id, CacheKind::ResolvedVars, ttl)
        {
            info!("Cache hit (after lock) for account {account_id}");
            let _ = lock_file.unlock();
            return parse_cached_vars(&cached);
        }

        // Cache is stale/missing and we hold the lock — resolve via op inject.
        let resolved_json = resolve_vars_json(account_id, input)?;
        if let Err(err) = write_cached_output(account_id, CacheKind::ResolvedVars, &resolved_json) {
            eprintln!("# Warning: Failed to write cache for account {account_id}: {err}");
        }
        let _ = lock_file.unlock();
        return parse_cached_vars(&resolved_json);
    }

    let resolved_json = resolve_vars_json(account_id, input)?;
    parse_cached_vars(&resolved_json)
}

/// Attempt to acquire an exclusive lock on `file`, blocking up to `timeout`.
///
/// Returns `Ok(true)` if the lock was acquired, `Ok(false)` if the timeout
/// elapsed. Uses a background thread so the caller's thread can enforce
/// the deadline.
fn lock_exclusive_with_timeout(file: &std::fs::File, timeout: Duration) -> Result<bool> {
    use fs2::FileExt;
    use std::sync::mpsc;

    // First try a non-blocking acquire — avoids spawning a thread when
    // the lock is uncontended (the common case).
    if file.try_lock_exclusive().is_ok() {
        return Ok(true);
    }

    info!("Lock contended, waiting up to {}s", timeout.as_secs());

    // Clone the file descriptor so the background thread can call the
    // blocking lock_exclusive() without borrowing from the caller.
    let file_dup = file.try_clone().context("Failed to duplicate lock fd")?;
    let (tx, rx) = mpsc::channel();

    std::thread::spawn(move || {
        let result = file_dup.lock_exclusive();
        // If the receiver has been dropped (timeout elapsed), release the
        // lock we just acquired so we don't hold it indefinitely.
        if tx.send(result).is_err() {
            let _ = file_dup.unlock();
        }
    });

    match rx.recv_timeout(timeout) {
        Ok(Ok(())) => Ok(true),
        Ok(Err(err)) => Err(err).context("Failed to acquire exclusive lock"),
        Err(mpsc::RecvTimeoutError::Timeout) => Ok(false),
        Err(mpsc::RecvTimeoutError::Disconnected) => {
            anyhow::bail!("Lock thread terminated unexpectedly")
        }
    }
}

fn resolve_vars_json(account_id: &str, input: &str) -> Result<String> {
    let output = run_op_inject(account_id, input)?;
    let mut vars = std::collections::HashMap::new();
    for line in output.lines() {
        if let Some((var_name, value)) = line.split_once(": ") {
            vars.insert(var_name.to_string(), value.to_string());
        }
    }
    serde_json::to_string(&vars).context("Failed to serialize resolved vars")
}

fn parse_cached_vars(cached_json: &str) -> Result<std::collections::HashMap<String, String>> {
    serde_json::from_str(cached_json).context("Failed to parse cached vars")
}

fn format_exports(vars: &std::collections::HashMap<String, String>) -> String {
    let mut lines: Vec<(&String, &String)> = vars.iter().collect();
    lines.sort_by(|a, b| a.0.cmp(b.0));

    let mut output = String::new();
    for (key, value) in lines {
        let escaped = escape_shell_single_quotes(value);
        output.push_str("export ");
        output.push_str(key);
        output.push_str("='");
        output.push_str(&escaped);
        output.push_str("'\n");
    }
    output
}

fn escape_shell_single_quotes(value: &str) -> String {
    value.replace('\'', "'\\''")
}

#[cfg(target_os = "macos")]
fn write_cached_output_macos(account_id: &str, kind: CacheKind, output: &str) -> Result<()> {
    use std::fs::OpenOptions;
    use std::io::Write;

    ensure_cache_dir()?;
    let path = cache_file_for_account(account_id, kind)?;
    let tmp_path = path.with_extension("cache.tmp");

    let encrypted = encrypt_cache(output.as_bytes())?;

    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&tmp_path)
        .with_context(|| {
            format!(
                "Failed to open temp cache file for writing: {}",
                tmp_path.display()
            )
        })?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = file.metadata()?.permissions();
        perms.set_mode(0o600);
        std::fs::set_permissions(&tmp_path, perms).with_context(|| {
            format!(
                "Failed to set cache file permissions: {}",
                tmp_path.display()
            )
        })?;
    }

    file.write_all(encrypted.as_bytes())
        .with_context(|| format!("Failed to write temp cache file: {}", tmp_path.display()))?;

    // Flush to disk before rename to ensure readers see complete data.
    file.sync_all()
        .with_context(|| format!("Failed to sync temp cache file: {}", tmp_path.display()))?;
    drop(file);

    // Atomic rename: readers either see the old file or the new complete file.
    std::fs::rename(&tmp_path, &path)
        .with_context(|| format!("Failed to rename temp cache to {}", path.display()))?;

    Ok(())
}

fn open_lock_file_for_account(account_id: &str) -> Result<std::fs::File> {
    use std::fs::OpenOptions;

    ensure_cache_dir()?;
    let lock_path = lock_path_for_account(account_id)?;
    let lock_file = OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(&lock_path)
        .with_context(|| format!("Failed to open cache lock: {}", lock_path.display()))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = lock_file.metadata()?.permissions();
        perms.set_mode(0o600);
        std::fs::set_permissions(&lock_path, perms).with_context(|| {
            format!(
                "Failed to set lock file permissions: {}",
                lock_path.display()
            )
        })?;
    }

    Ok(lock_file)
}

fn get_templates_dir() -> Result<PathBuf> {
    let config_path = confy::get_configuration_file_path("op_loader", None)
        .context("Failed to get config path")?;
    let config_dir = config_path
        .parent()
        .context("Config path has no parent directory")?;
    Ok(config_dir.join("templates"))
}

fn expand_path(path: &str) -> Result<PathBuf> {
    let expanded = if let Some(suffix) = path.strip_prefix("~/") {
        let home = std::env::var("HOME").context("HOME environment variable not set")?;
        PathBuf::from(home).join(suffix)
    } else {
        PathBuf::from(path)
    };

    if expanded.exists() {
        expanded
            .canonicalize()
            .with_context(|| format!("Failed to canonicalize path: {}", expanded.display()))
    } else {
        Ok(expanded)
    }
}

fn path_to_template_name(path: &Path) -> String {
    let filename = path.file_name().map_or_else(
        || "template".to_string(),
        |s| s.to_string_lossy().to_string(),
    );
    format!("{filename}.tmpl")
}

pub fn handle_template_action(action: TemplateAction) -> Result<()> {
    debug!("Handling template action: {action:?}");

    match action {
        TemplateAction::Add { path } => template_add(&path),
        TemplateAction::List => template_list(),
        TemplateAction::Remove { path } => template_remove(&path),
        TemplateAction::Render => {
            let config: OpLoadConfig =
                confy::load("op_loader", None).context("Failed to load configuration")?;
            let resolved_vars_by_account = std::collections::HashMap::new();
            render_templates(&config, &resolved_vars_by_account)
        }
    }
}

pub fn handle_cache_action(action: CacheAction) -> Result<()> {
    debug!("Handling cache action: {action:?}");

    match action {
        CacheAction::Clear { account } => {
            if let Some(account_id) = account {
                match remove_cache_for_account(&account_id) {
                    Ok(CacheRemoval::Removed) => {
                        println!("Cleared cache for account {account_id}");
                    }
                    Ok(CacheRemoval::NotFound) => {
                        println!("No cache found for account {account_id}");
                    }
                    Err(err) => {
                        eprintln!("Warning: Failed to clear cache for account {account_id}: {err}");
                    }
                }
            } else {
                clear_all_caches()?;
                #[cfg(target_os = "macos")]
                {
                    if let Err(err) = delete_key() {
                        eprintln!("Warning: Failed to delete cache key from Keychain: {err}");
                    }
                }
            }
        }
    }

    Ok(())
}

fn clear_all_caches() -> Result<()> {
    let dir = cache_dir()?;
    if !dir.exists() {
        println!("No cache directory found.");
        return Ok(());
    }

    let mut removed = 0usize;
    let mut failed = 0usize;
    let mut saw_file = false;
    for entry in std::fs::read_dir(&dir)
        .with_context(|| format!("Failed to read cache directory: {}", dir.display()))?
    {
        let entry = entry?;
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        match std::fs::remove_file(&path) {
            Ok(()) => removed += 1,
            Err(err) => {
                failed += 1;
                eprintln!("Warning: Failed to remove {}: {err}", path.display());
            }
        }
        saw_file = true;
    }

    if !saw_file {
        println!("No cache files found.");
        return Ok(());
    }

    println!(
        "Cleared {removed} cache file(s).{suffix}",
        suffix = if failed > 0 { " (some failures)" } else { "" }
    );
    Ok(())
}

fn template_add(path: &str) -> Result<()> {
    info!("Adding template for: {path}");

    let target_path = expand_path(path)?;
    let target_key = target_path.to_string_lossy().to_string();

    if !target_path.exists() {
        anyhow::bail!("File does not exist: {}", target_path.display());
    }

    let mut config: OpLoadConfig =
        confy::load("op_loader", None).context("Failed to load configuration")?;

    if config.templated_files.contains_key(&target_key) {
        anyhow::bail!(
            "File is already managed as a template: {}",
            target_path.display()
        );
    }

    let templates_dir = get_templates_dir()?;
    std::fs::create_dir_all(&templates_dir).with_context(|| {
        format!(
            "Failed to create templates directory: {}",
            templates_dir.display()
        )
    })?;

    let template_name = path_to_template_name(&target_path);
    let template_path = templates_dir.join(&template_name);

    let original_content =
        std::fs::read_to_string(&target_path).context("Failed to read source file")?;

    let var_names: Vec<String> = config
        .inject_vars
        .keys()
        .map(|k| format!("{{{{{k}}}}}"))
        .collect();

    let vars_comment = if var_names.is_empty() {
        "# op-loader: No variables configured yet. Use the TUI to add variables.\n".to_string()
    } else {
        format!(
            "# op-loader: Available variables: {}\n",
            var_names.join(", ")
        )
    };

    let template_content = format!("{vars_comment}{original_content}");
    std::fs::write(&template_path, &template_content)
        .with_context(|| format!("Failed to write template to {}", template_path.display()))?;

    config
        .templated_files
        .insert(target_key, TemplatedFile { template_name });
    confy::store("op_loader", None, &config).context("Failed to save configuration")?;

    println!("Added template for: {}", target_path.display());
    println!("Template stored at: {}", template_path.display());
    println!("\nAdd {{VAR_NAME}} placeholders to the template file.");
    println!("Use `op-loader template list` to see configured variables.");

    Ok(())
}

fn template_list() -> Result<()> {
    info!("Listing templates");

    let config: OpLoadConfig =
        confy::load("op_loader", None).context("Failed to load configuration")?;

    if config.templated_files.is_empty() {
        println!("No template files configured.");
        println!("\nAdd a template with: op-loader template add <path>");
        return Ok(());
    }

    let templates_dir = get_templates_dir()?;

    println!("Managed template files:\n");
    for (target_path, template_config) in &config.templated_files {
        let template_path = templates_dir.join(&template_config.template_name);
        let status = if template_path.exists() {
            ""
        } else {
            "✗ (missing)"
        };
        println!("  {status} {target_path}");
        println!("    └─ {}", template_path.display());
    }

    Ok(())
}

fn template_remove(path: &str) -> Result<()> {
    info!("Removing template for: {path}");

    let target_path = expand_path(path)?;
    let target_key = target_path.to_string_lossy().to_string();

    let mut config: OpLoadConfig =
        confy::load("op_loader", None).context("Failed to load configuration")?;

    let template_config = config
        .templated_files
        .remove(&target_key)
        .with_context(|| {
            format!(
                "File is not managed as a template: {}",
                target_path.display()
            )
        })?;

    let templates_dir = get_templates_dir()?;
    let template_path = templates_dir.join(&template_config.template_name);

    if template_path.exists() {
        std::fs::remove_file(&template_path)
            .with_context(|| format!("Failed to delete template: {}", template_path.display()))?;
        println!("Removed template: {}", template_path.display());
    } else {
        println!(
            "Removed config for: {} (template file was already missing)",
            target_path.display()
        );
    }

    confy::store("op_loader", None, &config).context("Failed to save configuration")?;

    Ok(())
}

fn render_templates(
    config: &OpLoadConfig,
    resolved_vars_by_account: &std::collections::HashMap<
        String,
        std::collections::HashMap<String, String>,
    >,
) -> Result<()> {
    let templates_dir = get_templates_dir()?;

    let resolved_vars: std::collections::HashMap<String, String> = resolved_vars_by_account
        .values()
        .flat_map(|vars| vars.iter().map(|(k, v)| (k.clone(), v.clone())))
        .collect();

    for (target_path, template_config) in &config.templated_files {
        let template_path = templates_dir.join(&template_config.template_name);

        if !template_path.exists() {
            eprintln!(
                "# Warning: Template file not found for {}: {}",
                target_path,
                template_path.display()
            );
            continue;
        }

        debug!(
            "Rendering template: {} -> {}",
            template_path.display(),
            target_path
        );

        let template_content =
            std::fs::read_to_string(&template_path).context("Failed to read template file")?;

        let mut rendered: String = template_content
            .lines()
            .filter(|line| !line.starts_with("# op-loader:"))
            .collect::<Vec<_>>()
            .join("\n");

        if template_content.ends_with('\n') && !rendered.ends_with('\n') {
            rendered.push('\n');
        }

        for (var_name, value) in &resolved_vars {
            let placeholder = format!("{{{{{var_name}}}}}");
            rendered = rendered.replace(&placeholder, value);
        }

        let target = PathBuf::from(target_path);
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }

        std::fs::write(&target, &rendered)
            .with_context(|| format!("Failed to write to {target_path}"))?;

        info!("Rendered template: {target_path}");
    }

    Ok(())
}

fn group_vars_by_account<'a>(
    inject_vars: &'a std::collections::HashMap<String, InjectVarConfig>,
) -> std::collections::BTreeMap<&'a str, Vec<(&'a str, &'a InjectVarConfig)>> {
    let mut vars_by_account: std::collections::BTreeMap<
        &'a str,
        Vec<(&'a str, &'a InjectVarConfig)>,
    > = std::collections::BTreeMap::new();

    for (var_name, var_config) in inject_vars {
        vars_by_account
            .entry(var_config.account_id.as_str())
            .or_default()
            .push((var_name.as_str(), var_config));
    }

    vars_by_account
}

#[cfg(all(test, target_os = "macos"))]
mod cache_tests {
    use super::*;
    use crate::cache::cache_path_for_account;
    use assert_fs::TempDir;
    use filetime::FileTime;

    #[cfg(target_os = "macos")]
    fn write_cached_output_at(
        cache_root: &std::path::Path,
        account_id: &str,
        kind: CacheKind,
        output: &str,
    ) -> Result<()> {
        use std::fs::OpenOptions;
        use std::io::Write;

        std::fs::create_dir_all(cache_root).with_context(|| {
            format!("Failed to create cache directory: {}", cache_root.display())
        })?;
        let path = cache_path_for_account(cache_root, account_id, kind);
        let encrypted = super::encrypt_cache(output.as_bytes())?;

        let mut file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&path)
            .with_context(|| {
                format!("Failed to open cache file for writing: {}", path.display())
            })?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = file.metadata()?.permissions();
            perms.set_mode(0o600);
            std::fs::set_permissions(&path, perms).with_context(|| {
                format!("Failed to set cache file permissions: {}", path.display())
            })?;
        }

        file.write_all(encrypted.as_bytes())
            .with_context(|| format!("Failed to write cache file: {}", path.display()))?;
        Ok(())
    }

    #[cfg(target_os = "macos")]
    fn read_cached_output_at(
        cache_root: &std::path::Path,
        account_id: &str,
        kind: CacheKind,
        ttl: Duration,
    ) -> Result<CacheReadOutcome> {
        let path = cache_path_for_account(cache_root, account_id, kind);
        let metadata = match std::fs::metadata(&path) {
            Ok(meta) => meta,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                return Ok(CacheReadOutcome::Miss);
            }
            Err(err) => {
                return Err(err)
                    .with_context(|| format!("Failed to read cache metadata: {}", path.display()));
            }
        };

        let modified = metadata
            .modified()
            .with_context(|| format!("Failed to read cache mtime: {}", path.display()))?;

        let age = modified
            .elapsed()
            .unwrap_or_else(|_| Duration::from_secs(0));
        if age > ttl {
            return Ok(CacheReadOutcome::Expired);
        }

        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read cache file: {}", path.display()))?;
        let decrypted = super::decrypt_cache(&contents)?;
        let rendered = String::from_utf8_lossy(&decrypted).to_string();
        Ok(CacheReadOutcome::Hit(rendered))
    }

    #[cfg(target_os = "macos")]
    fn clear_all_caches_at(cache_root: &std::path::Path) -> Result<()> {
        if !cache_root.exists() {
            return Ok(());
        }

        for entry in std::fs::read_dir(cache_root)
            .with_context(|| format!("Failed to read cache directory: {}", cache_root.display()))?
        {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                std::fs::remove_file(&path)
                    .with_context(|| format!("Failed to remove cache file: {}", path.display()))?;
            }
        }
        Ok(())
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn cache_write_and_read_hit() {
        let temp_dir = TempDir::new().unwrap();
        let cache_root = temp_dir.path().join("op_loader");

        let output = "{\"FOO\":\"bar\"}";
        write_cached_output_at(&cache_root, "account-1", CacheKind::ResolvedVars, output).unwrap();
        let result = read_cached_output_at(
            &cache_root,
            "account-1",
            CacheKind::ResolvedVars,
            Duration::from_secs(60),
        )
        .unwrap();

        match result {
            CacheReadOutcome::Hit(contents) => assert_eq!(contents, output),
            _ => panic!("Expected cache hit"),
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn cache_read_expired_returns_expired() {
        let temp_dir = TempDir::new().unwrap();
        let cache_root = temp_dir.path().join("op_loader");

        write_cached_output_at(
            &cache_root,
            "account-2",
            CacheKind::ResolvedVars,
            "{\"TOKEN\":\"old\"}",
        )
        .unwrap();
        let cache_path = cache_path_for_account(&cache_root, "account-2", CacheKind::ResolvedVars);
        let past = std::time::SystemTime::now() - Duration::from_secs(120);
        filetime::set_file_mtime(&cache_path, FileTime::from_system_time(past)).unwrap();

        let result = read_cached_output_at(
            &cache_root,
            "account-2",
            CacheKind::ResolvedVars,
            Duration::from_secs(60),
        )
        .unwrap();

        assert!(matches!(result, CacheReadOutcome::Expired));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn cache_read_missing_returns_miss() {
        let temp_dir = TempDir::new().unwrap();
        let cache_root = temp_dir.path().join("op_loader");

        let result = read_cached_output_at(
            &cache_root,
            "missing-account",
            CacheKind::ResolvedVars,
            Duration::from_secs(60),
        )
        .unwrap();

        assert!(matches!(result, CacheReadOutcome::Miss));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn cache_clear_removes_all_files() {
        let temp_dir = TempDir::new().unwrap();
        let cache_root = temp_dir.path().join("op_loader");

        write_cached_output_at(
            &cache_root,
            "account-a",
            CacheKind::ResolvedVars,
            "{\"A\":\"1\"}",
        )
        .unwrap();
        std::fs::write(cache_root.join("extra-file.txt"), "extra").unwrap();
        std::fs::create_dir_all(cache_root.join("nested")).unwrap();

        clear_all_caches_at(&cache_root).unwrap();

        let remaining_files = std::fs::read_dir(cache_root)
            .unwrap()
            .filter_map(|entry| entry.ok())
            .filter(|entry| entry.path().is_file())
            .count();
        assert_eq!(remaining_files, 0);
    }
}

#[cfg(test)]
mod config_tests {
    use super::*;
    use assert_fs::TempDir;

    #[test]
    fn config_get_default_account_id() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");

        let config = OpLoadConfig {
            default_account_id: Some("test-account-123".to_string()),
            ..Default::default()
        };
        confy::store_path(&config_path, &config).unwrap();

        let result = handle_config_action_with_path(
            ConfigAction::Get {
                key: "default_account_id".to_string(),
            },
            Some(&config_path),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn config_get_unknown_key() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");

        let result = handle_config_action_with_path(
            ConfigAction::Get {
                key: "nonexistent_key".to_string(),
            },
            Some(&config_path),
        );

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unknown config key")
        );
    }

    #[test]
    fn config_path_shows_custom_path() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");

        let result = handle_config_action_with_path(ConfigAction::Path, Some(&config_path));

        assert!(result.is_ok());
    }

    #[test]
    fn config_get_when_file_does_not_exist_returns_not_set() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("nonexistent.toml");

        let result = handle_config_action_with_path(
            ConfigAction::Get {
                key: "default_account_id".to_string(),
            },
            Some(&config_path),
        );

        assert!(result.is_ok());
    }
}

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

    #[test]
    fn parses_resolved_vars_json() {
        let json = r#"{"API_KEY":"abc123","URL":"https://example.com"}"#;

        let parsed = parse_cached_vars(json).unwrap();

        assert_eq!(parsed.get("API_KEY"), Some(&"abc123".to_string()));
        assert_eq!(parsed.get("URL"), Some(&"https://example.com".to_string()));
    }

    #[test]
    fn format_exports_escapes_single_quotes() {
        let mut vars = std::collections::HashMap::new();
        vars.insert("TOKEN".to_string(), "a'b".to_string());

        let output = format_exports(&vars);

        assert_eq!(output, "export TOKEN='a'\\''b'\n");
    }

    #[test]
    fn format_exports_preserves_colons_and_newlines() {
        let mut vars = std::collections::HashMap::new();
        vars.insert("CONFIG".to_string(), "line1:ok\nline2".to_string());

        let output = format_exports(&vars);

        assert_eq!(output, "export CONFIG='line1:ok\nline2'\n");
    }
}

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

    #[test]
    fn format_unsets_empty_returns_empty_string() {
        let keys: Vec<&String> = Vec::new();

        let output = format_unsets(keys);

        assert_eq!(output, "");
    }

    #[test]
    fn format_unsets_emits_unset_lines_in_order() {
        let var_a = "API_TOKEN".to_string();
        let var_b = "USER".to_string();
        let keys = vec![&var_a, &var_b];

        let output = format_unsets(keys);

        assert_eq!(output, "unset API_TOKEN\nunset USER\n");
    }
}

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

    mod path_to_template_name {
        use super::*;

        #[test]
        fn extracts_filename_from_path() {
            let path = Path::new("/Users/foo/.npmrc");
            let result = path_to_template_name(path);
            assert_eq!(result, ".npmrc.tmpl");
        }

        #[test]
        fn handles_simple_filename() {
            let path = Path::new("myfile.txt");
            let result = path_to_template_name(path);
            assert_eq!(result, "myfile.txt.tmpl");
        }

        #[test]
        fn handles_nested_path() {
            let path = Path::new("/home/user/.config/app/settings.json");
            let result = path_to_template_name(path);
            assert_eq!(result, "settings.json.tmpl");
        }
    }

    mod expand_path {
        use super::*;
        use std::env;

        #[test]
        fn expands_tilde_to_home() {
            let home = env::var("HOME").unwrap();
            let result = expand_path("~/.npmrc").unwrap();
            assert_eq!(result, PathBuf::from(format!("{}/.npmrc", home)));
        }

        #[test]
        fn preserves_absolute_path() {
            // For non-existent files, it returns the path as-is
            let result = expand_path("/some/absolute/path").unwrap();
            assert_eq!(result, PathBuf::from("/some/absolute/path"));
        }

        #[test]
        fn handles_relative_path() {
            let result = expand_path("relative/path").unwrap();
            assert_eq!(result, PathBuf::from("relative/path"));
        }
    }

    mod render_template_content {
        /// Helper to test template rendering logic without 1Password
        fn render_content(
            template: &str,
            vars: &std::collections::HashMap<String, String>,
        ) -> String {
            let mut rendered: String = template
                .lines()
                .filter(|line| !line.starts_with("# op-loader:"))
                .collect::<Vec<_>>()
                .join("\n");

            if template.ends_with('\n') && !rendered.ends_with('\n') {
                rendered.push('\n');
            }

            for (var_name, value) in vars {
                let placeholder = format!("{{{{{}}}}}", var_name);
                rendered = rendered.replace(&placeholder, value);
            }

            rendered
        }

        #[test]
        fn substitutes_single_variable() {
            let template = "token={{MY_TOKEN}}\n";
            let mut vars = std::collections::HashMap::new();
            vars.insert("MY_TOKEN".to_string(), "secret123".to_string());

            let result = render_content(template, &vars);
            assert_eq!(result, "token=secret123\n");
        }

        #[test]
        fn substitutes_multiple_variables() {
            let template = "user={{USER}}\npass={{PASS}}\n";
            let mut vars = std::collections::HashMap::new();
            vars.insert("USER".to_string(), "admin".to_string());
            vars.insert("PASS".to_string(), "secret".to_string());

            let result = render_content(template, &vars);
            assert_eq!(result, "user=admin\npass=secret\n");
        }

        #[test]
        fn strips_op_loader_comments() {
            let template = "# op-loader: Available variables: {{TOKEN}}\n# op-loader: This line too\ntoken={{TOKEN}}\n";
            let mut vars = std::collections::HashMap::new();
            vars.insert("TOKEN".to_string(), "abc".to_string());

            let result = render_content(template, &vars);
            assert_eq!(result, "token=abc\n");
        }

        #[test]
        fn preserves_other_comments() {
            let template = "# This is a regular comment\ntoken={{TOKEN}}\n";
            let mut vars = std::collections::HashMap::new();
            vars.insert("TOKEN".to_string(), "xyz".to_string());

            let result = render_content(template, &vars);
            assert_eq!(result, "# This is a regular comment\ntoken=xyz\n");
        }

        #[test]
        fn handles_same_var_multiple_times() {
            let template = "first={{VAR}} second={{VAR}}\n";
            let mut vars = std::collections::HashMap::new();
            vars.insert("VAR".to_string(), "value".to_string());

            let result = render_content(template, &vars);
            assert_eq!(result, "first=value second=value\n");
        }

        #[test]
        fn leaves_unmatched_placeholders() {
            let template = "token={{UNKNOWN}}\n";
            let vars = std::collections::HashMap::new();

            let result = render_content(template, &vars);
            assert_eq!(result, "token={{UNKNOWN}}\n");
        }

        #[test]
        fn preserves_trailing_newline() {
            let template = "content\n";
            let vars = std::collections::HashMap::new();

            let result = render_content(template, &vars);
            assert!(result.ends_with('\n'));
        }

        #[test]
        fn handles_empty_template() {
            let template = "";
            let vars = std::collections::HashMap::new();

            let result = render_content(template, &vars);
            assert_eq!(result, "");
        }
    }
}

#[cfg(test)]
mod lock_tests {
    use super::*;
    use assert_fs::TempDir;
    use std::fs::OpenOptions;
    use std::time::Duration;

    fn open_temp_lock(dir: &std::path::Path, name: &str) -> std::fs::File {
        OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(dir.join(name))
            .unwrap()
    }

    #[test]
    fn uncontended_lock_succeeds_immediately() {
        let dir = TempDir::new().unwrap();
        let lock = open_temp_lock(dir.path(), "test.lock");

        let result = lock_exclusive_with_timeout(&lock, Duration::from_secs(1)).unwrap();
        assert!(result, "should acquire uncontended lock");
    }

    #[test]
    fn lock_times_out_when_held_by_another_thread() {
        use fs2::FileExt;

        let dir = TempDir::new().unwrap();
        let lock_path = dir.path().join("contended.lock");

        // Holder thread grabs the lock and keeps it.
        let holder = open_temp_lock(dir.path(), "contended.lock");
        holder.lock_exclusive().unwrap();

        // A second handle on the same file should time out.
        let contender = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lock_path)
            .unwrap();

        let result = lock_exclusive_with_timeout(&contender, Duration::from_millis(200)).unwrap();
        assert!(!result, "should time out while lock is held");

        // Clean up: release the holder lock so the background thread exits.
        let _ = holder.unlock();
    }

    #[test]
    fn lock_acquired_after_holder_releases() {
        use fs2::FileExt;

        let dir = TempDir::new().unwrap();
        let lock_path = dir.path().join("delayed.lock");

        let holder = open_temp_lock(dir.path(), "delayed.lock");
        holder.lock_exclusive().unwrap();

        // Release after a short delay in a separate thread.
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(100));
            let _ = holder.unlock();
        });

        let contender = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lock_path)
            .unwrap();

        let result = lock_exclusive_with_timeout(&contender, Duration::from_secs(5)).unwrap();
        assert!(result, "should acquire lock after holder releases");
    }

    #[test]
    fn per_account_locks_are_independent() {
        use fs2::FileExt;

        let dir = TempDir::new().unwrap();

        // Hold lock for account A.
        let lock_a = open_temp_lock(dir.path(), "account_a.lock");
        lock_a.lock_exclusive().unwrap();

        // Lock for account B should succeed immediately — different file.
        let lock_b = open_temp_lock(dir.path(), "account_b.lock");
        let result = lock_exclusive_with_timeout(&lock_b, Duration::from_millis(200)).unwrap();
        assert!(result, "account B lock should not be blocked by account A");

        let _ = lock_a.unlock();
    }
}

#[cfg(all(test, target_os = "macos"))]
mod concurrency_tests {
    use super::*;
    use crate::cache::cache_path_for_account;
    use assert_fs::TempDir;
    use std::time::Duration;

    /// Write an encrypted cache entry to a temp directory, reusing the same
    /// logic as the production code.
    fn write_test_cache(
        cache_root: &std::path::Path,
        account_id: &str,
        kind: CacheKind,
        output: &str,
    ) {
        use std::fs::OpenOptions;
        use std::io::Write;

        std::fs::create_dir_all(cache_root).unwrap();
        let path = cache_path_for_account(cache_root, account_id, kind);
        let encrypted = encrypt_cache(output.as_bytes()).unwrap();
        let mut file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&path)
            .unwrap();
        file.write_all(encrypted.as_bytes()).unwrap();
    }

    /// Read a cache entry from a temp directory.
    fn read_test_cache(
        cache_root: &std::path::Path,
        account_id: &str,
        kind: CacheKind,
        ttl: Duration,
    ) -> Option<String> {
        let path = cache_path_for_account(cache_root, account_id, kind);
        let metadata = match std::fs::metadata(&path) {
            Ok(m) => m,
            Err(_) => return None,
        };
        let modified = metadata.modified().ok()?;
        let age = modified.elapsed().unwrap_or_default();
        if age > ttl {
            return None;
        }
        let contents = std::fs::read_to_string(&path).ok()?;
        let decrypted = decrypt_cache(&contents).ok()?;
        Some(String::from_utf8_lossy(&decrypted).to_string())
    }

    #[test]
    fn atomic_write_not_visible_as_partial_data() {
        // Verify that using write-to-tmp + rename means a reader either sees
        // the old file or the new complete file — never a half-written file.
        let dir = TempDir::new().unwrap();
        let cache_root = dir.path().join("cache");
        let account = "test-atomic";

        // Write initial cache.
        let original = r#"{"KEY":"original"}"#;
        write_test_cache(&cache_root, account, CacheKind::ResolvedVars, original);

        let cache_root_clone = cache_root.clone();
        let reader_done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let reader_done_clone = reader_done.clone();

        // Spawn a reader that continuously reads the cache for a short window.
        let reader = std::thread::spawn(move || {
            let mut saw_values = Vec::new();
            let start = std::time::Instant::now();
            while start.elapsed() < Duration::from_millis(500) {
                if let Some(data) = read_test_cache(
                    &cache_root_clone,
                    account,
                    CacheKind::ResolvedVars,
                    Duration::from_secs(60),
                ) {
                    // Every read should be valid JSON — never a partial/corrupt
                    // string from a half-written file.
                    assert!(
                        serde_json::from_str::<std::collections::HashMap<String, String>>(&data)
                            .is_ok(),
                        "Reader saw invalid JSON: {data}"
                    );
                    saw_values.push(data);
                }
                std::thread::sleep(Duration::from_millis(1));
            }
            reader_done_clone.store(true, std::sync::atomic::Ordering::Release);
            saw_values
        });

        // Meanwhile, write a new value using the atomic approach.
        let updated = r#"{"KEY":"updated"}"#;
        let path = cache_path_for_account(&cache_root, account, CacheKind::ResolvedVars);
        let tmp_path = path.with_extension("cache.tmp");

        let encrypted = encrypt_cache(updated.as_bytes()).unwrap();
        std::fs::write(&tmp_path, &encrypted).unwrap();
        std::fs::rename(&tmp_path, &path).unwrap();

        let saw = reader.join().unwrap();
        // The reader should have seen at least one value, and every value
        // should be either the original or the updated content.
        assert!(
            !saw.is_empty(),
            "reader should have seen at least one cache value"
        );
        for val in &saw {
            assert!(
                val == original || val == updated,
                "unexpected cache content: {val}"
            );
        }
    }

    #[test]
    fn double_check_prevents_redundant_resolve() {
        // Verify the double-check pattern: after acquiring a contended lock,
        // the cache should be re-checked. If another holder populated it,
        // we get a hit and skip resolution.
        //
        // We simulate this by:
        // 1. Having "process 1" hold the lock, write cache, then release.
        // 2. Having "process 2" wait for the lock via blocking lock_exclusive,
        //    then read cache — it should see the data from process 1.
        use fs2::FileExt;

        let dir = TempDir::new().unwrap();
        let cache_root = dir.path().join("cache");
        let lock_path = dir.path().join("account.lock");

        let account = "double-check-test";
        let expected = r#"{"SECRET":"from_process_1"}"#;

        // Create the lock file and have "process 1" hold it.
        let lock_file = std::fs::OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
            .unwrap();
        lock_file.lock_exclusive().unwrap();

        let cache_root_clone = cache_root.clone();
        let lock_path_clone = lock_path.clone();

        // "Process 2" thread: blocks on lock_exclusive, then double-checks cache.
        let process2 = std::thread::spawn(move || {
            let lock = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .open(&lock_path_clone)
                .unwrap();

            // Blocking acquire — will wait until process 1 releases.
            lock.lock_exclusive().unwrap();

            // Double-check: read cache after acquiring lock.
            let cached = read_test_cache(
                &cache_root_clone,
                account,
                CacheKind::ResolvedVars,
                Duration::from_secs(60),
            );

            let _ = lock.unlock();
            cached
        });

        // Give process 2 time to start blocking on the lock.
        std::thread::sleep(Duration::from_millis(50));

        // "Process 1": write cache, then release lock.
        write_test_cache(&cache_root, account, CacheKind::ResolvedVars, expected);
        let _ = lock_file.unlock();

        // Process 2 should have found a cache hit — no need to resolve.
        let result = process2.join().unwrap();
        assert_eq!(
            result.as_deref(),
            Some(expected),
            "process 2 should see cache populated by process 1"
        );
    }
}