requirements-manager 0.1.1

Plain-text requirements management tool
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
use std::{
    collections::BTreeSet,
    fs::File,
    io::{self, BufRead, BufReader, BufWriter, Write},
    path::Path,
};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{
    domain::{
        requirement::{Content, Metadata, Parent as DomainParent},
        Hrid, HridError,
    },
    Requirement,
};

/// A requirement serialized in markdown format with YAML frontmatter.
#[derive(Debug, Clone)]
pub struct MarkdownRequirement {
    frontmatter: FrontMatter,
    hrid: Hrid,
    title: String,
    body: String,
}

impl MarkdownRequirement {
    fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
        let frontmatter = serde_yaml::to_string(&self.frontmatter).expect("this must never fail");

        // Construct the heading with HRID and title
        let heading = format!("# {} {}", self.hrid, self.title);

        // Combine frontmatter, heading, and body
        let result = if self.body.is_empty() {
            format!("---\n{frontmatter}---\n{heading}\n")
        } else {
            format!("---\n{frontmatter}---\n{heading}\n\n{}\n", self.body)
        };

        writer.write_all(result.as_bytes())
    }

    pub(crate) fn read<R: BufRead>(reader: &mut R) -> Result<Self, LoadError> {
        let mut lines = reader.lines();

        // Ensure frontmatter starts correctly
        let first_line = lines
            .next()
            .ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "Empty input"))?
            .map_err(LoadError::from)?;

        if first_line.trim() != "---" {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Expected frontmatter starting with '---'",
            )
            .into());
        }

        // Collect lines until next '---'
        let frontmatter = lines
            .by_ref()
            .map_while(|line| match line {
                Ok(content) if content.trim() == "---" => None,
                Ok(content) => Some(Ok(content)),
                Err(e) => Some(Err(e)),
            })
            .collect::<Result<Vec<_>, _>>()?
            .join("\n");

        // The rest of the lines are Markdown content
        let content = lines.collect::<Result<Vec<_>, _>>()?.join("\n");

        let front: FrontMatter = serde_yaml::from_str(&frontmatter)?;

        // Extract HRID, title, and body from content
        let (hrid, title, body) = parse_content(&content)?;

        Ok(Self {
            frontmatter: front,
            hrid,
            title,
            body,
        })
    }

    /// Writes the requirement to a file path constructed using the given
    /// config.
    ///
    /// The path construction respects the `subfolders_are_namespaces` setting:
    /// - If `false`: file is saved as `root/FULL-HRID.md`
    /// - If `true`: file is saved as `root/namespace/folders/KIND-ID.md`
    ///
    /// Parent directories are created automatically if they don't exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created or written to.
    pub fn save(&self, root: &Path, config: &crate::domain::Config) -> io::Result<()> {
        use crate::storage::construct_path_from_hrid;

        let file_path = construct_path_from_hrid(
            root,
            &self.hrid,
            config.subfolders_are_namespaces,
            config.digits(),
        );

        self.save_to_path(&file_path)
    }

    /// Writes the requirement to a specific file path.
    ///
    /// Parent directories are created automatically if they don't exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created or written to.
    pub fn save_to_path(&self, file_path: &Path) -> io::Result<()> {
        // Create parent directories if needed
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let file = File::create(file_path)?;
        let mut writer = BufWriter::new(file);
        self.write(&mut writer)
    }

    /// Reads a requirement using the given configuration.
    ///
    /// The path construction respects the `subfolders_are_namespaces` setting:
    /// - If `false`: loads from `root/FULL-HRID.md`
    /// - If `true`: loads from `root/namespace/folders/KIND-ID.md`
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed.
    pub fn load(
        root: &Path,
        hrid: &Hrid,
        config: &crate::domain::Config,
    ) -> Result<Self, LoadError> {
        use crate::storage::construct_path_from_hrid;

        let file_path = construct_path_from_hrid(
            root,
            hrid,
            config.subfolders_are_namespaces,
            config.digits(),
        );

        let file = File::open(&file_path).map_err(|io_error| match io_error.kind() {
            io::ErrorKind::NotFound => LoadError::NotFound,
            _ => LoadError::Io(io_error),
        })?;

        let mut reader = BufReader::new(file);
        Self::read(&mut reader)
    }
}

/// Trim empty lines from the start and end of a string, preserving indentation.
///
/// Unlike `.trim()`, this function only removes completely empty lines from
/// the beginning and end, keeping any leading/trailing whitespace on non-empty
/// lines. This is crucial for preserving markdown structures like code blocks,
/// lists, and blockquotes which rely on indentation.
pub(crate) fn trim_empty_lines(s: &str) -> String {
    let lines: Vec<&str> = s.lines().collect();

    // Find first and last non-empty lines
    let first_non_empty = lines.iter().position(|line| !line.trim().is_empty());
    let last_non_empty = lines.iter().rposition(|line| !line.trim().is_empty());

    match (first_non_empty, last_non_empty) {
        (Some(start), Some(end)) => lines[start..=end].join("\n"),
        _ => String::new(),
    }
}

/// Parses markdown content into HRID, title, and body.
///
/// The HRID must be the first token in the first heading (after the `#`
/// markers), followed by the title. The body is everything after the first
/// heading.
///
/// # Errors
///
/// Returns an error if no heading is found or if the HRID cannot be parsed.
fn parse_content(content: &str) -> Result<(Hrid, String, String), LoadError> {
    // Find the first non-empty line that starts with '#'
    let (heading_line_idx, line) = content
        .lines()
        .enumerate()
        .find(|(_, line)| line.trim().starts_with('#'))
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "No heading found in content - HRID must be in the first heading",
            )
        })?;

    let trimmed = line.trim();
    // Remove leading '#' characters and whitespace
    let after_hashes = trimmed.trim_start_matches('#').trim();

    // Extract the first token (should be the HRID)
    let first_token = after_hashes
        .split_whitespace()
        .next()
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "No HRID found in title"))?;

    // Parse the HRID
    let hrid = first_token.parse::<Hrid>().map_err(LoadError::from)?;

    // The rest after the HRID is the title
    let title = after_hashes
        .strip_prefix(first_token)
        .unwrap_or("")
        .trim()
        .to_string();

    // The body is everything after the heading line
    // Preserve leading indentation but trim empty lines from start/end
    let body_content: String = content
        .lines()
        .skip(heading_line_idx + 1)
        .collect::<Vec<_>>()
        .join("\n");
    let body = trim_empty_lines(&body_content);

    Ok((hrid, title, body))
}

/// Errors that can occur when loading a requirement from markdown.
#[derive(Debug, thiserror::Error)]
#[error("failed to read from markdown")]
pub enum LoadError {
    /// The requirement file was not found.
    NotFound,
    /// An I/O error occurred.
    Io(#[from] io::Error),
    /// The YAML frontmatter could not be parsed.
    Yaml(#[from] serde_yaml::Error),
    /// The HRID could not be parsed.
    Hrid(#[from] HridError),
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(from = "FrontMatterVersion")]
#[serde(into = "FrontMatterVersion")]
struct FrontMatter {
    uuid: Uuid,
    created: DateTime<Utc>,
    tags: BTreeSet<String>,
    parents: Vec<Parent>,
}

/// A parent requirement reference in the serialized format.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct Parent {
    uuid: Uuid,
    fingerprint: String,
    #[serde(
        serialize_with = "hrid_as_string",
        deserialize_with = "hrid_from_string"
    )]
    hrid: Hrid,
}

/// Serialize an HRID as a string.
///
/// # Errors
///
/// Returns an error if serialization fails.
pub fn hrid_as_string<S>(hrid: &Hrid, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&hrid.to_string())
}

/// Deserialize an HRID from a string.
///
/// # Errors
///
/// Returns an error if the string cannot be parsed as a valid HRID.
pub fn hrid_from_string<'de, D>(deserializer: D) -> Result<Hrid, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    Hrid::try_from(s.as_str()).map_err(serde::de::Error::custom)
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "_version")]
enum FrontMatterVersion {
    #[serde(rename = "1")]
    V1 {
        uuid: Uuid,
        created: DateTime<Utc>,
        #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
        tags: BTreeSet<String>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        parents: Vec<Parent>,
    },
}

impl From<FrontMatterVersion> for FrontMatter {
    fn from(version: FrontMatterVersion) -> Self {
        match version {
            FrontMatterVersion::V1 {
                uuid,
                created,
                tags,
                parents,
            } => Self {
                uuid,
                created,
                tags,
                parents,
            },
        }
    }
}

impl From<FrontMatter> for FrontMatterVersion {
    fn from(front_matter: FrontMatter) -> Self {
        let FrontMatter {
            uuid,
            created,
            tags,
            parents,
        } = front_matter;
        Self::V1 {
            uuid,
            created,
            tags,
            parents,
        }
    }
}

impl From<Requirement> for MarkdownRequirement {
    fn from(req: Requirement) -> Self {
        let Requirement {
            content: Content { title, body, tags },
            metadata:
                Metadata {
                    uuid,
                    hrid,
                    created,
                    parents,
                },
        } = req;

        let frontmatter = FrontMatter {
            uuid,
            created,
            tags,
            parents: parents
                .into_iter()
                .map(|(uuid, DomainParent { hrid, fingerprint })| Parent {
                    uuid,
                    fingerprint,
                    hrid,
                })
                .collect(),
        };

        Self {
            frontmatter,
            hrid,
            title,
            body,
        }
    }
}

impl TryFrom<MarkdownRequirement> for Requirement {
    type Error = HridError;

    fn try_from(req: MarkdownRequirement) -> Result<Self, Self::Error> {
        let MarkdownRequirement {
            hrid,
            frontmatter:
                FrontMatter {
                    uuid,
                    created,
                    tags,
                    parents,
                },
            title,
            body,
        } = req;

        let parent_map = parents
            .into_iter()
            .map(|parent| {
                let Parent {
                    uuid,
                    fingerprint,
                    hrid: parent_hrid,
                } = parent;
                Ok((
                    uuid,
                    DomainParent {
                        hrid: parent_hrid,
                        fingerprint,
                    },
                ))
            })
            .collect::<Result<_, Self::Error>>()?;

        Ok(Self {
            content: Content { title, body, tags },
            metadata: Metadata {
                uuid,
                hrid,
                created,
                parents: parent_map,
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use std::{io::Cursor, num::NonZeroUsize};

    use chrono::TimeZone;
    use tempfile::TempDir;

    use super::{Parent, *};
    use crate::domain::hrid::KindString;

    fn req_hrid() -> Hrid {
        Hrid::new(
            KindString::new("REQ".to_string()).unwrap(),
            NonZeroUsize::new(1).unwrap(),
        )
    }

    fn create_test_frontmatter() -> FrontMatter {
        let uuid = Uuid::parse_str("12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53").unwrap();
        let created = Utc.with_ymd_and_hms(2025, 7, 14, 7, 15, 0).unwrap();
        let tags = BTreeSet::from(["tag1".to_string(), "tag2".to_string()]);
        let parents = vec![Parent {
            uuid: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
            fingerprint: "fingerprint1".to_string(),
            hrid: "REQ-PARENT-001".parse().unwrap(),
        }];
        FrontMatter {
            uuid,
            created,
            tags,
            parents,
        }
    }

    #[test]
    fn markdown_round_trip() {
        let input = r"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
tags:
- tag1
- tag2
parents:
- uuid: 550e8400-e29b-41d4-a716-446655440000
  fingerprint: fingerprint1
  hrid: REQ-PARENT-001
---
# REQ-001 The Title

This is a paragraph.
";

        let mut reader = Cursor::new(input);
        let requirement = MarkdownRequirement::read(&mut reader).unwrap();

        assert_eq!(requirement.hrid, req_hrid());

        let mut bytes: Vec<u8> = vec![];
        requirement.write(&mut bytes).unwrap();

        let actual = String::from_utf8(bytes).unwrap();
        assert_eq!(input, &actual);
    }

    #[test]
    fn markdown_minimal_content() {
        let hrid = req_hrid();
        let content = r"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
---
# REQ-001 Just content
";

        let mut reader = Cursor::new(content);
        let requirement = MarkdownRequirement::read(&mut reader).unwrap();

        assert_eq!(requirement.hrid, hrid);
        assert_eq!(requirement.title, "Just content");
        assert_eq!(requirement.body, "");
        assert!(requirement.frontmatter.tags.is_empty());
        assert!(requirement.frontmatter.parents.is_empty());
    }

    #[test]
    fn hrid_only_title() {
        let content = r"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
---
# REQ-001
";

        let mut reader = Cursor::new(content);
        let requirement = MarkdownRequirement::read(&mut reader).unwrap();

        assert_eq!(requirement.hrid, req_hrid());
        assert_eq!(requirement.title, "");
        assert_eq!(requirement.body, "");
    }

    #[test]
    fn multiline_content() {
        let content = r"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
---
# REQ-001 Title

Line 2

Line 4
";

        let mut reader = Cursor::new(content);
        let requirement = MarkdownRequirement::read(&mut reader).unwrap();

        assert_eq!(requirement.hrid, req_hrid());
        assert_eq!(requirement.title, "Title");
        assert_eq!(requirement.body, "Line 2\n\nLine 4");
    }

    #[test]
    fn invalid_frontmatter_start() {
        let content = "invalid frontmatter";

        let mut reader = Cursor::new(content);
        let result = MarkdownRequirement::read(&mut reader);

        assert!(result.is_err());
    }

    #[test]
    fn missing_frontmatter_end() {
        let content = r"---
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
This should be content but there's no closing ---";

        let mut reader = Cursor::new(content);
        let result = MarkdownRequirement::read(&mut reader);

        assert!(result.is_err());
    }

    #[test]
    fn invalid_yaml() {
        let content = r"---
invalid: yaml: structure:
created: not-a-date
---
# REQ-001 Content";

        let mut reader = Cursor::new(content);
        let result = MarkdownRequirement::read(&mut reader);

        assert!(matches!(result, Err(LoadError::Yaml(_))));
    }

    #[test]
    fn empty_input() {
        let content = "";

        let mut reader = Cursor::new(content);
        let result = MarkdownRequirement::read(&mut reader);

        assert!(result.is_err());
    }

    #[test]
    fn write_success() {
        let frontmatter = create_test_frontmatter();
        let requirement = MarkdownRequirement {
            frontmatter,
            hrid: req_hrid(),
            title: "Test content".to_string(),
            body: String::new(),
        };

        let mut buffer = Vec::new();
        let result = requirement.write(&mut buffer);

        assert!(result.is_ok());
        let output = String::from_utf8(buffer).unwrap();
        assert!(output.contains("---"));
        assert!(output.contains("# REQ-001 Test content"));
        // The frontmatter should not have an hrid field at the top level
        // (though parent entries still contain hrid fields)
        let lines: Vec<&str> = output.lines().collect();
        let frontmatter_end = lines
            .iter()
            .skip(1)
            .position(|l| l.trim() == "---")
            .unwrap()
            + 1;
        let frontmatter_lines = &lines[1..frontmatter_end];
        let has_top_level_hrid = frontmatter_lines
            .iter()
            .any(|line| line.starts_with("hrid:") && !line.contains("  "));
        assert!(
            !has_top_level_hrid,
            "Frontmatter should not have top-level hrid field"
        );
    }

    #[test]
    fn save_and_load() {
        let temp_dir = TempDir::new().unwrap();
        let frontmatter = create_test_frontmatter();
        let hrid = req_hrid();
        let title = "Saved content".to_string();
        let body = "Some body text".to_string();

        let requirement = MarkdownRequirement {
            frontmatter: frontmatter.clone(),
            hrid: hrid.clone(),
            title: title.clone(),
            body: body.clone(),
        };

        // Test save
        let config = crate::domain::Config::default();
        let save_result = requirement.save(temp_dir.path(), &config);
        assert!(save_result.is_ok());

        // Test load
        let loaded_requirement =
            MarkdownRequirement::load(temp_dir.path(), &hrid, &config).unwrap();
        assert_eq!(loaded_requirement.hrid, hrid);
        assert_eq!(loaded_requirement.title, title);
        assert_eq!(loaded_requirement.body, body);
        assert_eq!(loaded_requirement.frontmatter, frontmatter);
    }

    #[test]
    fn load_nonexistent_file() {
        let temp_dir = TempDir::new().unwrap();
        let config = crate::domain::Config::default();
        let result = MarkdownRequirement::load(temp_dir.path(), &req_hrid(), &config);
        assert!(matches!(result, Err(LoadError::NotFound)));
    }

    #[test]
    fn frontmatter_version_conversion() {
        let uuid = Uuid::parse_str("12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53").unwrap();
        let created = Utc.with_ymd_and_hms(2025, 7, 14, 7, 15, 0).unwrap();
        let tags = BTreeSet::from(["tag1".to_owned()]);
        let parents = vec![Parent {
            uuid: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
            fingerprint: "fp1".to_string(),
            hrid: req_hrid(),
        }];

        let frontmatter = FrontMatter {
            uuid,
            created,
            tags,
            parents,
        };
        let version: FrontMatterVersion = frontmatter.clone().into();
        let back_to_frontmatter: FrontMatter = version.into();

        assert_eq!(frontmatter, back_to_frontmatter);
    }

    #[test]
    fn parent_creation() {
        let uuid = Uuid::parse_str("12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53").unwrap();
        let fingerprint = "test-fingerprint".to_string();
        let hrid = req_hrid();

        let parent = Parent {
            uuid,
            fingerprint: fingerprint.clone(),
            hrid: hrid.clone(),
        };

        assert_eq!(parent.uuid, uuid);
        assert_eq!(parent.fingerprint, fingerprint);
        assert_eq!(parent.hrid, hrid);
    }

    #[test]
    fn content_with_triple_dashes() {
        let content = r"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
---
# REQ-001 Content

This content has --- in it
And more --- here
";

        let mut reader = Cursor::new(content);
        let requirement = MarkdownRequirement::read(&mut reader).unwrap();

        assert_eq!(requirement.hrid, req_hrid());
        assert_eq!(requirement.title, "Content");
        assert_eq!(
            requirement.body,
            "This content has --- in it\nAnd more --- here"
        );
    }

    #[test]
    fn frontmatter_with_special_characters() {
        let content = r#"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
tags:
- "tag with spaces"
- "tag-with-dashes"
- "tag_with_underscores"
---
# REQ-001 Content here
"#;

        let mut reader = Cursor::new(content);
        let requirement = MarkdownRequirement::read(&mut reader).unwrap();

        assert_eq!(requirement.hrid, req_hrid());
        assert!(requirement.frontmatter.tags.contains("tag with spaces"));
        assert!(requirement.frontmatter.tags.contains("tag-with-dashes"));
        assert!(requirement
            .frontmatter
            .tags
            .contains("tag_with_underscores"));
    }

    #[test]
    fn missing_hrid_in_title() {
        let content = r"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
---
# Just a title without HRID
";

        let mut reader = Cursor::new(content);
        let result = MarkdownRequirement::read(&mut reader);

        assert!(matches!(result, Err(LoadError::Hrid(_))));
    }

    #[test]
    fn no_heading_in_content() {
        let content = r"---
_version: '1'
uuid: 12b3f5c5-b1a8-4aa8-a882-20ff1c2aab53
created: 2025-07-14T07:15:00Z
---
Just plain text without a heading
";

        let mut reader = Cursor::new(content);
        let result = MarkdownRequirement::read(&mut reader);

        assert!(matches!(result, Err(LoadError::Io(_))));
    }

    #[test]
    fn trim_empty_lines_removes_only_empty_lines() {
        assert_eq!(trim_empty_lines(""), "");
        assert_eq!(trim_empty_lines("\n\n"), "");
        assert_eq!(trim_empty_lines("content"), "content");
        assert_eq!(trim_empty_lines("\n\ncontent\n\n"), "content");
    }

    #[test]
    fn trim_empty_lines_preserves_leading_indentation() {
        assert_eq!(trim_empty_lines("    indented"), "    indented");
        assert_eq!(trim_empty_lines("\n    indented\n"), "    indented");
        assert_eq!(
            trim_empty_lines("    code block\n    more code"),
            "    code block\n    more code"
        );
    }

    #[test]
    fn trim_empty_lines_preserves_internal_empty_lines() {
        assert_eq!(trim_empty_lines("line1\n\nline2"), "line1\n\nline2");
        assert_eq!(trim_empty_lines("\nline1\n\nline2\n"), "line1\n\nline2");
    }

    #[test]
    fn trim_empty_lines_handles_markdown_structures() {
        // Code block
        let code = "    fn main() {\n        println!(\"hello\");\n    }";
        assert_eq!(trim_empty_lines(code), code);

        // List with indentation
        let list = "- Item 1\n  - Sub item\n- Item 2";
        assert_eq!(trim_empty_lines(list), list);

        // Blockquote
        let quote = "> This is a quote\n> with multiple lines";
        assert_eq!(trim_empty_lines(quote), quote);
    }

    #[test]
    fn trim_empty_lines_with_trailing_whitespace_lines() {
        // Lines with only spaces should be treated as empty
        assert_eq!(trim_empty_lines("   \n\ncontent\n   \n"), "content");
    }

    #[test]
    fn parse_content_preserves_body_indentation() {
        let content = "# REQ-001 Title\n\n    code block\n    more code";
        let (hrid, title, body) = parse_content(content).unwrap();

        assert_eq!(hrid.to_string(), "REQ-001");
        assert_eq!(title, "Title");
        assert_eq!(body, "    code block\n    more code");
    }

    #[test]
    fn parse_content_trims_empty_lines_around_body() {
        let content = "# REQ-001 Title\n\n\n\ncontent\n\n\n";
        let (_hrid, _title, body) = parse_content(content).unwrap();

        assert_eq!(body, "content");
    }

    #[test]
    fn round_trip_preserves_indentation() {
        let temp_dir = TempDir::new().unwrap();
        let frontmatter = create_test_frontmatter();
        let hrid = req_hrid();
        let title = "Code Example".to_string();
        let body = "Here's a code block:\n\n    fn main() {\n        println!(\"hello\");\n    \
                    }\n\nAnd a list:\n\n- Item 1\n  - Sub item\n- Item 2"
            .to_string();

        let requirement = MarkdownRequirement {
            frontmatter,
            hrid: hrid.clone(),
            title,
            body: body.clone(),
        };

        // Save and reload
        let config = crate::domain::Config::default();
        requirement.save(temp_dir.path(), &config).unwrap();
        let loaded = MarkdownRequirement::load(temp_dir.path(), &hrid, &config).unwrap();

        // Verify indentation is preserved
        assert_eq!(loaded.body, body);
    }
}