sublime_pkg_tools 0.0.27

Package and version management toolkit for Node.js projects with changeset support
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
//! Changelog generator for creating and managing changelogs.
//!
//! **What**: Provides the core `ChangelogGenerator` structure that orchestrates changelog
//! generation for both single-package and monorepo projects.
//!
//! **How**: This module integrates Git repository access, filesystem operations, and
//! configuration to generate changelogs from commit history. It supports multiple formats
//! (Keep a Changelog, Conventional Commits, custom templates) and handles version detection
//! from Git tags.
//!
//! **Why**: To provide a unified interface for changelog generation that works consistently
//! across different project structures and changelog formats, automating the creation of
//! human-readable release documentation.
//!
//! # Examples
//!
//! ```rust,ignore
//! use sublime_pkg_tools::changelog::ChangelogGenerator;
//! use sublime_pkg_tools::config::PackageToolsConfig;
//! use sublime_git_tools::Repo;
//! use sublime_standard_tools::filesystem::FileSystemManager;
//! use std::path::PathBuf;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let workspace_root = PathBuf::from(".");
//! let git_repo = Repo::open(".")?;
//! let fs = FileSystemManager::new();
//! let config = PackageToolsConfig::default();
//!
//! let generator = ChangelogGenerator::new(
//!     workspace_root,
//!     git_repo,
//!     fs,
//!     config.changelog
//! ).await?;
//!
//! // Generate changelog for a specific version
//! let changelog = generator.generate_for_version(Some("my-package"), "2.0.0", Some("1.0.0"), None).await?;
//! println!("{}", changelog.to_markdown(&config.changelog));
//! # Ok(())
//! # }
//! ```

use crate::changelog::version_detection::{VersionTag, find_previous_version, parse_version_tag};
use crate::changelog::{Changelog, ChangelogCollector, ChangelogMetadata};
use crate::config::ChangelogConfig;
use crate::error::{ChangelogError, ChangelogResult};
use crate::types::VersionBump;
use chrono::Utc;
use std::path::{Path, PathBuf};
use sublime_git_tools::Repo;
use sublime_standard_tools::filesystem::{AsyncFileSystem, FileSystemManager};

/// Main changelog generator for creating and managing changelogs.
///
/// The `ChangelogGenerator` is the primary entry point for all changelog operations.
/// It provides methods to generate changelogs from version history, update existing
/// changelog files, and parse commit messages using conventional commit format.
///
/// # Architecture
///
/// The generator integrates several components:
/// - **Git Repository**: Access to commit history, tags, and version detection
/// - **File System**: Reading and writing changelog files
/// - **Configuration**: Changelog format, templates, and generation options
///
/// # Supported Formats
///
/// - **Keep a Changelog**: Standard format following <https://keepachangelog.com>
/// - **Conventional Commits**: Automatic grouping by commit type (feat, fix, etc.)
/// - **Custom Templates**: User-defined formats with variable substitution
///
/// # Monorepo Support
///
/// The generator supports three monorepo modes:
/// - **Per-Package**: Each package has its own CHANGELOG.md in its directory
/// - **Root**: Single CHANGELOG.md at the repository root
/// - **Both**: Maintain both per-package and root changelogs
///
/// # Examples
///
/// ## Creating a generator
///
/// ```rust,ignore
/// use sublime_pkg_tools::changelog::ChangelogGenerator;
/// use sublime_pkg_tools::config::PackageToolsConfig;
/// use sublime_git_tools::Repo;
/// use sublime_standard_tools::filesystem::FileSystemManager;
/// use std::path::PathBuf;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let workspace_root = PathBuf::from("/path/to/workspace");
/// let git_repo = Repo::open("/path/to/workspace")?;
/// let fs = FileSystemManager::new();
/// let config = PackageToolsConfig::default();
///
/// let generator = ChangelogGenerator::new(
///     workspace_root,
///     git_repo,
///     fs,
///     config.changelog,
/// ).await?;
///
/// println!("Generator ready for workspace: {}", generator.workspace_root().display());
/// # Ok(())
/// # }
/// ```
///
/// ## Accessing configuration
///
/// ```rust,ignore
/// # use sublime_pkg_tools::changelog::ChangelogGenerator;
/// # use sublime_pkg_tools::config::{PackageToolsConfig, ChangelogFormat};
/// # use sublime_git_tools::Repo;
/// # use sublime_standard_tools::filesystem::FileSystemManager;
/// # use std::path::PathBuf;
/// #
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let workspace_root = PathBuf::from(".");
/// # let git_repo = Repo::open(".")?;
/// # let fs = FileSystemManager::new();
/// # let config = PackageToolsConfig::default();
/// #
/// let generator = ChangelogGenerator::new(
///     workspace_root,
///     git_repo,
///     fs,
///     config.changelog,
/// ).await?;
///
/// let format = generator.config().format;
/// println!("Using changelog format: {:?}", format);
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ChangelogGenerator {
    /// Root path of the workspace or repository.
    ///
    /// This is used as the base path for resolving package locations and
    /// changelog file paths.
    workspace_root: PathBuf,

    /// Git repository for accessing commit history and tags.
    ///
    /// The repository provides access to commits, tags, and version detection
    /// needed for changelog generation.
    git_repo: Repo,

    /// File system manager for reading and writing changelog files.
    ///
    /// The file system abstraction enables testing with mock implementations
    /// and provides async file operations.
    fs: FileSystemManager,

    /// Changelog generation configuration.
    ///
    /// Controls the format, templates, exclusion rules, and other aspects
    /// of changelog generation.
    config: ChangelogConfig,
}

impl ChangelogGenerator {
    /// Creates a new `ChangelogGenerator` instance.
    ///
    /// This constructor initializes the generator with the provided workspace root,
    /// Git repository, file system manager, and configuration. It validates that
    /// the workspace root exists and is a valid directory.
    ///
    /// # Arguments
    ///
    /// * `workspace_root` - The root path of the workspace or repository
    /// * `git_repo` - Git repository instance for accessing commit history
    /// * `fs` - File system manager for file operations
    /// * `config` - Changelog generation configuration
    ///
    /// # Returns
    ///
    /// Returns a `ChangelogResult<Self>` containing the new generator instance,
    /// or an error if initialization fails.
    ///
    /// # Errors
    ///
    /// This method returns an error if:
    /// - The workspace root path is invalid or doesn't exist
    /// - The workspace root is not a directory
    /// - The configuration is invalid
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use sublime_git_tools::Repo;
    /// use sublime_standard_tools::filesystem::FileSystemManager;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let git_repo = Repo::open(".")?;
    /// let fs = FileSystemManager::new();
    /// let config = PackageToolsConfig::default();
    ///
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// assert!(generator.workspace_root().exists());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new(
        workspace_root: PathBuf,
        git_repo: Repo,
        fs: FileSystemManager,
        config: ChangelogConfig,
    ) -> ChangelogResult<Self> {
        // Validate workspace root exists and is a directory
        if !fs.exists(&workspace_root).await {
            return Err(ChangelogError::InvalidPath {
                path: workspace_root.clone(),
                reason: "Workspace root does not exist".to_string(),
            });
        }

        // Check if path is a directory by attempting to read it
        // If read_dir fails, it's likely not a directory
        if fs.read_dir(&workspace_root).await.is_err() {
            return Err(ChangelogError::InvalidPath {
                path: workspace_root.clone(),
                reason: "Workspace root is not a directory".to_string(),
            });
        }

        Ok(Self { workspace_root, git_repo, fs, config })
    }

    /// Returns a reference to the workspace root path.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// println!("Workspace: {}", generator.workspace_root().display());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn workspace_root(&self) -> &PathBuf {
        &self.workspace_root
    }

    /// Returns a reference to the Git repository.
    ///
    /// This provides access to the underlying Git repository for operations
    /// that need direct access to commits, tags, or other Git functionality.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// let current_sha = generator.git_repo().get_current_sha()?;
    /// println!("Current commit: {}", current_sha);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn git_repo(&self) -> &Repo {
        &self.git_repo
    }

    /// Returns a reference to the file system manager.
    ///
    /// This provides access to the filesystem operations for reading and
    /// writing files during changelog generation.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// let fs = generator.fs();
    /// let exists = fs.exists(&PathBuf::from("CHANGELOG.md")).await;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn fs(&self) -> &FileSystemManager {
        &self.fs
    }

    /// Returns a reference to the changelog configuration.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// let config = generator.config();
    /// println!("Changelog format: {:?}", config.format);
    /// println!("Include links: {}", config.include_commit_links);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn config(&self) -> &ChangelogConfig {
        &self.config
    }

    /// Checks if changelog generation is enabled in the configuration.
    ///
    /// This is a convenience method to check the `enabled` flag in the
    /// configuration without directly accessing the config field.
    ///
    /// # Returns
    ///
    /// Returns `true` if changelog generation is enabled, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// if generator.is_enabled() {
    ///     println!("Changelog generation is enabled");
    /// } else {
    ///     println!("Changelog generation is disabled");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Gets the repository URL from configuration or Git remote.
    ///
    /// This method returns the repository URL needed for generating links to
    /// commits and issues. It first checks the configuration for an explicit
    /// repository URL, and if not found, attempts to detect it from the Git
    /// remote configuration.
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(url))` if a repository URL is found, `Ok(None)` if no
    /// URL is configured, or an error if Git operations fail.
    ///
    /// # Errors
    ///
    /// This method returns an error if:
    /// - Git remote operations fail
    /// - The remote URL is in an invalid format
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// if let Some(url) = generator.get_repository_url()? {
    ///     println!("Repository URL: {}", url);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_repository_url(&self) -> ChangelogResult<Option<String>> {
        // Return configured URL if available
        if let Some(ref url) = self.config.repository_url {
            return Ok(Some(url.clone()));
        }

        // TODO: will be implemented in future story
        // Attempt to detect from git remote
        // This would call git_repo methods to get remote URLs
        Ok(None)
    }

    /// Detects the previous version tag for a package from Git tags.
    ///
    /// This method searches through Git tags to find the most recent version
    /// that is less than the current version. It supports both monorepo
    /// (per-package tags) and single-package (root tags) scenarios based on
    /// the configuration.
    ///
    /// # Arguments
    ///
    /// * `package_name` - Optional package name for monorepo scenarios
    /// * `current_version` - The current version to find the previous version for
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(VersionTag))` if a previous version is found,
    /// `Ok(None)` if this is the first version (no previous tags),
    /// or an error if Git operations fail or the version is invalid.
    ///
    /// # Errors
    ///
    /// This method returns an error if:
    /// - Git tag retrieval fails
    /// - The current version string is invalid
    /// - Git repository operations fail
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// // Detect previous version for a package
    /// let previous = generator.detect_previous_version(Some("mypackage"), "2.0.0").await?;
    /// if let Some(tag) = previous {
    ///     println!("Previous version: {}", tag.version());
    ///     println!("Previous tag: {}", tag.tag_name());
    /// } else {
    ///     println!("This is the first release");
    /// }
    ///
    /// // Detect previous version for root package
    /// let previous = generator.detect_previous_version(None, "1.5.0").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn detect_previous_version(
        &self,
        package_name: Option<&str>,
        current_version: &str,
    ) -> ChangelogResult<Option<VersionTag>> {
        // Get all tags from Git repository
        let git_tags = self.git_repo.get_remote_or_local_tags(Some(true)).map_err(|e| {
            ChangelogError::GitError {
                operation: "get tags".to_string(),
                reason: e.as_ref().to_string(),
            }
        })?;

        // Extract tag names
        let tag_names: Vec<String> = git_tags.iter().map(|t| t.tag.clone()).collect();

        // Determine which format to use based on package_name
        let format = if package_name.is_some() {
            &self.config.version_tag_format
        } else {
            &self.config.root_tag_format
        };

        // Find previous version
        find_previous_version(&tag_names, current_version, package_name, format)
    }

    /// Parses a Git tag string into a version tag structure.
    ///
    /// This method attempts to parse a tag according to the configured format
    /// (either monorepo or root format). It's useful for validating or extracting
    /// version information from tag strings.
    ///
    /// # Arguments
    ///
    /// * `tag` - The Git tag string to parse
    /// * `package_name` - Optional package name for monorepo tags
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(VersionTag))` if the tag matches the expected format,
    /// `Ok(None)` if the tag doesn't match the format,
    /// or an error if the operation fails.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// // Parse monorepo tag
    /// let tag = generator.parse_version_tag("mypackage@1.0.0", Some("mypackage"))?;
    /// if let Some(version_tag) = tag {
    ///     println!("Version: {}", version_tag.version());
    /// }
    ///
    /// // Parse root tag
    /// let tag = generator.parse_version_tag("v1.0.0", None)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse_version_tag(
        &self,
        tag: &str,
        package_name: Option<&str>,
    ) -> ChangelogResult<Option<VersionTag>> {
        // Determine which format to use
        let format = if package_name.is_some() {
            &self.config.version_tag_format
        } else {
            &self.config.root_tag_format
        };

        Ok(parse_version_tag(tag, package_name, format))
    }

    /// Gets all version tags from the Git repository.
    ///
    /// This method retrieves all tags from Git and filters them to only
    /// include valid version tags according to the configured format.
    /// Optionally filters by package name for monorepo scenarios.
    ///
    /// # Arguments
    ///
    /// * `package_name` - Optional package name to filter monorepo tags
    ///
    /// # Returns
    ///
    /// Returns a vector of `VersionTag` instances, sorted by version (newest first).
    ///
    /// # Errors
    ///
    /// This method returns an error if Git operations fail.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// // Get all version tags for a package
    /// let tags = generator.get_version_tags(Some("mypackage")).await?;
    /// for tag in tags {
    ///     println!("Tag: {} -> Version: {}", tag.tag_name(), tag.version());
    /// }
    ///
    /// // Get all root version tags
    /// let tags = generator.get_version_tags(None).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_version_tags(
        &self,
        package_name: Option<&str>,
    ) -> ChangelogResult<Vec<VersionTag>> {
        // Get all tags from Git repository
        let git_tags = self.git_repo.get_remote_or_local_tags(Some(true)).map_err(|e| {
            ChangelogError::GitError {
                operation: "get tags".to_string(),
                reason: e.as_ref().to_string(),
            }
        })?;

        // Extract tag names
        let tag_names: Vec<String> = git_tags.iter().map(|t| t.tag.clone()).collect();

        // Determine which format to use
        let format = if package_name.is_some() {
            &self.config.version_tag_format
        } else {
            &self.config.root_tag_format
        };

        // Parse and filter tags
        let mut version_tags: Vec<VersionTag> = tag_names
            .iter()
            .filter_map(|tag| parse_version_tag(tag, package_name, format))
            .collect();

        // Sort by version (newest first)
        version_tags.sort_by(|a, b| b.cmp(a));

        Ok(version_tags)
    }

    /// Generates a changelog for a specific version.
    ///
    /// This method collects commits between the previous version and the current version,
    /// parses them into changelog entries, groups them by section type, and creates
    /// a complete `Changelog` structure.
    ///
    /// # Arguments
    ///
    /// * `package_name` - Optional package name for monorepo scenarios
    /// * `version` - The version to generate the changelog for
    /// * `previous_version` - Optional previous version (auto-detected if None)
    /// * `relative_path` - Optional path filter for monorepo packages
    ///
    /// # Returns
    ///
    /// A `Changelog` instance containing all changes for the specified version.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Git operations fail
    /// - Version detection fails
    /// - Commit retrieval fails
    /// - No commits are found between versions
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use sublime_git_tools::Repo;
    /// use sublime_standard_tools::filesystem::FileSystemManager;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let git_repo = Repo::open(".")?;
    /// let fs = FileSystemManager::new();
    /// let config = PackageToolsConfig::default();
    ///
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// // Generate for specific package with auto-detected previous version
    /// let changelog = generator.generate_for_version(
    ///     Some("my-package"),
    ///     "2.0.0",
    ///     None,
    ///     Some("packages/my-package")
    /// ).await?;
    ///
    /// // Generate for root with explicit previous version
    /// let changelog = generator.generate_for_version(
    ///     None,
    ///     "1.5.0",
    ///     Some("1.4.0"),
    ///     None
    /// ).await?;
    ///
    /// println!("Generated changelog with {} entries", changelog.entry_count());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn generate_for_version(
        &self,
        package_name: Option<&str>,
        version: &str,
        previous_version: Option<&str>,
        relative_path: Option<&str>,
    ) -> ChangelogResult<Changelog> {
        // Determine previous version if not provided
        let prev_version = if let Some(prev) = previous_version {
            Some(prev.to_string())
        } else {
            self.detect_previous_version(package_name, version)
                .await?
                .map(|tag| tag.version().to_string())
        };

        // Determine Git references
        let (from_ref, to_ref) =
            self.build_git_refs(package_name, prev_version.as_deref(), version)?;

        // Collect commits using the collector
        let collector = ChangelogCollector::new(&self.git_repo, &self.config);
        let sections =
            collector.collect_between_versions(&from_ref, &to_ref, relative_path).await?;

        // Build changelog metadata
        let metadata = self.build_metadata(
            package_name,
            version,
            prev_version.as_deref(),
            &from_ref,
            &to_ref,
            &sections,
        )?;

        // Create changelog
        let mut changelog =
            Changelog::new(package_name, version, prev_version.as_deref(), Utc::now());

        // Add sections
        for section in sections {
            changelog.add_section(section);
        }

        changelog.metadata = metadata;

        Ok(changelog)
    }

    /// Checks if a Git reference (tag, branch, or commit) exists in the repository.
    ///
    /// This method attempts to resolve a Git reference using `revparse_single`.
    /// If the reference can be resolved, it exists; otherwise, it does not.
    ///
    /// # Arguments
    ///
    /// * `git_ref` - The Git reference to check (tag name, branch name, or commit SHA)
    ///
    /// # Returns
    ///
    /// Returns `true` if the reference exists and can be resolved, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// # use sublime_pkg_tools::config::PackageToolsConfig;
    /// # use sublime_git_tools::Repo;
    /// # use sublime_standard_tools::filesystem::FileSystemManager;
    /// # use std::path::PathBuf;
    /// #
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let workspace_root = PathBuf::from(".");
    /// # let git_repo = Repo::open(".")?;
    /// # let fs = FileSystemManager::new();
    /// # let config = PackageToolsConfig::default();
    /// #
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// // Check if a tag exists
    /// if generator.reference_exists("v1.0.0") {
    ///     println!("Tag v1.0.0 exists");
    /// }
    ///
    /// // HEAD always exists
    /// assert!(generator.reference_exists("HEAD"));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    fn reference_exists(&self, git_ref: &str) -> bool {
        // Use the git_repo's internal repo to check if reference exists
        // This is a simple check - if revparse_single succeeds, the reference exists
        self.git_repo.get_diverged_commit(git_ref).is_ok()
    }

    /// Builds Git references for changelog generation.
    ///
    /// Creates the from and to references based on the configured tag format.
    /// When the target version tag does not exist yet (common during changelog
    /// generation before tags are created), this method automatically falls back
    /// to using `HEAD` as the `to_ref`.
    ///
    /// # Arguments
    ///
    /// * `package_name` - Optional package name for scoped packages
    /// * `previous_version` - Optional previous version string
    /// * `current_version` - Current version string
    ///
    /// # Returns
    ///
    /// A tuple of (from_ref, to_ref) strings representing Git references.
    ///
    /// # Errors
    ///
    /// Returns an error if no previous version is available.
    fn build_git_refs(
        &self,
        package_name: Option<&str>,
        previous_version: Option<&str>,
        current_version: &str,
    ) -> ChangelogResult<(String, String)> {
        let format = if package_name.is_some() {
            &self.config.version_tag_format
        } else {
            &self.config.root_tag_format
        };

        // Build to_ref (current version tag)
        let to_ref_tag = if let Some(pkg_name) = package_name {
            format.replace("{name}", pkg_name).replace("{version}", current_version)
        } else {
            format.replace("{version}", current_version)
        };

        // Check if the to_ref tag exists; if not, use HEAD
        // This handles the case where changelog is generated before tags are created
        let to_ref =
            if self.reference_exists(&to_ref_tag) { to_ref_tag } else { "HEAD".to_string() };

        // Build from_ref (previous version tag or HEAD)
        let from_ref = if let Some(prev_version) = previous_version {
            if let Some(pkg_name) = package_name {
                format.replace("{name}", pkg_name).replace("{version}", prev_version)
            } else {
                format.replace("{version}", prev_version)
            }
        } else {
            // No previous version - use first commit
            return Err(ChangelogError::VersionNotFound {
                reason: "No previous version found for changelog generation".to_string(),
            });
        };

        Ok((from_ref, to_ref))
    }

    /// Builds changelog metadata from collected data.
    ///
    /// # Arguments
    ///
    /// * `package_name` - Optional package name
    /// * `version` - Current version
    /// * `previous_version` - Optional previous version
    /// * `from_ref` - Starting Git reference
    /// * `to_ref` - Ending Git reference
    /// * `sections` - Collected changelog sections
    ///
    /// # Returns
    ///
    /// A `ChangelogMetadata` instance.
    fn build_metadata(
        &self,
        _package_name: Option<&str>,
        _version: &str,
        previous_version: Option<&str>,
        from_ref: &str,
        to_ref: &str,
        sections: &[crate::changelog::ChangelogSection],
    ) -> ChangelogResult<ChangelogMetadata> {
        // Calculate total commits
        let total_commits: usize = sections.iter().map(|s| s.entries.len()).sum();

        // Build commit range
        let commit_range = if previous_version.is_some() {
            Some(format!("{}..{}", from_ref, to_ref))
        } else {
            None
        };

        // Determine bump type based on sections
        let bump_type = self.infer_bump_type(sections);

        // Get repository URL
        let repository_url = self.get_repository_url()?;

        Ok(ChangelogMetadata {
            tag: Some(to_ref.to_string()),
            commit_range,
            total_commits,
            repository_url,
            bump_type: Some(bump_type),
        })
    }

    /// Infers the version bump type from changelog sections.
    ///
    /// # Arguments
    ///
    /// * `sections` - Changelog sections
    ///
    /// # Returns
    ///
    /// The inferred `VersionBump`.
    fn infer_bump_type(&self, sections: &[crate::changelog::ChangelogSection]) -> VersionBump {
        use crate::changelog::SectionType;

        // Breaking changes = major bump
        for section in sections {
            if section.section_type == SectionType::Breaking && !section.is_empty() {
                return VersionBump::Major;
            }
        }

        // Features = minor bump
        for section in sections {
            if section.section_type == SectionType::Features && !section.is_empty() {
                return VersionBump::Minor;
            }
        }

        // Any other changes = patch bump
        if sections.iter().any(|s| !s.is_empty()) {
            return VersionBump::Patch;
        }

        // No changes
        VersionBump::None
    }

    /// Updates or creates a CHANGELOG.md file with new changelog content.
    ///
    /// This method either creates a new changelog file with a header or updates an existing
    /// one by prepending the new version section. The operation can be performed in dry-run
    /// mode, which returns the content without writing to the file system.
    ///
    /// # Arguments
    ///
    /// * `package_path` - The path to the package directory
    /// * `changelog` - The changelog data to add
    /// * `dry_run` - If `true`, returns content without writing to disk
    ///
    /// # Returns
    ///
    /// Returns the final changelog content (whether written or not).
    ///
    /// # Errors
    ///
    /// This method returns an error if:
    /// - File system operations fail
    /// - The existing changelog cannot be parsed
    /// - The path is invalid
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::{Changelog, ChangelogGenerator};
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use sublime_git_tools::Repo;
    /// use sublime_standard_tools::filesystem::FileSystemManager;
    /// use std::path::PathBuf;
    /// use chrono::Utc;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let git_repo = Repo::open(".")?;
    /// let fs = FileSystemManager::new();
    /// let config = PackageToolsConfig::default();
    ///
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// let changelog = Changelog::new(Some("my-package"), "1.0.0", None, Utc::now());
    /// let package_path = PathBuf::from("packages/my-package");
    ///
    /// // Dry run - preview without writing
    /// let content = generator.update_changelog(&package_path, &changelog, true).await?;
    /// println!("Would write:\n{}", content);
    ///
    /// // Actually write the changelog
    /// generator.update_changelog(&package_path, &changelog, false).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn update_changelog(
        &self,
        package_path: &Path,
        changelog: &Changelog,
        dry_run: bool,
    ) -> ChangelogResult<String> {
        let changelog_path = package_path.join(&self.config.filename);

        // Render new content
        let new_section = changelog.to_markdown(&self.config);

        // Read existing changelog (if exists)
        let existing_content = if self.fs.exists(&changelog_path).await {
            self.fs.read_file_string(&changelog_path).await.map_err(|e| {
                ChangelogError::FileSystemError {
                    path: changelog_path.clone(),
                    reason: e.as_ref().to_string(),
                }
            })?
        } else {
            // Create header for new changelog
            let mut header = self.config.template.header.clone();
            if !header.is_empty() && !header.ends_with('\n') {
                header.push('\n');
            }
            header.push('\n');
            header
        };

        // Prepend new section
        let updated_content = self.prepend_changelog(&existing_content, &new_section);

        // Write if not dry-run
        if !dry_run {
            // Ensure parent directory exists
            if let Some(parent) = changelog_path.parent() {
                self.fs.create_dir_all(parent).await.map_err(|e| {
                    ChangelogError::FileSystemError {
                        path: parent.to_path_buf(),
                        reason: e.as_ref().to_string(),
                    }
                })?;
            }

            self.fs.write_file_string(&changelog_path, &updated_content).await.map_err(|e| {
                ChangelogError::UpdateFailed {
                    path: changelog_path.clone(),
                    reason: e.as_ref().to_string(),
                }
            })?;
        }

        Ok(updated_content)
    }

    /// Parses an existing CHANGELOG.md file.
    ///
    /// This method reads and parses an existing changelog file, extracting version
    /// information and content. It's useful for querying existing changelogs or
    /// checking if a version already exists before updating.
    ///
    /// # Arguments
    ///
    /// * `package_path` - The path to the package directory
    ///
    /// # Returns
    ///
    /// Returns a `ParsedChangelog` containing the structured changelog data.
    ///
    /// # Errors
    ///
    /// This method returns an error if:
    /// - The changelog file doesn't exist
    /// - The file cannot be read
    /// - The changelog format is invalid
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use sublime_git_tools::Repo;
    /// use sublime_standard_tools::filesystem::FileSystemManager;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let git_repo = Repo::open(".")?;
    /// let fs = FileSystemManager::new();
    /// let config = PackageToolsConfig::default();
    ///
    /// let generator = ChangelogGenerator::new(
    ///     workspace_root,
    ///     git_repo,
    ///     fs,
    ///     config.changelog,
    /// ).await?;
    ///
    /// let package_path = PathBuf::from("packages/my-package");
    /// let parsed = generator.parse_changelog(&package_path).await?;
    ///
    /// println!("Found {} versions", parsed.versions.len());
    /// if let Some(latest) = parsed.latest_version() {
    ///     println!("Latest version: {}", latest.version);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn parse_changelog(
        &self,
        package_path: &Path,
    ) -> ChangelogResult<crate::changelog::parser::ParsedChangelog> {
        use crate::changelog::parser::ChangelogParser;

        let changelog_path = package_path.join(&self.config.filename);

        // Check if file exists
        if !self.fs.exists(&changelog_path).await {
            return Err(ChangelogError::NotFound { path: changelog_path });
        }

        // Read the file
        let content = self.fs.read_file_string(&changelog_path).await.map_err(|e| {
            ChangelogError::FileSystemError {
                path: changelog_path.clone(),
                reason: e.as_ref().to_string(),
            }
        })?;

        // Parse the content
        let parser = ChangelogParser::new();
        parser.parse(&content)
    }

    /// Prepends a new changelog section to existing content.
    ///
    /// This method intelligently inserts the new version section after the header
    /// but before any existing versions, preserving the overall structure of the
    /// changelog.
    ///
    /// The insertion logic:
    /// 1. Finds the first version header (## )
    /// 2. Inserts the new section before it
    /// 3. If no versions exist, appends to the header
    ///
    /// # Arguments
    ///
    /// * `existing` - The existing changelog content
    /// * `new_section` - The new version section to prepend
    ///
    /// # Returns
    ///
    /// The updated changelog content with the new section prepended.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::ChangelogGenerator;
    ///
    /// # fn example(generator: &ChangelogGenerator) {
    /// let existing = "# Changelog\n\n## [1.0.0] - 2024-01-15\n- Old feature";
    /// let new_section = "## [2.0.0] - 2024-02-01\n\n### Features\n- New feature\n";
    ///
    /// let updated = generator.prepend_changelog(existing, new_section);
    /// assert!(updated.contains("## [2.0.0]"));
    /// assert!(updated.contains("## [1.0.0]"));
    /// # }
    /// ```
    pub(crate) fn prepend_changelog(&self, existing: &str, new_section: &str) -> String {
        let lines: Vec<&str> = existing.lines().collect();

        // Find the position of the first version header (starts with "## ")
        let insert_pos =
            lines.iter().position(|line| line.starts_with("## ")).unwrap_or(lines.len());

        let mut result = String::new();

        // Add lines before insert position (header)
        for (i, line) in lines.iter().enumerate().take(insert_pos) {
            result.push_str(line);
            result.push('\n');

            // Add extra newline after header if this is the last header line
            if i == insert_pos - 1 && insert_pos < lines.len() {
                result.push('\n');
            }
        }

        // If we're at the end (no existing versions), ensure proper spacing
        if insert_pos == lines.len() && !result.is_empty() && !result.ends_with("\n\n") {
            if !result.ends_with('\n') {
                result.push('\n');
            }
            result.push('\n');
        }

        // Add new section
        result.push_str(new_section);

        // Ensure proper spacing before existing versions
        if insert_pos < lines.len() && !new_section.ends_with("\n\n") {
            if !new_section.ends_with('\n') {
                result.push('\n');
            }
            result.push('\n');
        }

        // Add remaining lines (existing versions)
        for line in lines.iter().skip(insert_pos) {
            result.push_str(line);
            result.push('\n');
        }

        // Remove trailing newlines beyond two
        while result.ends_with("\n\n\n") {
            result.pop();
        }

        result
    }

    /// Generates changelogs from a changeset and version resolution.
    ///
    /// This method takes a changeset with commits and a version resolution with
    /// package updates, then generates changelog entries for each affected package.
    /// It respects the configured monorepo mode and generates changelogs accordingly.
    ///
    /// # Arguments
    ///
    /// * `changeset` - The changeset containing commits and package information
    /// * `version_resolution` - Resolved versions for all affected packages
    ///
    /// # Returns
    ///
    /// A vector of `GeneratedChangelog` instances, one for each package that
    /// needs a changelog update.
    ///
    /// # Errors
    ///
    /// This method returns an error if:
    /// - Monorepo detection fails
    /// - Package information cannot be loaded
    /// - Commit collection fails
    /// - Changelog generation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::ChangelogGenerator;
    /// use sublime_pkg_tools::changeset::ChangesetManager;
    /// use sublime_pkg_tools::version::VersionResolver;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let generator = ChangelogGenerator::new(workspace_root, git_repo, fs, config).await?;
    /// let changeset_manager = ChangesetManager::new(changeset_storage, git_repo).await?;
    /// let version_resolver = VersionResolver::new(&workspace_root, &config).await?;
    ///
    /// // Load changeset
    /// let changeset = changeset_manager.load("feature-branch").await?;
    ///
    /// // Resolve versions
    /// let resolution = version_resolver.resolve_versions(&changeset).await?;
    ///
    /// // Generate changelogs
    /// let changelogs = generator.generate_from_changeset(&changeset, &resolution).await?;
    ///
    /// for generated in &changelogs {
    ///     println!("Generated changelog for: {:?}", generated.package_name);
    ///     generated.write(&fs).await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn generate_from_changeset(
        &self,
        changeset: &crate::types::Changeset,
        version_resolution: &crate::version::VersionResolution,
    ) -> ChangelogResult<Vec<crate::changelog::GeneratedChangelog>> {
        use sublime_standard_tools::monorepo::{MonorepoDetector, MonorepoDetectorTrait};

        // Check if this is a monorepo
        let monorepo_detector = MonorepoDetector::with_filesystem(self.fs.clone());
        let is_monorepo = monorepo_detector
            .is_monorepo_root(&self.workspace_root)
            .await
            .map_err(|e| ChangelogError::FileSystemError {
                path: self.workspace_root.clone(),
                reason: e.as_ref().to_string(),
            })?
            .is_some();

        let mut generated_changelogs = Vec::new();

        // Determine which packages need changelogs based on monorepo_mode
        match self.config.monorepo_mode {
            crate::config::MonorepoMode::PerPackage => {
                // Generate changelog for each updated package
                if is_monorepo {
                    generated_changelogs.extend(
                        self.generate_per_package_changelogs(changeset, version_resolution).await?,
                    );
                } else {
                    // Single package - generate root changelog
                    generated_changelogs
                        .extend(self.generate_root_changelog(changeset, version_resolution).await?);
                }
            }
            crate::config::MonorepoMode::Root => {
                // Generate only root changelog
                generated_changelogs
                    .extend(self.generate_root_changelog(changeset, version_resolution).await?);
            }
            crate::config::MonorepoMode::Both => {
                // Generate both per-package and root changelogs
                if is_monorepo {
                    generated_changelogs.extend(
                        self.generate_per_package_changelogs(changeset, version_resolution).await?,
                    );
                }
                generated_changelogs
                    .extend(self.generate_root_changelog(changeset, version_resolution).await?);
            }
        }

        Ok(generated_changelogs)
    }

    /// Generates changelogs for each package in a monorepo.
    ///
    /// # Arguments
    ///
    /// * `changeset` - The changeset with commits
    /// * `version_resolution` - Resolved versions for packages
    ///
    /// # Returns
    ///
    /// A vector of generated changelogs, one per package.
    async fn generate_per_package_changelogs(
        &self,
        _changeset: &crate::types::Changeset,
        version_resolution: &crate::version::VersionResolution,
    ) -> ChangelogResult<Vec<crate::changelog::GeneratedChangelog>> {
        use crate::changelog::GeneratedChangelog;
        use sublime_standard_tools::filesystem::AsyncFileSystem;

        let mut changelogs = Vec::new();

        for update in &version_resolution.updates {
            // Load package.json to get package name
            let package_json_path = update.path.join("package.json");
            let package_json_content =
                self.fs.read_file_string(&package_json_path).await.map_err(|_e| {
                    ChangelogError::PackageNotFound { package: update.name.clone() }
                })?;

            let package_json: package_json::PackageJson =
                serde_json::from_str(&package_json_content).map_err(|e| {
                    ChangelogError::FileSystemError {
                        path: package_json_path.clone(),
                        reason: format!("Failed to parse package.json: {}", e),
                    }
                })?;

            let package_name = package_json.name.clone();

            // Determine relative path for commit filtering
            let relative_path = update
                .path
                .strip_prefix(&self.workspace_root)
                .ok()
                .and_then(|p| p.to_str())
                .map(String::from);

            // Determine previous version for Git refs
            let previous_version = if let Ok(prev_tag) = self
                .detect_previous_version(Some(&package_name), &update.next_version.to_string())
                .await
            {
                prev_tag.map(|t| t.version().to_string())
            } else {
                None
            };

            // Build Git refs and collect commits
            let (sections, from_ref, to_ref) = if let Some(ref prev_version) = previous_version {
                let (from_ref, to_ref) = self.build_git_refs(
                    Some(&package_name),
                    Some(prev_version.as_str()),
                    &update.next_version.to_string(),
                )?;

                // Collect commits for this package
                let collector = ChangelogCollector::new(&self.git_repo, &self.config);
                let sections = collector
                    .collect_between_versions(&from_ref, &to_ref, relative_path.as_deref())
                    .await?;

                (sections, from_ref, to_ref)
            } else {
                // No previous version - try to collect all commits using git log
                // If that fails (empty repo), return empty sections
                let collector = ChangelogCollector::new(&self.git_repo, &self.config);

                // Try to get commits since the beginning
                // Use get_commits_since with None to get all commits
                let commits_result = self.git_repo.get_commits_since(None, &relative_path);

                let sections = if let Ok(commits) = commits_result {
                    collector.process_commits(commits)?
                } else {
                    // Empty repo or no commits accessible
                    Vec::new()
                };

                // Use empty refs for metadata when no previous version
                (sections, String::new(), "HEAD".to_string())
            };

            // Build metadata
            let metadata = self.build_metadata(
                Some(&package_name),
                &update.next_version.to_string(),
                previous_version.as_deref(),
                &from_ref,
                &to_ref,
                &sections,
            )?;

            // Create changelog
            let mut changelog = crate::changelog::Changelog::new(
                Some(&package_name),
                &update.next_version.to_string(),
                previous_version.as_deref(),
                chrono::Utc::now(),
            );

            for section in sections {
                changelog.add_section(section);
            }

            changelog.metadata = metadata;

            // Render to markdown
            let content = changelog.to_markdown(&self.config);

            // Determine changelog path
            let changelog_path = update.path.join(&self.config.filename);
            let existing = self.fs.exists(&changelog_path).await;

            changelogs.push(GeneratedChangelog::new(
                Some(package_name),
                update.path.clone(),
                changelog,
                content,
                existing,
                changelog_path,
            ));
        }

        Ok(changelogs)
    }

    /// Generates a root changelog for the entire workspace.
    ///
    /// # Arguments
    ///
    /// * `changeset` - The changeset with commits
    /// * `version_resolution` - Resolved versions for packages
    ///
    /// # Returns
    ///
    /// A vector containing a single root changelog.
    async fn generate_root_changelog(
        &self,
        _changeset: &crate::types::Changeset,
        version_resolution: &crate::version::VersionResolution,
    ) -> ChangelogResult<Vec<crate::changelog::GeneratedChangelog>> {
        use crate::changelog::GeneratedChangelog;
        use sublime_standard_tools::filesystem::AsyncFileSystem;

        // For root changelog, we need to determine a version
        // Use the highest version from the resolution, or construct one
        let version = if let Some(first_update) = version_resolution.updates.first() {
            first_update.next_version.to_string()
        } else {
            // No updates - shouldn't happen, but handle gracefully
            return Ok(Vec::new());
        };

        // Determine previous version for Git refs
        let previous_version =
            if let Ok(prev_tag) = self.detect_previous_version(None, &version).await {
                prev_tag.map(|t| t.version().to_string())
            } else {
                None
            };

        // Build Git refs and collect commits
        let collector = ChangelogCollector::new(&self.git_repo, &self.config);
        let (sections, from_ref, to_ref) = if let Some(ref prev_version) = previous_version {
            let (from_ref, to_ref) =
                self.build_git_refs(None, Some(prev_version.as_str()), &version)?;
            let sections = collector.collect_between_versions(&from_ref, &to_ref, None).await?;
            (sections, from_ref, to_ref)
        } else {
            // No previous version - try to collect all commits
            let commits_result = self.git_repo.get_commits_since(None, &None);

            let sections = if let Ok(commits) = commits_result {
                collector.process_commits(commits)?
            } else {
                // Empty repo or no commits accessible
                Vec::new()
            };

            // Use empty refs for metadata when no previous version
            (sections, String::new(), "HEAD".to_string())
        };

        // Build metadata
        let metadata = self.build_metadata(
            None,
            &version,
            previous_version.as_deref(),
            &from_ref,
            &to_ref,
            &sections,
        )?;

        // Create changelog
        let mut changelog = crate::changelog::Changelog::new(
            None,
            &version,
            previous_version.as_deref(),
            chrono::Utc::now(),
        );

        for section in sections {
            changelog.add_section(section);
        }

        changelog.metadata = metadata;

        // Render to markdown
        let content = changelog.to_markdown(&self.config);

        // Determine changelog path (at workspace root)
        let changelog_path = self.workspace_root.join(&self.config.filename);
        let existing = self.fs.exists(&changelog_path).await;

        Ok(vec![GeneratedChangelog::new(
            None,
            self.workspace_root.clone(),
            changelog,
            content,
            existing,
            changelog_path,
        )])
    }
}