agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
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
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
//! Common utilities and shared functionality for CLI commands.
//!
//! This module provides reusable infrastructure for install and update commands:
//!
//! # Core Components
//!
//! - **`CommandExecutor` trait**: Standardized command execution pattern
//! - **`CommandContext`**: Manifest and lockfile management utilities
//! - **`OperationMode` enum**: Distinguishes install vs update for shared logic
//!
//! # Shared Display Helpers
//!
//! - **`display_dry_run_results()`**: Rich dry-run output with CI exit codes
//! - **`display_no_changes()`**: Context-appropriate "no changes" messages
//!
//! # Legacy Support
//!
//! - **`handle_legacy_ccpm_migration()`**: CCPM to AGPM migration utilities
//! - **`check_for_legacy_ccpm_files()`**: Detects old CCPM installations
//!
//! # Lockfile Management
//!
//! - **`load_lockfile()`**: Loads lockfile with automatic regeneration
//! - **`save_lockfile()`**: Saves lockfile with error handling
//! - **`backup_and_regenerate_lockfile()`**: Recovery from corrupted lockfiles

use anyhow::{Context, Result};
use colored::Colorize;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use tokio::io::{AsyncBufReadExt, BufReader};

use crate::manifest::{Manifest, find_manifest};

/// Common trait for CLI command execution pattern
pub trait CommandExecutor: Sized {
    /// Execute the command, finding the manifest automatically
    fn execute(self) -> impl std::future::Future<Output = Result<()>> + Send
    where
        Self: Send,
    {
        async move {
            let manifest_path = if let Ok(path) = find_manifest() {
                path
            } else {
                // Check if legacy CCPM files exist and offer interactive migration
                // Default to interactive mode (yes=false); commands with --yes flag
                // should use their own implementation
                match handle_legacy_ccpm_migration(None, false).await {
                    Ok(Some(path)) => path,
                    Ok(None) => {
                        return Err(anyhow::anyhow!(
                            "No agpm.toml found in current directory or any parent directory. \
                             Run 'agpm init' to create a new project."
                        ));
                    }
                    Err(e) => return Err(e),
                }
            };
            self.execute_from_path(manifest_path).await
        }
    }

    /// Execute the command with a specific manifest path
    fn execute_from_path(
        self,
        manifest_path: PathBuf,
    ) -> impl std::future::Future<Output = Result<()>> + Send;
}

/// Common context for CLI commands that need manifest and project information
#[derive(Debug)]
pub struct CommandContext {
    /// Parsed project manifest (agpm.toml)
    pub manifest: Manifest,
    /// Path to the manifest file
    pub manifest_path: PathBuf,
    /// Project root directory (containing agpm.toml)
    pub project_dir: PathBuf,
    /// Path to the lockfile (agpm.lock)
    pub lockfile_path: PathBuf,
}

impl CommandContext {
    /// Create a new command context from a manifest and project directory
    pub fn new(manifest: Manifest, project_dir: PathBuf) -> Result<Self> {
        let lockfile_path = project_dir.join("agpm.lock");
        Ok(Self {
            manifest,
            manifest_path: project_dir.join("agpm.toml"),
            project_dir,
            lockfile_path,
        })
    }

    /// Create a new command context from a manifest path
    ///
    /// # Errors
    /// Returns an error if the manifest file doesn't exist or cannot be read
    pub fn from_manifest_path(manifest_path: impl AsRef<Path>) -> Result<Self> {
        let manifest_path = manifest_path.as_ref();

        if !manifest_path.exists() {
            return Err(anyhow::anyhow!("Manifest file {} not found", manifest_path.display()));
        }

        let project_dir = manifest_path
            .parent()
            .ok_or_else(|| anyhow::anyhow!("Invalid manifest path"))?
            .to_path_buf();

        let manifest = Manifest::load(manifest_path).with_context(|| {
            format!("Failed to parse manifest file: {}", manifest_path.display())
        })?;

        let lockfile_path = project_dir.join("agpm.lock");

        Ok(Self {
            manifest,
            manifest_path: manifest_path.to_path_buf(),
            project_dir,
            lockfile_path,
        })
    }

    /// Reload the manifest from disk.
    ///
    /// This should be called after any operation that modifies the manifest file,
    /// such as migration updating the tools configuration.
    ///
    /// # Errors
    /// Returns an error if the manifest file cannot be loaded or parsed.
    pub fn reload_manifest(&mut self) -> Result<()> {
        self.manifest = Manifest::load(&self.manifest_path).with_context(|| {
            format!("Failed to reload manifest file: {}", self.manifest_path.display())
        })?;
        Ok(())
    }

    /// Load an existing lockfile if it exists
    ///
    /// # Errors
    /// Returns an error if the lockfile exists but cannot be parsed
    pub fn load_lockfile(&self) -> Result<Option<crate::lockfile::LockFile>> {
        if self.lockfile_path.exists() {
            let lockfile =
                crate::lockfile::LockFile::load(&self.lockfile_path).with_context(|| {
                    format!("Failed to load lockfile: {}", self.lockfile_path.display())
                })?;
            Ok(Some(lockfile))
        } else {
            Ok(None)
        }
    }

    /// Load an existing lockfile with automatic regeneration for invalid files
    ///
    /// If the lockfile exists but is invalid or corrupted, this method will
    /// offer to automatically regenerate it. This provides a better user
    /// experience by recovering from common lockfile issues.
    ///
    /// # Arguments
    ///
    /// * `can_regenerate` - Whether automatic regeneration should be offered
    /// * `operation_name` - Name of the operation for error messages (e.g., "list")
    ///
    /// # Returns
    ///
    /// * `Ok(Some(lockfile))` - Successfully loaded or regenerated lockfile
    /// * `Ok(None)` - No lockfile exists (not an error)
    /// * `Err` - Critical error that cannot be recovered from
    ///
    /// # Behavior
    ///
    /// - **Interactive mode** (TTY): Prompts user with Y/n confirmation
    /// - **Non-interactive mode** (CI/CD): Fails with helpful error message
    /// - **Backup strategy**: Copies invalid lockfile to `agpm.lock.invalid` before regeneration
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use anyhow::Result;
    /// # use agpm_cli::cli::common::CommandContext;
    /// # use agpm_cli::manifest::Manifest;
    /// # use std::path::PathBuf;
    /// # async fn example() -> Result<()> {
    /// let manifest = Manifest::load(&PathBuf::from("agpm.toml"))?;
    /// let project_dir = PathBuf::from(".");
    /// let ctx = CommandContext::new(manifest, project_dir)?;
    /// match ctx.load_lockfile_with_regeneration(true, "list") {
    ///     Ok(Some(lockfile)) => println!("Loaded lockfile"),
    ///     Ok(None) => println!("No lockfile found"),
    ///     Err(e) => eprintln!("Error: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn load_lockfile_with_regeneration(
        &self,
        can_regenerate: bool,
        operation_name: &str,
    ) -> Result<Option<crate::lockfile::LockFile>> {
        // If lockfile doesn't exist, that's not an error
        if !self.lockfile_path.exists() {
            return Ok(None);
        }

        // Try to load the lockfile
        match crate::lockfile::LockFile::load(&self.lockfile_path) {
            Ok(mut lockfile) => {
                // Also load and merge private lockfile if it exists
                if let Ok(Some(private_lock)) =
                    crate::lockfile::PrivateLockFile::load(&self.project_dir)
                {
                    lockfile.merge_private(&private_lock);
                }
                // If private lockfile fails to load or doesn't exist, we just skip it
                // (it could be corrupted or from a different version)
                Ok(Some(lockfile))
            }
            Err(e) => {
                // Analyze the error to see if it's recoverable
                let error_msg = e.to_string();
                let can_auto_recover = can_regenerate
                    && (error_msg.contains("Invalid TOML syntax")
                        || error_msg.contains("Lockfile version")
                        || error_msg.contains("missing field")
                        || error_msg.contains("invalid type")
                        || error_msg.contains("expected"));

                if !can_auto_recover {
                    // Not a recoverable error, return the original error
                    return Err(e);
                }

                // This is a recoverable error, offer regeneration
                let backup_path = self.lockfile_path.with_extension("lock.invalid");

                // Create user-friendly message
                let regenerate_message = format!(
                    "The lockfile appears to be invalid or corrupted.\n\n\
                     Error: {}\n\n\
                     Note: The lockfile format is not yet stable as this is beta software.\n\n\
                     The invalid lockfile will be backed up to: {}",
                    error_msg,
                    backup_path.display()
                );

                // Check if we're in interactive mode
                if io::stdin().is_terminal() {
                    // Interactive mode: prompt user
                    println!("{}", regenerate_message);
                    print!("Would you like to regenerate the lockfile automatically? [Y/n] ");
                    // Unwrap justified: stdout flush only fails on catastrophic OS errors
                    io::stdout().flush().unwrap();

                    let mut input = String::new();
                    match io::stdin().read_line(&mut input) {
                        Ok(_) => {
                            let response = input.trim().to_lowercase();
                            if response.is_empty() || response == "y" || response == "yes" {
                                // User agreed to regenerate
                                self.backup_and_regenerate_lockfile(&backup_path, operation_name)?;
                                Ok(None) // Return None so caller creates new lockfile
                            } else {
                                // User declined, return the original error
                                Err(crate::core::AgpmError::InvalidLockfileError {
                                    file: self.lockfile_path.display().to_string(),
                                    reason: format!(
                                        "{} (User declined automatic regeneration)",
                                        error_msg
                                    ),
                                    can_regenerate: true,
                                }
                                .into())
                            }
                        }
                        Err(_) => {
                            // Failed to read input, fall back to non-interactive behavior
                            Err(self.create_non_interactive_error(&error_msg, operation_name))
                        }
                    }
                } else {
                    // Non-interactive mode: fail with helpful message
                    Err(self.create_non_interactive_error(&error_msg, operation_name))
                }
            }
        }
    }

    /// Backup the invalid lockfile and display regeneration instructions
    fn backup_and_regenerate_lockfile(
        &self,
        backup_path: &Path,
        operation_name: &str,
    ) -> Result<()> {
        // Backup the invalid lockfile
        if let Err(e) = std::fs::copy(&self.lockfile_path, backup_path) {
            eprintln!("Warning: Failed to backup invalid lockfile: {}", e);
        } else {
            println!("✓ Backed up invalid lockfile to: {}", backup_path.display());
        }

        // Remove the invalid lockfile
        if let Err(e) = std::fs::remove_file(&self.lockfile_path) {
            return Err(anyhow::anyhow!("Failed to remove invalid lockfile: {}", e));
        }

        println!("✓ Removed invalid lockfile");
        println!("Note: Run 'agpm install' to regenerate the lockfile");

        // If this is not an install command, suggest running install
        if operation_name != "install" {
            println!("Alternatively, run 'agpm {} --regenerate' if available", operation_name);
        }

        Ok(())
    }

    /// Create a non-interactive error message for CI/CD environments
    fn create_non_interactive_error(
        &self,
        error_msg: &str,
        _operation_name: &str,
    ) -> anyhow::Error {
        let backup_path = self.lockfile_path.with_extension("lock.invalid");

        crate::core::AgpmError::InvalidLockfileError {
            file: self.lockfile_path.display().to_string(),
            reason: format!(
                "{}\n\n\
                 To fix this issue:\n\
                 1. Backup the invalid lockfile: cp agpm.lock {}\n\
                 2. Remove the invalid lockfile: rm agpm.lock\n\
                 3. Regenerate it: agpm install\n\n\
                 Note: The lockfile format is not yet stable as this is beta software.",
                error_msg,
                backup_path.display()
            ),
            can_regenerate: true,
        }
        .into()
    }

    /// Save a lockfile to the project directory
    ///
    /// # Errors
    /// Returns an error if the lockfile cannot be written
    pub fn save_lockfile(&self, lockfile: &crate::lockfile::LockFile) -> Result<()> {
        lockfile
            .save(&self.lockfile_path)
            .with_context(|| format!("Failed to save lockfile: {}", self.lockfile_path.display()))
    }
}

/// Handle legacy CCPM files by offering interactive migration.
///
/// This function searches for ccpm.toml and ccpm.lock files in the current
/// directory and parent directories. If found, it prompts the user to migrate
/// and performs the migration if they accept.
///
/// # Behavior
///
/// - **Interactive mode**: Prompts user with Y/n confirmation (stdin is a TTY)
/// - **Non-interactive mode**: Returns `Ok(None)` if stdin is not a TTY (e.g., CI/CD)
/// - **Auto-accept mode**: When `yes` is true, accepts migration without prompting
/// - **Search scope**: Traverses from current directory to filesystem root
///
/// # Arguments
///
/// * `from_dir` - Optional starting directory for the search
/// * `yes` - When true, automatically accept migration prompts without user interaction
///
/// # Returns
///
/// - `Ok(Some(PathBuf))` with the path to agpm.toml if migration succeeded
/// - `Ok(None)` if no legacy files were found OR user declined OR non-interactive mode
/// - `Err` if migration failed
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # async fn example() -> Result<()> {
/// use agpm_cli::cli::common::handle_legacy_ccpm_migration;
///
/// // Interactive mode
/// match handle_legacy_ccpm_migration(None, false).await? {
///     Some(path) => println!("Migrated to: {}", path.display()),
///     None => println!("No migration performed"),
/// }
///
/// // Auto-accept mode (for CI/scripts)
/// match handle_legacy_ccpm_migration(None, true).await? {
///     Some(path) => println!("Migrated to: {}", path.display()),
///     None => println!("No legacy files found"),
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - Unable to access current directory (when `from_dir` is None)
/// - Unable to perform migration operations
pub async fn handle_legacy_ccpm_migration(
    from_dir: Option<PathBuf>,
    yes: bool,
) -> Result<Option<PathBuf>> {
    let current_dir = match from_dir {
        Some(dir) => dir,
        None => std::env::current_dir()?,
    };
    let legacy_dir = find_legacy_ccpm_directory(&current_dir);

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

    // Check if we're in an interactive terminal (unless --yes flag is set)
    if !yes && !std::io::stdin().is_terminal() {
        // Non-interactive mode: Don't prompt, just inform and exit
        eprintln!("{}", "Legacy CCPM files detected (non-interactive mode).".yellow());
        eprintln!(
            "Run {} to migrate manually, or use --yes to auto-accept.",
            format!("agpm migrate --path {}", dir.display()).cyan()
        );
        return Ok(None);
    }

    // Found legacy files - prompt for migration (or auto-accept if --yes)
    let ccpm_toml = dir.join("ccpm.toml");
    let ccpm_lock = dir.join("ccpm.lock");

    let mut files = Vec::new();
    if ccpm_toml.exists() {
        files.push("ccpm.toml");
    }
    if ccpm_lock.exists() {
        files.push("ccpm.lock");
    }

    let files_str = files.join(" and ");

    println!("{}", "Legacy CCPM files detected!".yellow().bold());
    println!("{} {} found in {}", "→".cyan(), files_str, dir.display());
    println!();

    // Auto-accept if --yes flag is set, otherwise prompt
    let should_migrate = if yes {
        true
    } else {
        // Prompt user for migration
        print!("{} ", "Would you like to migrate to AGPM now? [Y/n]:".green());
        io::stdout().flush()?;

        // Use async I/O for proper integration with Tokio runtime
        let mut reader = BufReader::new(tokio::io::stdin());
        let mut response = String::new();
        reader.read_line(&mut response).await?;
        let response = response.trim().to_lowercase();
        response.is_empty() || response == "y" || response == "yes"
    };

    if should_migrate {
        println!();
        println!("{}", "🚀 Starting migration...".cyan());

        // Perform the migration with automatic installation
        let migrate_cmd = super::migrate::MigrateCommand::new(Some(dir.clone()), false, false);

        migrate_cmd.execute().await?;

        // Return the path to the newly created agpm.toml
        Ok(Some(dir.join("agpm.toml")))
    } else {
        println!();
        println!("{}", "Migration cancelled.".yellow());
        println!(
            "Run {} to migrate manually.",
            format!("agpm migrate --path {}", dir.display()).cyan()
        );
        Ok(None)
    }
}

/// Handle legacy format migration (old gitignore-managed → agpm/ subdirectory).
///
/// This function detects if a project has resources at old paths (not in agpm/
/// subdirectory) and offers interactive migration to the new format.
///
/// # Behavior
///
/// - **Interactive mode**: Prompts user with Y/n confirmation (stdin is a TTY)
/// - **Non-interactive mode**: Returns `Ok(false)` if stdin is not a TTY (e.g., CI/CD)
/// - **Auto-accept mode**: When `yes` is true, accepts migration without prompting
/// - **Detection**: Uses lockfile to identify AGPM-managed files at old paths
///
/// # Arguments
///
/// * `project_dir` - Path to the project directory
/// * `yes` - When true, automatically accept migration prompts without user interaction
///
/// # Returns
///
/// - `Ok(true)` if migration was performed
/// - `Ok(false)` if no migration needed OR user declined OR non-interactive mode
/// - `Err` if migration failed
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # async fn example() -> Result<()> {
/// use agpm_cli::cli::common::handle_legacy_format_migration;
/// use std::path::Path;
///
/// // Interactive mode
/// let migrated = handle_legacy_format_migration(Path::new("."), false).await?;
/// if migrated {
///     println!("Format migration complete!");
/// }
///
/// // Auto-accept mode (for CI/scripts)
/// let migrated = handle_legacy_format_migration(Path::new("."), true).await?;
/// # Ok(())
/// # }
/// ```
pub async fn handle_legacy_format_migration(project_dir: &Path, yes: bool) -> Result<bool> {
    use super::migrate::{detect_old_format, run_format_migration};

    let detection = detect_old_format(project_dir);

    if !detection.needs_migration() {
        return Ok(false);
    }

    // Check if we're in an interactive terminal (unless --yes flag is set)
    if !yes && !std::io::stdin().is_terminal() {
        // Non-interactive mode: Don't prompt, just inform
        eprintln!("{}", "Legacy AGPM format detected (non-interactive mode).".yellow());
        eprintln!(
            "Run {} to migrate manually, or use --yes to auto-accept.",
            format!("agpm migrate --path {}", project_dir.display()).cyan()
        );
        return Ok(false);
    }

    // Show what was detected
    println!("{}", "Legacy AGPM format detected!".yellow().bold());

    if !detection.old_resource_paths.is_empty() {
        println!(
            "\n{} Found {} resources at old paths:",
            "→".cyan(),
            detection.old_resource_paths.len()
        );
        for path in &detection.old_resource_paths {
            let rel = path.strip_prefix(project_dir).unwrap_or(path);
            println!("    • {}", rel.display());
        }
    }

    if detection.has_managed_gitignore_section {
        println!("\n{} Found AGPM/CCPM managed section in .gitignore", "→".cyan());
    }

    println!();
    println!(
        "{}",
        "The new format uses agpm/ subdirectories for easier gitignore management.".dimmed()
    );
    println!();

    // Auto-accept if --yes flag is set, otherwise prompt
    let should_migrate = if yes {
        true
    } else {
        // Prompt user for migration
        print!("{} ", "Would you like to migrate to the new format now? [Y/n]:".green());
        io::stdout().flush()?;

        // Use async I/O for proper integration with Tokio runtime
        let mut reader = BufReader::new(tokio::io::stdin());
        let mut response = String::new();
        reader.read_line(&mut response).await?;
        let response = response.trim().to_lowercase();
        response.is_empty() || response == "y" || response == "yes"
    };

    if should_migrate {
        println!();
        run_format_migration(project_dir).await?;
        Ok(true)
    } else {
        println!();
        println!("{}", "Migration cancelled.".yellow());
        println!(
            "Run {} to migrate manually.",
            format!("agpm migrate --path {}", project_dir.display()).cyan()
        );
        Ok(false)
    }
}

/// Check for legacy CCPM files and return a migration message if found.
///
/// This function searches for ccpm.toml and ccpm.lock files in the current
/// directory and parent directories, similar to how `find_manifest` works.
/// If legacy files are found, it returns a helpful error message suggesting
/// to run the migration command.
///
/// # Returns
///
/// - `Some(String)` with migration instructions if legacy files are found
/// - `None` if no legacy files are detected
#[must_use]
pub fn check_for_legacy_ccpm_files() -> Option<String> {
    check_for_legacy_ccpm_files_from(std::env::current_dir().ok()?)
}

/// Find the directory containing legacy CCPM files.
///
/// Searches for ccpm.toml or ccpm.lock starting from the given directory
/// and walking up the directory tree.
///
/// # Returns
///
/// - `Some(PathBuf)` with the directory containing legacy files
/// - `None` if no legacy files are found
fn find_legacy_ccpm_directory(start_dir: &Path) -> Option<PathBuf> {
    let mut dir = start_dir;

    loop {
        let ccpm_toml = dir.join("ccpm.toml");
        let ccpm_lock = dir.join("ccpm.lock");

        if ccpm_toml.exists() || ccpm_lock.exists() {
            return Some(dir.to_path_buf());
        }

        dir = dir.parent()?;
    }
}

/// Check for legacy CCPM files starting from a specific directory.
///
/// This is the internal implementation that allows for testing without
/// changing the current working directory.
fn check_for_legacy_ccpm_files_from(start_dir: PathBuf) -> Option<String> {
    let current = start_dir;
    let mut dir = current.as_path();

    loop {
        let ccpm_toml = dir.join("ccpm.toml");
        let ccpm_lock = dir.join("ccpm.lock");

        if ccpm_toml.exists() || ccpm_lock.exists() {
            let mut files = Vec::new();
            if ccpm_toml.exists() {
                files.push("ccpm.toml");
            }
            if ccpm_lock.exists() {
                files.push("ccpm.lock");
            }

            let files_str = files.join(" and ");
            let location = if dir == current {
                "current directory".to_string()
            } else {
                format!("parent directory: {}", dir.display())
            };

            return Some(format!(
                "{}\n\n{} {} found in {}.\n{}\n  {}\n\n{}",
                "Legacy CCPM files detected!".yellow().bold(),
                "→".cyan(),
                files_str,
                location,
                "Run the migration command to upgrade:".yellow(),
                format!("agpm migrate --path {}", dir.display()).cyan().bold(),
                "Or run 'agpm init' to create a new AGPM project.".dimmed()
            ));
        }

        dir = dir.parent()?;
    }
}

/// Determines the type of operation being performed for user-facing messages.
///
/// This enum distinguishes between install and update operations to provide
/// appropriate feedback messages and exit codes. Used by shared helper functions
/// like `display_dry_run_results()` and `display_no_changes()` to customize
/// behavior based on the operation context.
///
/// # Examples
///
/// ```rust
/// use agpm_cli::cli::common::OperationMode;
///
/// let mode = OperationMode::Install;
/// // Used to determine appropriate "no changes" message:
/// // Install: "No dependencies to install"
/// // Update: "All dependencies are up to date!"
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationMode {
    /// Fresh installation operation (agpm install)
    Install,
    /// Dependency update operation (agpm update)
    Update,
}

/// Display dry-run results with rich categorization of changes.
///
/// Shows new resources, updated resources, and unchanged count.
/// **IMPORTANT**: Returns an error (exit code 1) if changes are detected,
/// making this suitable for CI validation workflows.
///
/// # Arguments
///
/// * `new_lockfile` - The lockfile that would be created
/// * `existing_lockfile` - The current lockfile if it exists
/// * `quiet` - Whether to suppress output
///
/// # Returns
///
/// * `Ok(())` - No changes detected (exit code 0)
/// * `Err(...)` - Changes detected (exit code 1 for CI validation)
///
/// # CI/CD Usage
///
/// This function is designed for CI validation workflows where you want
/// to detect if running install/update would make changes:
///
/// ```bash
/// # CI pipeline check - fails if dependencies need updating
/// agpm install --dry-run  # Exit code 1 if changes needed
/// agpm update --dry-run   # Exit code 1 if updates available
/// ```
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # use agpm_cli::cli::common::display_dry_run_results;
/// # use agpm_cli::lockfile::LockFile;
/// # fn example() -> Result<()> {
/// let new_lockfile = LockFile::new();
/// let existing_lockfile = None;
///
/// // In CI: this will return Err if changes detected
/// display_dry_run_results(
///     &new_lockfile,
///     existing_lockfile.as_ref(),
///     false,
/// )?;
/// # Ok(())
/// # }
/// ```
///
/// # Output Format
///
/// When changes are detected, displays:
/// - **New resources**: Resources that would be installed (green)
/// - **Updated resources**: Resources that would be updated (yellow)
/// - **Unchanged count**: Resources that are already up to date (dimmed)
pub fn display_dry_run_results(
    new_lockfile: &crate::lockfile::LockFile,
    existing_lockfile: Option<&crate::lockfile::LockFile>,
    quiet: bool,
) -> Result<()> {
    // 1. Categorize changes
    let (new_resources, updated_resources, unchanged_count) =
        categorize_resource_changes(new_lockfile, existing_lockfile);

    // 2. Display results
    let has_changes = !new_resources.is_empty() || !updated_resources.is_empty();
    display_dry_run_output(&new_resources, &updated_resources, unchanged_count, quiet);

    // 3. Return CI exit code
    if has_changes {
        Err(anyhow::anyhow!("Dry-run detected changes (exit 1)"))
    } else {
        Ok(())
    }
}

/// Represents a new resource to be installed.
#[derive(Debug, Clone)]
struct NewResource {
    resource_type: String,
    name: String,
    version: String,
}

/// Represents a resource being updated.
#[derive(Debug, Clone)]
struct UpdatedResource {
    resource_type: String,
    name: String,
    old_version: String,
    new_version: String,
}

/// Categorize resources into new, updated, and unchanged.
///
/// Compares a new lockfile against an existing lockfile to determine what has changed.
/// Returns tuple of (new_resources, updated_resources, unchanged_count).
fn categorize_resource_changes(
    new_lockfile: &crate::lockfile::LockFile,
    existing_lockfile: Option<&crate::lockfile::LockFile>,
) -> (Vec<NewResource>, Vec<UpdatedResource>, usize) {
    use crate::core::resource_iterator::ResourceIterator;

    let mut new_resources = Vec::new();
    let mut updated_resources = Vec::new();
    let mut unchanged_count = 0;

    // Compare lockfiles to find changes
    if let Some(existing) = existing_lockfile {
        ResourceIterator::for_each_resource(new_lockfile, |resource_type, new_entry| {
            // Find corresponding entry in existing lockfile
            if let Some((_, old_entry)) = ResourceIterator::find_resource_by_name_and_source(
                existing,
                &new_entry.name,
                new_entry.source.as_deref(),
            ) {
                // Check if it was updated
                if old_entry.resolved_commit == new_entry.resolved_commit {
                    unchanged_count += 1;
                } else {
                    let old_version =
                        old_entry.version.clone().unwrap_or_else(|| "latest".to_string());
                    let new_version =
                        new_entry.version.clone().unwrap_or_else(|| "latest".to_string());
                    updated_resources.push(UpdatedResource {
                        resource_type: resource_type.to_string(),
                        name: new_entry.name.clone(),
                        old_version,
                        new_version,
                    });
                }
            } else {
                // New resource
                new_resources.push(NewResource {
                    resource_type: resource_type.to_string(),
                    name: new_entry.name.clone(),
                    version: new_entry.version.clone().unwrap_or_else(|| "latest".to_string()),
                });
            }
        });
    } else {
        // No existing lockfile, everything is new
        ResourceIterator::for_each_resource(new_lockfile, |resource_type, new_entry| {
            new_resources.push(NewResource {
                resource_type: resource_type.to_string(),
                name: new_entry.name.clone(),
                version: new_entry.version.clone().unwrap_or_else(|| "latest".to_string()),
            });
        });
    }

    (new_resources, updated_resources, unchanged_count)
}

/// Format and display dry-run results.
///
/// Displays new resources, updated resources, and unchanged count with rich formatting.
/// Shows nothing if quiet mode is enabled.
fn display_dry_run_output(
    new_resources: &[NewResource],
    updated_resources: &[UpdatedResource],
    unchanged_count: usize,
    quiet: bool,
) {
    if quiet {
        return;
    }

    let has_changes = !new_resources.is_empty() || !updated_resources.is_empty();

    if has_changes {
        println!("{}", "Dry run - the following changes would be made:".yellow());
        println!();

        if !new_resources.is_empty() {
            println!("{}", "New resources:".green().bold());
            for resource in new_resources {
                println!(
                    "  {} {} ({})",
                    "+".green(),
                    resource.name.cyan(),
                    format!("{} {}", resource.resource_type, resource.version).dimmed()
                );
            }
            println!();
        }

        if !updated_resources.is_empty() {
            println!("{}", "Updated resources:".yellow().bold());
            for resource in updated_resources {
                print!(
                    "  {} {} {} → ",
                    "~".yellow(),
                    resource.name.cyan(),
                    resource.old_version.yellow()
                );
                println!("{} ({})", resource.new_version.green(), resource.resource_type.dimmed());
            }
            println!();
        }

        if unchanged_count > 0 {
            println!("{}", format!("{unchanged_count} unchanged resources").dimmed());
        }

        println!();
        println!(
            "{}",
            format!(
                "Total: {} new, {} updated, {} unchanged",
                new_resources.len(),
                updated_resources.len(),
                unchanged_count
            )
            .bold()
        );
        println!();
        println!("{}", "No files were modified (dry-run mode)".yellow());
    } else {
        println!("✓ {}", "No changes would be made".green());
    }
}

/// Display "no changes" message appropriate for the operation mode.
///
/// Shows a message indicating no changes were made, with different messages
/// depending on whether this was an install or update operation.
///
/// # Arguments
///
/// * `mode` - The operation mode (install or update)
/// * `quiet` - Whether to suppress output
///
/// # Examples
///
/// ```no_run
/// use agpm_cli::cli::common::{display_no_changes, OperationMode};
///
/// display_no_changes(OperationMode::Install, false);
/// display_no_changes(OperationMode::Update, false);
/// ```
pub fn display_no_changes(mode: OperationMode, quiet: bool) {
    if quiet {
        return;
    }

    match mode {
        OperationMode::Install => println!("No dependencies to install"),
        OperationMode::Update => println!("All dependencies are up to date!"),
    }
}

/// Handle missing gitignore entries by offering to add them interactively.
///
/// When missing gitignore entries are detected, this function offers to add
/// the standard AGPM managed paths section to the project's `.gitignore` file.
/// It follows the same interactive pattern as the legacy migration handlers.
///
/// # Behavior
///
/// - **Interactive mode** (TTY): Prompts user with Y/n confirmation
/// - **Non-interactive mode** (CI/CD): Prints warning and returns
/// - **Auto-accept mode**: When `yes` is true, adds entries without prompting
///
/// # Arguments
///
/// * `validation` - The `ConfigValidation` result containing missing entries
/// * `project_dir` - Path to the project directory
/// * `yes` - When true, automatically accept without prompting
///
/// # Returns
///
/// - `Ok(true)` if entries were added successfully
/// - `Ok(false)` if no entries were added (user declined, non-interactive, or empty)
/// - `Err` if write operation failed
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # async fn example() -> Result<()> {
/// use agpm_cli::cli::common::handle_missing_gitignore_entries;
/// use agpm_cli::installer::ConfigValidation;
/// use std::path::Path;
///
/// let validation = ConfigValidation::default();
///
/// // Interactive mode
/// let added = handle_missing_gitignore_entries(&validation, Path::new("."), false).await?;
///
/// // Auto-accept mode (for CI/scripts with --yes flag)
/// let added = handle_missing_gitignore_entries(&validation, Path::new("."), true).await?;
/// # Ok(())
/// # }
/// ```
pub async fn handle_missing_gitignore_entries(
    validation: &crate::installer::ConfigValidation,
    project_dir: &Path,
    yes: bool,
) -> Result<bool> {
    use super::migrate::{AGPM_MANAGED_PATHS, AGPM_MANAGED_PATHS_END};
    use tokio::io::AsyncWriteExt;

    // Early return if no missing entries
    if validation.missing_gitignore_entries.is_empty() {
        return Ok(false);
    }

    let missing = &validation.missing_gitignore_entries;
    let gitignore_path = project_dir.join(".gitignore");

    // Check if managed section already exists (avoid duplicates)
    if gitignore_path.exists() {
        if let Ok(content) = tokio::fs::read_to_string(&gitignore_path).await {
            if content.contains(AGPM_MANAGED_PATHS) {
                // Section exists but validation still found missing entries
                // This means user has partial entries - just warn, don't modify
                eprintln!("\n{}", "Warning: Missing gitignore entries detected:".yellow());
                for entry in missing {
                    eprintln!("  {}", entry);
                }
                eprintln!(
                    "\nThe {} section exists but may need manual updates.",
                    AGPM_MANAGED_PATHS.cyan()
                );
                return Ok(false);
            }
        }
    }

    // Check if we're in an interactive terminal (unless --yes flag is set)
    if !yes && !std::io::stdin().is_terminal() {
        // Non-interactive mode: print warning and return
        eprintln!("\n{}", "Missing gitignore entries detected:".yellow());
        for entry in missing {
            eprintln!("  {}", entry);
        }
        eprintln!("\nRun with {} to add them automatically, or add manually.", "--yes".cyan());
        return Ok(false);
    }

    // Show what we found
    println!("\n{}", "Missing .gitignore entries detected:".yellow().bold());
    for entry in missing {
        println!("  {} {}", "→".cyan(), entry);
    }
    println!();

    // Auto-accept if --yes flag is set, otherwise prompt
    let should_add = if yes {
        true
    } else {
        print!("{} ", "Would you like to add them now? [Y/n]:".green());
        io::stdout().flush()?;

        let mut reader = BufReader::new(tokio::io::stdin());
        let mut response = String::new();
        reader.read_line(&mut response).await?;
        let response = response.trim().to_lowercase();
        response.is_empty() || response == "y" || response == "yes"
    };

    if !should_add {
        println!("{}", "Skipped adding gitignore entries.".yellow());
        return Ok(false);
    }

    // Build the managed section content
    let mut content = String::new();

    // Add newline separator if appending to existing file
    if gitignore_path.exists() {
        let existing = tokio::fs::read_to_string(&gitignore_path).await.unwrap_or_default();
        if !existing.is_empty() && !existing.ends_with('\n') {
            content.push('\n');
        }
        content.push('\n');
    }

    content.push_str(AGPM_MANAGED_PATHS);
    content.push('\n');
    content.push_str(".claude/*/agpm/\n");
    content.push_str(".opencode/*/agpm/\n");
    content.push_str(".agpm/\n");
    content.push_str("agpm.private.toml\n");
    content.push_str("agpm.private.lock\n");
    content.push_str(AGPM_MANAGED_PATHS_END);
    content.push('\n');

    // Append to .gitignore (creates if doesn't exist)
    let mut file = tokio::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&gitignore_path)
        .await
        .context("Failed to open .gitignore for writing")?;

    file.write_all(content.as_bytes()).await.context("Failed to write to .gitignore")?;

    // Ensure data is flushed to disk
    file.sync_all().await.context("Failed to sync .gitignore")?;

    println!("{} Added AGPM managed paths section to .gitignore", "✓".green());

    Ok(true)
}

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

    #[test]
    fn test_command_context_from_manifest_path() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        // Create a test manifest
        std::fs::write(
            &manifest_path,
            r#"
[sources]
test = "https://github.com/test/repo.git"

[agents]
"#,
        )
        .unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();

        assert_eq!(context.manifest_path, manifest_path);
        assert_eq!(context.project_dir, temp_dir.path());
        assert_eq!(context.lockfile_path, temp_dir.path().join("agpm.lock"));
        assert!(context.manifest.sources.contains_key("test"));
    }

    #[test]
    fn test_command_context_missing_manifest() {
        let result = CommandContext::from_manifest_path("/nonexistent/agpm.toml");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_command_context_invalid_manifest() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        // Create an invalid manifest
        std::fs::write(&manifest_path, "invalid toml {{").unwrap();

        let result = CommandContext::from_manifest_path(&manifest_path);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Failed to parse manifest"));
    }

    #[test]
    fn test_load_lockfile_exists() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");
        let lockfile_path = temp_dir.path().join("agpm.lock");

        // Create test files
        std::fs::write(&manifest_path, "[sources]\n").unwrap();
        std::fs::write(
            &lockfile_path,
            r#"
version = 1

[[sources]]
name = "test"
url = "https://github.com/test/repo.git"
commit = "abc123"
fetched_at = "2024-01-01T00:00:00Z"
"#,
        )
        .unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();
        let lockfile = context.load_lockfile().unwrap();

        assert!(lockfile.is_some());
        let lockfile = lockfile.unwrap();
        assert_eq!(lockfile.sources.len(), 1);
        assert_eq!(lockfile.sources[0].name, "test");
    }

    #[test]
    fn test_load_lockfile_not_exists() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        std::fs::write(&manifest_path, "[sources]\n").unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();
        let lockfile = context.load_lockfile().unwrap();

        assert!(lockfile.is_none());
    }

    #[test]
    fn test_save_lockfile() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        std::fs::write(&manifest_path, "[sources]\n").unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();

        let lockfile = crate::lockfile::LockFile {
            version: 1,
            sources: vec![],
            agents: vec![],
            snippets: vec![],
            commands: vec![],
            scripts: vec![],
            hooks: vec![],
            mcp_servers: vec![],
            skills: vec![],
            manifest_hash: None,
            has_mutable_deps: None,
            resource_count: None,
        };

        context.save_lockfile(&lockfile).unwrap();

        assert!(context.lockfile_path.exists());
        let saved_content = std::fs::read_to_string(&context.lockfile_path).unwrap();
        assert!(saved_content.contains("version = 1"));
    }

    #[test]
    fn test_check_for_legacy_ccpm_no_files() {
        let temp_dir = TempDir::new().unwrap();
        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_none());
    }

    #[test]
    fn test_check_for_legacy_ccpm_toml_only() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.toml"), "[sources]\n").unwrap();

        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_some());
        let msg = result.unwrap();
        assert!(msg.contains("Legacy CCPM files detected"));
        assert!(msg.contains("ccpm.toml"));
        assert!(msg.contains("agpm migrate"));
    }

    #[test]
    fn test_check_for_legacy_ccpm_lock_only() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.lock"), "# lock\n").unwrap();

        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_some());
        let msg = result.unwrap();
        assert!(msg.contains("ccpm.lock"));
    }

    #[test]
    fn test_check_for_legacy_ccpm_both_files() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.toml"), "[sources]\n").unwrap();
        std::fs::write(temp_dir.path().join("ccpm.lock"), "# lock\n").unwrap();

        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_some());
        let msg = result.unwrap();
        assert!(msg.contains("ccpm.toml and ccpm.lock"));
    }

    #[test]
    fn test_find_legacy_ccpm_directory_no_files() {
        let temp_dir = TempDir::new().unwrap();
        let result = find_legacy_ccpm_directory(temp_dir.path());
        assert!(result.is_none());
    }

    #[test]
    fn test_find_legacy_ccpm_directory_in_current_dir() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.toml"), "[sources]\n").unwrap();

        let result = find_legacy_ccpm_directory(temp_dir.path());
        assert!(result.is_some());
        assert_eq!(result.unwrap(), temp_dir.path());
    }

    #[test]
    fn test_find_legacy_ccpm_directory_in_parent() {
        let temp_dir = TempDir::new().unwrap();
        let parent = temp_dir.path();
        let child = parent.join("subdir");
        std::fs::create_dir(&child).unwrap();

        // Create legacy file in parent
        std::fs::write(parent.join("ccpm.toml"), "[sources]\n").unwrap();

        // Search from child directory
        let result = find_legacy_ccpm_directory(&child);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), parent);
    }

    #[test]
    fn test_find_legacy_ccpm_directory_finds_lock_file() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.lock"), "# lock\n").unwrap();

        let result = find_legacy_ccpm_directory(temp_dir.path());
        assert!(result.is_some());
        assert_eq!(result.unwrap(), temp_dir.path());
    }

    #[tokio::test]
    async fn test_handle_legacy_ccpm_migration_no_files() -> Result<()> {
        let temp_dir = TempDir::new()?;

        // Test directory with no legacy files
        let result = handle_legacy_ccpm_migration(Some(temp_dir.path().to_path_buf()), false).await;

        assert!(result?.is_none());
        Ok(())
    }

    #[cfg(test)]
    mod lockfile_regeneration_tests {
        use super::*;
        use crate::manifest::Manifest;
        use tempfile::TempDir;

        #[test]
        fn test_load_lockfile_with_regeneration_valid_lockfile() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"

[agents]
test = { source = "example", path = "test.md", version = "v1.0.0" }
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create a valid lockfile
            let lockfile_content = r#"version = 1

[[sources]]
name = "example"
url = "https://github.com/example/repo.git"
commit = "abc123def456789012345678901234567890abcd"
fetched_at = "2024-01-01T00:00:00Z"

[[agents]]
name = "test"
source = "example"
path = "test.md"
version = "v1.0.0"
resolved_commit = "abc123def456789012345678901234567890abcd"
checksum = "sha256:examplechecksum"
installed_at = ".claude/agents/test.md"
"#;
            std::fs::write(&lockfile_path, lockfile_content).unwrap();

            // Test loading valid lockfile
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(true, "test").unwrap();
            assert!(result.is_some());
        }

        #[test]
        fn test_load_lockfile_with_regeneration_invalid_toml() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create an invalid TOML lockfile
            std::fs::write(&lockfile_path, "invalid toml [[[").unwrap();

            // Test loading invalid lockfile in non-interactive mode
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            // This should return an error in non-interactive mode
            let result = ctx.load_lockfile_with_regeneration(true, "test");
            assert!(result.is_err());

            let error_msg = result.unwrap_err().to_string();
            assert!(error_msg.contains("Invalid or corrupted lockfile detected"));
            assert!(error_msg.contains("beta software"));
            assert!(error_msg.contains("cp agpm.lock"));
        }

        #[test]
        fn test_load_lockfile_with_regeneration_missing_lockfile() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Test loading non-existent lockfile
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(true, "test").unwrap();
            assert!(result.is_none()); // Should return None for missing lockfile
        }

        #[test]
        fn test_load_lockfile_with_regeneration_version_incompatibility() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create a lockfile with future version
            let lockfile_content = r#"version = 999

[[sources]]
name = "example"
url = "https://github.com/example/repo.git"
commit = "abc123def456789012345678901234567890abcd"
fetched_at = "2024-01-01T00:00:00Z"
"#;
            std::fs::write(&lockfile_path, lockfile_content).unwrap();

            // Test loading future version lockfile
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(true, "test");
            assert!(result.is_err());

            let error_msg = result.unwrap_err().to_string();
            assert!(error_msg.contains("version") || error_msg.contains("newer"));
        }

        #[test]
        fn test_load_lockfile_with_regeneration_cannot_regenerate() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create an invalid TOML lockfile
            std::fs::write(&lockfile_path, "invalid toml [[[").unwrap();

            // Test with can_regenerate = false
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(false, "test");
            assert!(result.is_err());

            // Should return the original error, not the enhanced one
            let error_msg = result.unwrap_err().to_string();
            assert!(!error_msg.contains("Invalid or corrupted lockfile detected"));
            assert!(
                error_msg.contains("Failed to load lockfile")
                    || error_msg.contains("Invalid TOML syntax")
            );
        }

        #[test]
        fn test_backup_and_regenerate_lockfile() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create an invalid lockfile
            std::fs::write(&lockfile_path, "invalid content").unwrap();

            // Test backup and regeneration
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let backup_path = lockfile_path.with_extension("lock.invalid");

            // This should backup the file and remove the original
            ctx.backup_and_regenerate_lockfile(&backup_path, "test").unwrap();

            // Check that backup was created
            assert!(backup_path.exists());
            assert_eq!(std::fs::read_to_string(&backup_path).unwrap(), "invalid content");

            // Check that original was removed
            assert!(!lockfile_path.exists());
        }

        #[test]
        fn test_create_non_interactive_error() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Test non-interactive error creation
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let error = ctx.create_non_interactive_error("Invalid TOML syntax", "test");
            let error_msg = error.to_string();

            assert!(error_msg.contains("Invalid TOML syntax"));
            assert!(error_msg.contains("beta software"));
            assert!(error_msg.contains("cp agpm.lock"));
            assert!(error_msg.contains("rm agpm.lock"));
            assert!(error_msg.contains("agpm install"));
        }
    }

    /// Tests for CCPM and format migration functions.
    ///
    /// Note: These tests focus on non-interactive mode since mocking stdin
    /// with tokio::io::stdin() is complex. Interactive behavior is implicitly
    /// tested in CI environments which are non-TTY.
    mod migration_tests {
        use super::*;
        use tempfile::TempDir;

        #[tokio::test]
        async fn test_handle_legacy_ccpm_migration_with_files_non_interactive() {
            // Tests run in non-TTY mode, so this tests the non-interactive path
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();

            // Create legacy CCPM files
            std::fs::write(
                project_dir.join("ccpm.toml"),
                "[sources]\ntest = \"https://test.git\"\n",
            )
            .unwrap();
            std::fs::write(project_dir.join("ccpm.lock"), "version = 1\n").unwrap();

            // In non-interactive mode (yes=false), should return None without migrating
            let result = handle_legacy_ccpm_migration(Some(project_dir.to_path_buf()), false).await;
            assert!(result.is_ok());
            assert!(result.unwrap().is_none());

            // Files should NOT be migrated (non-interactive mode)
            assert!(project_dir.join("ccpm.toml").exists());
            assert!(!project_dir.join("agpm.toml").exists());
        }

        #[tokio::test]
        async fn test_handle_legacy_format_migration_no_migration_needed() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();

            // Create project with new format (files in agpm/ subdirectory)
            let agents_dir = project_dir.join(".claude/agents/agpm");
            std::fs::create_dir_all(&agents_dir).unwrap();
            std::fs::write(agents_dir.join("test.md"), "# Test Agent").unwrap();

            // Create a lockfile with new paths
            let lockfile = r#"version = 1

[[agents]]
name = "test"
source = "test"
path = "agents/test.md"
version = "v1.0.0"
resolved_commit = "abc123"
checksum = "sha256:abc"
context_checksum = "sha256:def"
installed_at = ".claude/agents/agpm/test.md"
dependencies = []
resource_type = "Agent"
tool = "claude-code"
"#;
            std::fs::write(project_dir.join("agpm.lock"), lockfile).unwrap();

            // No migration needed
            let result = handle_legacy_format_migration(project_dir, false).await;
            assert!(result.is_ok());
            assert!(!result.unwrap()); // false = no migration performed
        }

        #[tokio::test]
        async fn test_handle_legacy_format_migration_with_old_paths_non_interactive() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();

            // Create resources at OLD paths (not in agpm/ subdirectory)
            let agents_dir = project_dir.join(".claude/agents");
            std::fs::create_dir_all(&agents_dir).unwrap();
            std::fs::write(agents_dir.join("test.md"), "# Test Agent").unwrap();

            // Create a lockfile pointing to old paths
            let lockfile = r#"version = 1

[[agents]]
name = "test"
source = "test"
path = "agents/test.md"
version = "v1.0.0"
resolved_commit = "abc123"
checksum = "sha256:abc"
context_checksum = "sha256:def"
installed_at = ".claude/agents/test.md"
dependencies = []
resource_type = "Agent"
tool = "claude-code"
"#;
            std::fs::write(project_dir.join("agpm.lock"), lockfile).unwrap();

            // In non-interactive mode (yes=false), should return false without migrating
            let result = handle_legacy_format_migration(project_dir, false).await;
            assert!(result.is_ok());
            assert!(!result.unwrap()); // false = no migration performed

            // Files should NOT be migrated (non-interactive mode)
            assert!(agents_dir.join("test.md").exists());
            assert!(!agents_dir.join("agpm/test.md").exists());
        }

        #[tokio::test]
        async fn test_handle_legacy_format_migration_with_gitignore_section_non_interactive() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();

            // Create .gitignore with managed section
            let gitignore = r#"# User entries
node_modules/

# AGPM managed entries - do not edit below this line
.claude/agents/test.md
# End of AGPM managed entries
"#;
            std::fs::write(project_dir.join(".gitignore"), gitignore).unwrap();

            // Create an empty lockfile (gitignore section alone triggers migration)
            std::fs::write(project_dir.join("agpm.lock"), "version = 1\n").unwrap();

            // In non-interactive mode (yes=false), should return false without migrating
            let result = handle_legacy_format_migration(project_dir, false).await;
            assert!(result.is_ok());
            assert!(!result.unwrap()); // false = no migration performed

            // .gitignore should NOT be modified (non-interactive mode)
            let content = std::fs::read_to_string(project_dir.join(".gitignore")).unwrap();
            assert!(content.contains("# AGPM managed entries"));
        }

        #[tokio::test]
        async fn test_handle_legacy_format_migration_no_lockfile() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();

            // Create resources at old paths but NO lockfile
            let agents_dir = project_dir.join(".claude/agents");
            std::fs::create_dir_all(&agents_dir).unwrap();
            std::fs::write(agents_dir.join("test.md"), "# Test Agent").unwrap();

            // Without lockfile, can't detect AGPM-managed files
            // so no migration should be detected
            let result = handle_legacy_format_migration(project_dir, false).await;
            assert!(result.is_ok());
            assert!(!result.unwrap()); // false = no migration needed
        }
    }

    /// Tests for gitignore entry offering functionality.
    mod gitignore_offering_tests {
        use super::*;
        use crate::installer::ConfigValidation;
        use tempfile::TempDir;

        #[tokio::test]
        async fn test_handle_missing_gitignore_no_entries() {
            let temp_dir = TempDir::new().unwrap();
            let validation = ConfigValidation::default(); // Empty missing entries

            let result =
                handle_missing_gitignore_entries(&validation, temp_dir.path(), false).await;

            assert!(result.is_ok());
            assert!(!result.unwrap()); // No entries added
        }

        #[tokio::test]
        async fn test_handle_missing_gitignore_with_yes_flag() {
            let temp_dir = TempDir::new().unwrap();
            let validation = ConfigValidation {
                missing_gitignore_entries: vec![
                    ".claude/agents/agpm/".to_string(),
                    "agpm.private.toml".to_string(),
                ],
                ..Default::default()
            };

            // With --yes flag, should add entries without prompting
            let result = handle_missing_gitignore_entries(
                &validation,
                temp_dir.path(),
                true, // yes=true
            )
            .await;

            assert!(result.is_ok());
            assert!(result.unwrap()); // Entries added

            // Verify .gitignore was created with correct content
            let content = std::fs::read_to_string(temp_dir.path().join(".gitignore")).unwrap();
            assert!(content.contains("# AGPM managed paths"));
            assert!(content.contains(".claude/*/agpm/"));
            assert!(content.contains(".opencode/*/agpm/"));
            assert!(content.contains(".agpm/"));
            assert!(content.contains("agpm.private.toml"));
            assert!(content.contains("agpm.private.lock"));
            assert!(content.contains("# End of AGPM managed paths"));
        }

        #[tokio::test]
        async fn test_handle_missing_gitignore_appends_to_existing() {
            let temp_dir = TempDir::new().unwrap();

            // Create existing .gitignore
            std::fs::write(temp_dir.path().join(".gitignore"), "node_modules/\n.env\n").unwrap();

            let validation = ConfigValidation {
                missing_gitignore_entries: vec![".claude/agents/agpm/".to_string()],
                ..Default::default()
            };

            let result = handle_missing_gitignore_entries(&validation, temp_dir.path(), true).await;

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

            let content = std::fs::read_to_string(temp_dir.path().join(".gitignore")).unwrap();
            // Original content preserved
            assert!(content.contains("node_modules/"));
            assert!(content.contains(".env"));
            // New content added
            assert!(content.contains("# AGPM managed paths"));
            assert!(content.contains(".claude/*/agpm/"));
        }

        #[tokio::test]
        async fn test_handle_missing_gitignore_non_interactive_no_yes() {
            // In test environment, stdin is not a TTY, so this tests non-interactive mode
            let temp_dir = TempDir::new().unwrap();
            let validation = ConfigValidation {
                missing_gitignore_entries: vec![".claude/agents/agpm/".to_string()],
                ..Default::default()
            };

            let result = handle_missing_gitignore_entries(
                &validation,
                temp_dir.path(),
                false, // yes=false, non-TTY
            )
            .await;

            assert!(result.is_ok());
            assert!(!result.unwrap()); // No entries added in non-interactive

            // .gitignore should not be created
            assert!(!temp_dir.path().join(".gitignore").exists());
        }

        #[tokio::test]
        async fn test_handle_missing_gitignore_skips_if_section_exists() {
            let temp_dir = TempDir::new().unwrap();

            // Create .gitignore with existing managed section
            let existing = r#"node_modules/

# AGPM managed paths
.claude/*/agpm/
# End of AGPM managed paths
"#;
            std::fs::write(temp_dir.path().join(".gitignore"), existing).unwrap();

            // Even with missing entries, if section exists, don't add again
            let validation = ConfigValidation {
                missing_gitignore_entries: vec!["agpm.private.toml".to_string()],
                ..Default::default()
            };

            let result = handle_missing_gitignore_entries(&validation, temp_dir.path(), true).await;

            assert!(result.is_ok());
            assert!(!result.unwrap()); // Not added (section exists)

            // Content should be unchanged
            let content = std::fs::read_to_string(temp_dir.path().join(".gitignore")).unwrap();
            assert_eq!(content, existing);
        }

        #[tokio::test]
        async fn test_handle_missing_gitignore_creates_new_file() {
            let temp_dir = TempDir::new().unwrap();

            // No .gitignore exists
            assert!(!temp_dir.path().join(".gitignore").exists());

            let validation = ConfigValidation {
                missing_gitignore_entries: vec![".claude/agents/agpm/".to_string()],
                ..Default::default()
            };

            let result = handle_missing_gitignore_entries(&validation, temp_dir.path(), true).await;

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

            // .gitignore should be created
            assert!(temp_dir.path().join(".gitignore").exists());
            let content = std::fs::read_to_string(temp_dir.path().join(".gitignore")).unwrap();
            assert!(content.contains("# AGPM managed paths"));
        }

        #[tokio::test]
        async fn test_handle_missing_gitignore_handles_file_without_newline() {
            let temp_dir = TempDir::new().unwrap();

            // Create .gitignore without trailing newline
            std::fs::write(temp_dir.path().join(".gitignore"), "node_modules/").unwrap();

            let validation = ConfigValidation {
                missing_gitignore_entries: vec![".claude/agents/agpm/".to_string()],
                ..Default::default()
            };

            let result = handle_missing_gitignore_entries(&validation, temp_dir.path(), true).await;

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

            let content = std::fs::read_to_string(temp_dir.path().join(".gitignore")).unwrap();
            // Should have proper separation (newline added before section)
            assert!(content.contains("node_modules/\n\n# AGPM managed paths"));
        }
    }
}