sara-cli 0.7.6

CLI for Sara - Requirements Knowledge Graph
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
//! Interactive mode for the init command.
//!
//! Provides terminal prompts for creating requirement documents when
//! the --type argument is not provided (FR-040 through FR-052).

use std::io::{IsTerminal, stdin, stdout};
use std::path::PathBuf;

use inquire::validator::{StringValidator, Validation};
use inquire::{Confirm, InquireError, MultiSelect, Select, Text};
use sara_core::error::SaraError;
use sara_core::graph::{KnowledgeGraph, KnowledgeGraphBuilder};
use sara_core::model::{FieldName, ItemType, TraceabilityLinks};
use sara_core::repository::parse_repositories;
use thiserror::Error;

use crate::output::{OutputConfig, print_error};

/// Fields pre-provided via CLI arguments (FR-050).
#[derive(Debug, Default)]
pub struct PrefilledFields {
    pub file: Option<PathBuf>,
    pub item_type: Option<ItemType>,
    pub id: Option<String>,
    pub name: Option<String>,
    pub description: Option<String>,
    pub refines: Vec<String>,
    pub derives_from: Vec<String>,
    pub satisfies: Vec<String>,
    pub depends_on: Vec<String>,
    pub specification: Option<String>,
    pub platform: Option<String>,
    pub deciders: Vec<String>,
    pub justifies: Vec<String>,
}

/// Configuration for an interactive init session.
pub struct InteractiveSession<'a> {
    /// Pre-parsed knowledge graph for traceability lookups.
    pub graph: Option<KnowledgeGraph>,

    /// Pre-provided fields from CLI arguments (skip prompts for these).
    pub prefilled: PrefilledFields,

    /// Repository paths for graph building.
    pub repositories: &'a [PathBuf],

    /// Output configuration for colors and emojis.
    pub output: &'a OutputConfig,
}

/// Collected input from interactive session.
#[derive(Debug)]
pub struct InteractiveInput {
    pub file: PathBuf,
    pub item_type: ItemType,
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub traceability: TraceabilityLinks,
    pub type_specific: TypeSpecificInput,
}

/// Type-specific fields.
#[derive(Debug, Default)]
pub enum TypeSpecificInput {
    /// No type-specific fields (Solution, UseCase, Scenario, DetailedDesign).
    #[default]
    None,
    /// For requirement types (SystemRequirement, SoftwareRequirement, HardwareRequirement).
    Requirement { specification: Option<String> },
    /// For SystemArchitecture.
    SystemArchitecture { platform: Option<String> },
    /// For Architecture Decision Records.
    Adr { deciders: Vec<String> },
}

/// Errors that can occur during interactive prompts.
#[derive(Debug, Error)]
pub enum PromptError {
    #[error("Interactive mode requires a terminal. Use --type <TYPE> to specify the item type.")]
    NonInteractiveTerminal,

    #[error(transparent)]
    MissingParent(#[from] SaraError),

    #[error("User cancelled")]
    Cancelled,

    #[error("Prompt error: {0}")]
    InquireError(#[from] InquireError),
}

/// Option displayed in Select/MultiSelect prompts.
#[derive(Debug, Clone)]
pub struct SelectOption {
    /// Item ID (e.g., "SOL-001").
    pub id: String,
    /// Item name for display.
    pub name: String,
}

impl std::fmt::Display for SelectOption {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} - {}", self.id, self.name)
    }
}

/// Checks if the terminal is interactive (FR-051).
pub fn require_tty() -> Result<(), PromptError> {
    if !stdin().is_terminal() || !stdout().is_terminal() {
        return Err(PromptError::NonInteractiveTerminal);
    }
    Ok(())
}

/// ID format validator (alphanumeric, hyphens, underscores).
#[derive(Clone)]
struct IdValidator;

impl StringValidator for IdValidator {
    fn validate(&self, input: &str) -> Result<Validation, inquire::CustomUserError> {
        if input.is_empty() {
            return Ok(Validation::Invalid("ID cannot be empty".into()));
        }

        if input
            .chars()
            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
        {
            Ok(Validation::Valid)
        } else {
            Ok(Validation::Invalid(
                "ID must contain only letters, numbers, hyphens, and underscores".into(),
            ))
        }
    }
}

/// Name length validator (non-empty, reasonable length).
#[derive(Clone)]
struct NameValidator;

impl StringValidator for NameValidator {
    fn validate(&self, input: &str) -> Result<Validation, inquire::CustomUserError> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Ok(Validation::Invalid("Name is required".into()));
        }
        if trimmed.len() > 200 {
            return Ok(Validation::Invalid(
                "Name must be 200 characters or less".into(),
            ));
        }
        Ok(Validation::Valid)
    }
}

/// Prompts for item type selection (FR-041).
fn prompt_item_type(prefilled: Option<ItemType>) -> Result<ItemType, PromptError> {
    if let Some(item_type) = prefilled {
        return Ok(item_type);
    }

    let options: Vec<ItemType> = ItemType::all().to_vec();
    let selection = Select::new("Select item type:", options)
        .with_help_message("Use arrow keys to navigate, Enter to select")
        .prompt()?;

    Ok(selection)
}

/// Prompts for item name (FR-042, FR-056).
///
/// If `prefilled` is Some, returns that value without prompting.
/// If `default` is Some, shows that value as the default in the prompt.
pub fn prompt_name(
    prefilled: Option<&String>,
    default: Option<&str>,
) -> Result<String, PromptError> {
    if let Some(name) = prefilled {
        return Ok(name.clone());
    }

    let mut prompt = Text::new("Item name:")
        .with_validator(NameValidator)
        .with_help_message("Enter a human-readable name for this item");

    if let Some(def) = default {
        prompt = prompt.with_default(def);
    }

    let name = prompt.prompt()?;
    Ok(name.trim().to_string())
}

/// Prompts for item description (FR-043, FR-056).
///
/// If `prefilled` is Some, returns that value without prompting.
/// If `default` is Some, shows that value as the default in the prompt.
pub fn prompt_description(
    prefilled: Option<&String>,
    default: Option<&str>,
) -> Result<Option<String>, PromptError> {
    if let Some(desc) = prefilled {
        return Ok(Some(desc.clone()));
    }

    let mut prompt = Text::new("Description (optional):")
        .with_help_message("Brief summary of the item (press Enter to skip)");

    if let Some(def) = default {
        prompt = prompt.with_default(def);
    }

    let desc = prompt.prompt()?;
    let trimmed = desc.trim();
    if trimmed.is_empty() {
        Ok(None)
    } else {
        Ok(Some(trimmed.to_string()))
    }
}

/// Prompts for identifier with suggested default (FR-044).
fn prompt_identifier(
    item_type: ItemType,
    graph: Option<&KnowledgeGraph>,
    prefilled: Option<&String>,
) -> Result<String, PromptError> {
    if let Some(id) = prefilled {
        return Ok(id.clone());
    }

    let suggested = item_type.suggest_next_id(graph);
    let id = Text::new("Identifier:")
        .with_default(&suggested)
        .with_validator(IdValidator)
        .with_help_message("Unique identifier (suggested default shown)")
        .prompt()?;

    Ok(id.trim().to_string())
}

/// Gets items of specific types for traceability selection.
///
/// If `exclude_id` is provided, that item will be filtered out (to prevent self-references).
fn get_items_of_type(
    graph: Option<&KnowledgeGraph>,
    item_type: ItemType,
    exclude_id: Option<&str>,
) -> Vec<SelectOption> {
    graph
        .map(|g| {
            g.items()
                .filter(|item| item.item_type == item_type)
                .filter(|item| exclude_id.is_none_or(|id| item.id.as_str() != id))
                .map(|item| SelectOption {
                    id: item.id.as_str().to_string(),
                    name: item.name.clone(),
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Type alias for pre-selected traceability items (edit mode, FR-056).
/// Uses TraceabilityLinks from sara-core.
pub type PreselectedTraceability = TraceabilityLinks;

/// Helper to compute default selection indices for MultiSelect.
fn compute_default_indices(options: &[SelectOption], preselected: &[String]) -> Vec<usize> {
    options
        .iter()
        .enumerate()
        .filter(|(_, opt)| preselected.contains(&opt.id))
        .map(|(i, _)| i)
        .collect()
}

/// The type of traceability relationship (CLI-specific enum for prompt handling).
#[derive(Debug, Clone, Copy)]
enum TraceabilityKind {
    Refines,
    DerivesFrom,
    Satisfies,
    DependsOn,
    Justifies,
}

impl TraceabilityKind {
    /// Creates a TraceabilityKind from the FieldName.
    fn from_field(field: FieldName) -> Self {
        match field {
            FieldName::Refines => Self::Refines,
            FieldName::DerivesFrom => Self::DerivesFrom,
            FieldName::Satisfies => Self::Satisfies,
            FieldName::DependsOn => Self::DependsOn,
            FieldName::Justifies => Self::Justifies,
            _ => Self::Refines, // Fallback
        }
    }
}

/// Configuration for a traceability prompt (CLI-specific).
struct TraceabilityPromptConfig {
    kind: TraceabilityKind,
    target_type: ItemType,
    prompt_message: String,
}

/// Returns the traceability prompt configurations for an item type.
///
/// Uses core's `ItemType::traceability_configs()` for domain logic,
/// adds CLI-specific prompt messages.
fn get_traceability_prompt_configs(item_type: ItemType) -> Vec<TraceabilityPromptConfig> {
    item_type
        .traceability_configs()
        .into_iter()
        .map(|config| {
            let kind = TraceabilityKind::from_field(config.relationship_field);

            let prompt_message = format!(
                "Select {} this {} {}:",
                config.target_type.display_name(),
                item_type.display_name(),
                config.relationship_field.as_str().replace('_', " ")
            );

            TraceabilityPromptConfig {
                kind,
                target_type: config.target_type,
                prompt_message,
            }
        })
        .collect()
}

/// Gets the prefilled values for a traceability kind.
fn get_prefilled_for_kind(prefilled: &PrefilledFields, kind: TraceabilityKind) -> &[String] {
    match kind {
        TraceabilityKind::Refines => &prefilled.refines,
        TraceabilityKind::DerivesFrom => &prefilled.derives_from,
        TraceabilityKind::Satisfies => &prefilled.satisfies,
        TraceabilityKind::DependsOn => &prefilled.depends_on,
        TraceabilityKind::Justifies => &prefilled.justifies,
    }
}

/// Gets the preselected values for a traceability kind.
fn get_preselected_for_kind(
    preselected: Option<&PreselectedTraceability>,
    kind: TraceabilityKind,
) -> Vec<String> {
    preselected
        .map(|p| match kind {
            TraceabilityKind::Refines => p.refines.clone(),
            TraceabilityKind::DerivesFrom => p.derives_from.clone(),
            TraceabilityKind::Satisfies => p.satisfies.clone(),
            TraceabilityKind::DependsOn => p.depends_on.clone(),
            TraceabilityKind::Justifies => p.justifies.clone(),
        })
        .unwrap_or_default()
}

/// Prompts for selecting parent items and returns the selected IDs.
fn prompt_target_selection(
    options: Vec<SelectOption>,
    prompt_message: &str,
    preselected_ids: &[String],
) -> Result<Vec<String>, PromptError> {
    if options.is_empty() {
        return Ok(Vec::new());
    }

    let defaults = compute_default_indices(&options, preselected_ids);
    let selected = MultiSelect::new(prompt_message, options)
        .with_help_message("Space to select, Enter to confirm")
        .with_default(&defaults)
        .prompt()?;

    Ok(selected.into_iter().map(|s| s.id).collect())
}

/// Applies selected IDs to the appropriate field in TraceabilityLinks.
/// Uses extend to accumulate selections across multiple prompts for the same kind.
fn apply_selection_to_input(
    input: &mut TraceabilityLinks,
    kind: TraceabilityKind,
    ids: Vec<String>,
) {
    match kind {
        TraceabilityKind::Refines => input.refines.extend(ids),
        TraceabilityKind::DerivesFrom => input.derives_from.extend(ids),
        TraceabilityKind::Satisfies => input.satisfies.extend(ids),
        TraceabilityKind::DependsOn => input.depends_on.extend(ids),
        TraceabilityKind::Justifies => input.justifies.extend(ids),
    }
}

/// Prompts for traceability relationships (FR-045, FR-056).
///
/// If `preselected` is Some, those items will be pre-checked in the MultiSelect.
/// Requirement types prompt for both hierarchical (derives_from) and peer (depends_on) links.
/// If `exclude_id` is Some, that item will be filtered out of the selection list
/// (used during edit to prevent self-references in peer dependencies).
pub fn prompt_traceability(
    item_type: ItemType,
    graph: Option<&KnowledgeGraph>,
    prefilled: &PrefilledFields,
    preselected: Option<&PreselectedTraceability>,
    exclude_id: Option<&str>,
) -> Result<TraceabilityLinks, PromptError> {
    let mut input = TraceabilityLinks::default();

    let configs = get_traceability_prompt_configs(item_type);
    if configs.is_empty() {
        return Ok(input);
    }

    for config in configs {
        let prefilled_values = get_prefilled_for_kind(prefilled, config.kind);
        if !prefilled_values.is_empty() {
            apply_selection_to_input(&mut input, config.kind, prefilled_values.to_vec());
            continue;
        }

        let options = get_items_of_type(graph, config.target_type, exclude_id);
        let preselected_ids = get_preselected_for_kind(preselected, config.kind);
        let selected = prompt_target_selection(options, &config.prompt_message, &preselected_ids)?;
        apply_selection_to_input(&mut input, config.kind, selected);
    }

    Ok(input)
}

/// Prompts for specification (FR-046, FR-056, for requirement types).
///
/// If `prefilled` is Some, returns that value without prompting.
/// If `default` is Some, shows that value as the default in the prompt.
pub fn prompt_specification(
    item_type: ItemType,
    prefilled: Option<&String>,
    default: Option<&str>,
) -> Result<Option<String>, PromptError> {
    if !item_type.requires_specification() {
        return Ok(None);
    }

    if let Some(spec) = prefilled {
        return Ok(Some(spec.clone()));
    }

    let mut prompt = Text::new("Specification:")
        .with_help_message("Enter the SHALL statement (e.g., 'The system SHALL...')")
        .with_validator(NameValidator); // Reuse for non-empty

    if let Some(def) = default {
        prompt = prompt.with_default(def);
    }

    let spec = prompt.prompt()?;
    Ok(Some(spec.trim().to_string()))
}

/// Prompts for platform (FR-046, FR-056, for system_architecture).
///
/// If `prefilled` is Some, returns that value without prompting.
/// If `default` is Some, shows that value as the default in the prompt.
pub fn prompt_platform(
    item_type: ItemType,
    prefilled: Option<&String>,
    default: Option<&str>,
) -> Result<Option<String>, PromptError> {
    if item_type != ItemType::SystemArchitecture {
        return Ok(None);
    }

    if let Some(platform) = prefilled {
        return Ok(Some(platform.clone()));
    }

    let mut prompt = Text::new("Target platform (optional):")
        .with_help_message("e.g., AWS, STM32, Linux (press Enter to skip)");

    if let Some(def) = default {
        prompt = prompt.with_default(def);
    }

    let platform = prompt.prompt()?;
    let trimmed = platform.trim();
    if trimmed.is_empty() {
        Ok(None)
    } else {
        Ok(Some(trimmed.to_string()))
    }
}

/// Prompts for ADR deciders (for architecture_decision_record).
///
/// Asks for each decider one at a time until an empty answer is given.
/// If `prefilled` is not empty, returns those values without prompting.
/// If `default` is not empty, pre-populates the list and allows adding more.
pub fn prompt_deciders(
    item_type: ItemType,
    prefilled: &[String],
    default: &[String],
) -> Result<Vec<String>, PromptError> {
    if item_type != ItemType::ArchitectureDecisionRecord {
        return Ok(Vec::new());
    }

    if !prefilled.is_empty() {
        return Ok(prefilled.to_vec());
    }

    let mut deciders: Vec<String> = default.to_vec();

    loop {
        let prompt_msg = if deciders.is_empty() {
            "Decider name (press Enter to skip):"
        } else {
            "Additional decider (press Enter to finish):"
        };

        let input = Text::new(prompt_msg)
            .with_help_message("Person responsible for this decision")
            .prompt()?;

        let trimmed = input.trim();
        if trimmed.is_empty() {
            break;
        }

        deciders.push(trimmed.to_string());
    }

    Ok(deciders)
}

/// Displays a summary and prompts for confirmation (FR-048).
fn prompt_confirmation(input: &InteractiveInput) -> Result<bool, PromptError> {
    let summary = build_confirmation_summary(input);
    println!("{}", summary);

    let confirmed = Confirm::new("Create document?")
        .with_default(true)
        .prompt()?;

    Ok(confirmed)
}

/// Builds the confirmation summary string.
fn build_confirmation_summary(input: &InteractiveInput) -> String {
    let description = input
        .description
        .as_ref()
        .map(|d| format!("\n  Description: {}", d))
        .unwrap_or_default();

    let refines = if input.traceability.refines.is_empty() {
        String::new()
    } else {
        format!("\n  Refines: {}", input.traceability.refines.join(", "))
    };

    let derives_from = if input.traceability.derives_from.is_empty() {
        String::new()
    } else {
        format!(
            "\n  Derives from: {}",
            input.traceability.derives_from.join(", ")
        )
    };

    let satisfies = if input.traceability.satisfies.is_empty() {
        String::new()
    } else {
        format!("\n  Satisfies: {}", input.traceability.satisfies.join(", "))
    };

    let depends_on = if input.traceability.depends_on.is_empty() {
        String::new()
    } else {
        format!(
            "\n  Depends on: {}",
            input.traceability.depends_on.join(", ")
        )
    };

    let justifies = if input.traceability.justifies.is_empty() {
        String::new()
    } else {
        format!("\n  Justifies: {}", input.traceability.justifies.join(", "))
    };

    let type_specific_info = match &input.type_specific {
        TypeSpecificInput::None => String::new(),
        TypeSpecificInput::Requirement { specification } => specification
            .as_ref()
            .map(|s| format!("\n  Specification: {}", s))
            .unwrap_or_default(),
        TypeSpecificInput::SystemArchitecture { platform } => platform
            .as_ref()
            .map(|p| format!("\n  Platform: {}", p))
            .unwrap_or_default(),
        TypeSpecificInput::Adr { deciders } => {
            if deciders.is_empty() {
                String::new()
            } else {
                format!("\n  Deciders: {}", deciders.join(", "))
            }
        }
    };

    format!(
        "\n\
         \x20 Summary:\n\
         \x20 ────────────────────────────────────\n\
         \x20 Type: {}\n\
         \x20 ID:   {}\n\
         \x20 Name: {}\n\
         \x20 File: {}{}{}{}{}{}{}{}\n",
        input.item_type.display_name(),
        input.id,
        input.name,
        input.file.display(),
        description,
        refines,
        derives_from,
        satisfies,
        depends_on,
        justifies,
        type_specific_info,
    )
}

/// Prompts for file path if not provided.
fn prompt_file(prefilled: Option<&PathBuf>) -> Result<PathBuf, PromptError> {
    if let Some(file) = prefilled {
        return Ok(file.clone());
    }

    let file = Text::new("File path:")
        .with_help_message("Path for the new document (e.g., docs/SOL-001.md)")
        .with_validator(|input: &str| {
            let trimmed = input.trim();
            if trimmed.is_empty() {
                Ok(Validation::Invalid("File path is required".into()))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt()?;

    Ok(PathBuf::from(file.trim()))
}

/// Runs the interactive session, orchestrating all prompts (FR-040).
pub fn run_interactive_session(
    session: &mut InteractiveSession<'_>,
) -> Result<InteractiveInput, PromptError> {
    require_tty()?;
    ensure_graph_loaded(session);

    let item_type = prompt_item_type(session.prefilled.item_type)?;
    if let Some(graph) = &session.graph {
        graph.check_parent_exists(item_type)?;
    }

    let input = collect_item_input(session, item_type)?;
    confirm_creation(&input)?;

    Ok(input)
}

/// Ensures the knowledge graph is loaded for traceability suggestions.
fn ensure_graph_loaded(session: &mut InteractiveSession<'_>) {
    if session.graph.is_some() || session.repositories.is_empty() {
        return;
    }

    match build_graph_from_repositories(session.repositories) {
        Ok(graph) => {
            session.graph = Some(graph);
        }
        Err(msg) => {
            print_error(session.output, msg);
        }
    }
}

/// Builds the knowledge graph from repositories.
fn build_graph_from_repositories(repositories: &[PathBuf]) -> Result<KnowledgeGraph, &'static str> {
    let items = parse_repositories(repositories).map_err(|e| {
        tracing::warn!("Parse error: {}", e);
        "Failed to parse repositories"
    })?;

    KnowledgeGraphBuilder::new()
        .add_items(items)
        .build()
        .map_err(|e| {
            tracing::warn!("Graph build error: {}", e);
            "Failed to build graph"
        })
}

/// Collects all item input through prompts.
fn collect_item_input(
    session: &InteractiveSession<'_>,
    item_type: ItemType,
) -> Result<InteractiveInput, PromptError> {
    let name = prompt_name(session.prefilled.name.as_ref(), None)?;
    let id = prompt_identifier(
        item_type,
        session.graph.as_ref(),
        session.prefilled.id.as_ref(),
    )?;
    let description = prompt_description(session.prefilled.description.as_ref(), None)?;
    let traceability = prompt_traceability(
        item_type,
        session.graph.as_ref(),
        &session.prefilled,
        None,
        Some(&id),
    )?;
    let type_specific = collect_type_specific_input(session, item_type)?;
    let file = prompt_file(session.prefilled.file.as_ref())?;

    Ok(InteractiveInput {
        file,
        item_type,
        id,
        name,
        description,
        traceability,
        type_specific,
    })
}

/// Collects type-specific fields (specification, platform).
fn collect_type_specific_input(
    session: &InteractiveSession<'_>,
    item_type: ItemType,
) -> Result<TypeSpecificInput, PromptError> {
    match item_type {
        ItemType::SystemRequirement
        | ItemType::SoftwareRequirement
        | ItemType::HardwareRequirement => {
            let specification =
                prompt_specification(item_type, session.prefilled.specification.as_ref(), None)?;
            Ok(TypeSpecificInput::Requirement { specification })
        }
        ItemType::SystemArchitecture => {
            let platform = prompt_platform(item_type, session.prefilled.platform.as_ref(), None)?;
            Ok(TypeSpecificInput::SystemArchitecture { platform })
        }
        ItemType::ArchitectureDecisionRecord => {
            let deciders = prompt_deciders(item_type, &session.prefilled.deciders, &[])?;
            Ok(TypeSpecificInput::Adr { deciders })
        }
        _ => Ok(TypeSpecificInput::None),
    }
}

/// Confirms the creation with the user (FR-048).
fn confirm_creation(input: &InteractiveInput) -> Result<(), PromptError> {
    if prompt_confirmation(input)? {
        Ok(())
    } else {
        Err(PromptError::Cancelled)
    }
}

/// Handles the result of an interactive session, including Ctrl+C (FR-049).
pub fn handle_interactive_result(
    result: Result<InteractiveInput, PromptError>,
    config: &OutputConfig,
) -> Result<Option<InteractiveInput>, PromptError> {
    match result {
        Ok(input) => Ok(Some(input)),
        Err(PromptError::Cancelled) => {
            println!();
            println!("Cancelled. No file was created.");
            Ok(None)
        }
        Err(PromptError::InquireError(InquireError::OperationInterrupted)) => {
            println!();
            println!("Cancelled. No file was created.");
            Ok(None)
        }
        Err(PromptError::NonInteractiveTerminal) => {
            print_error(
                config,
                "Interactive mode requires a terminal. Use --type <TYPE> to specify the item type.",
            );
            Err(PromptError::NonInteractiveTerminal)
        }
        Err(PromptError::MissingParent(err)) => {
            print_error(config, &err.to_string());
            Err(PromptError::MissingParent(err))
        }
        Err(e) => Err(e),
    }
}

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

    #[test]
    fn test_suggest_next_id_no_graph() {
        let id = ItemType::Solution.suggest_next_id(None);
        assert!(id.starts_with("SOL-"));
    }

    #[test]
    fn test_id_validator_valid() {
        let validator = IdValidator;
        assert!(matches!(
            validator.validate("SOL-001"),
            Ok(Validation::Valid)
        ));
        assert!(matches!(
            validator.validate("UC_002"),
            Ok(Validation::Valid)
        ));
    }

    #[test]
    fn test_id_validator_invalid() {
        let validator = IdValidator;
        assert!(matches!(validator.validate(""), Ok(Validation::Invalid(_))));
        assert!(matches!(
            validator.validate("SOL 001"),
            Ok(Validation::Invalid(_))
        ));
    }

    #[test]
    fn test_name_validator_valid() {
        let validator = NameValidator;
        assert!(matches!(
            validator.validate("Test Name"),
            Ok(Validation::Valid)
        ));
    }

    #[test]
    fn test_name_validator_empty() {
        let validator = NameValidator;
        assert!(matches!(validator.validate(""), Ok(Validation::Invalid(_))));
        assert!(matches!(
            validator.validate("   "),
            Ok(Validation::Invalid(_))
        ));
    }

    #[test]
    fn test_required_parent_type() {
        assert_eq!(ItemType::Solution.required_parent_type(), None);
        assert_eq!(
            ItemType::UseCase.required_parent_type(),
            Some(ItemType::Solution)
        );
        assert_eq!(
            ItemType::Scenario.required_parent_type(),
            Some(ItemType::UseCase)
        );
    }

    #[test]
    fn test_traceability_field() {
        assert_eq!(ItemType::Solution.traceability_field(), None);
        assert_eq!(
            ItemType::UseCase.traceability_field(),
            Some(FieldName::Refines)
        );
        assert_eq!(
            ItemType::SystemRequirement.traceability_field(),
            Some(FieldName::DerivesFrom)
        );
        assert_eq!(
            ItemType::SystemArchitecture.traceability_field(),
            Some(FieldName::Satisfies)
        );
    }
}