ryo-analysis 0.1.0

Code graph and discovery engine for the RYO project
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
//! SpecFlowGraph V2 - Data-Oriented Design implementation
//!
//! High-performance domain semantics tracking using:
//! - SoA (Structure of Arrays) for cache efficiency
//! - Inverted indices for O(1) group/spec lookups
//! - Partial String-free design (SpecAlias is String-free, Group keeps name)
//!
//! # Architecture
//!
//! ```text
//! SpecFlowGraphV2
//! ├── Data Storage (SoA)
//! │   ├── groups: Vec<GroupData>           // String required (domain labels)
//! │   ├── spec_aliases: Vec<SpecAliasData> // String-free!
//! │   ├── constraints: Vec<ConstraintData>
//! │   └── intents: Vec<IntentData>
//!//! ├── Edge Relations (Side Tables)
//! │   ├── spec_to_group: Vec<u32>          // BelongsTo (1:1)
//! │   ├── spec_dependencies: HashMap       // DependsOn (N:N)
//! │   └── spec_to_constraints: HashMap     // ConstrainedBy (1:N)
//!//! └── Lookup Tables (Inverted Index)
//!     ├── symbol_to_spec: HashMap<SymbolId, u32>
//!     └── group_to_specs: Vec<SmallVec<[u32; 8]>>
//! ```

use crate::symbol::SymbolId;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::collections::HashMap;

// Re-use shared types
pub use super::specflow_common::{ConstraintKind, IntentKind, SpecSource};

// ============================================================================
// Node ID Types
// ============================================================================

/// Unified node ID with kind encoded in top 2 bits.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[repr(transparent)]
pub struct SpecNodeId(u32);

impl SpecNodeId {
    const KIND_SHIFT: u32 = 30;
    const KIND_MASK: u32 = 0xC000_0000;
    const INDEX_MASK: u32 = 0x3FFF_FFFF;

    const KIND_GROUP: u32 = 0;
    const KIND_SPEC: u32 = 1;
    const KIND_CONSTRAINT: u32 = 2;
    const KIND_INTENT: u32 = 3;

    /// Create a group node ID.
    #[inline]
    pub const fn group(idx: u32) -> Self {
        Self((Self::KIND_GROUP << Self::KIND_SHIFT) | idx)
    }

    /// Create a spec alias node ID.
    #[inline]
    pub const fn spec(idx: u32) -> Self {
        Self((Self::KIND_SPEC << Self::KIND_SHIFT) | idx)
    }

    /// Create a constraint node ID.
    #[inline]
    pub const fn constraint(idx: u32) -> Self {
        Self((Self::KIND_CONSTRAINT << Self::KIND_SHIFT) | idx)
    }

    /// Create an intent node ID.
    #[inline]
    pub const fn intent(idx: u32) -> Self {
        Self((Self::KIND_INTENT << Self::KIND_SHIFT) | idx)
    }

    /// Get the node kind.
    #[inline]
    pub const fn kind(self) -> SpecNodeKind {
        match (self.0 & Self::KIND_MASK) >> Self::KIND_SHIFT {
            Self::KIND_GROUP => SpecNodeKind::Group,
            Self::KIND_SPEC => SpecNodeKind::SpecAlias,
            Self::KIND_CONSTRAINT => SpecNodeKind::Constraint,
            Self::KIND_INTENT => SpecNodeKind::Intent,
            _ => unreachable!(),
        }
    }

    /// Get the raw index within the kind's array.
    #[inline]
    pub const fn index(self) -> u32 {
        self.0 & Self::INDEX_MASK
    }

    /// Get raw u32 value.
    #[inline]
    pub const fn as_u32(self) -> u32 {
        self.0
    }
}

/// Node kind discriminant.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum SpecNodeKind {
    /// Semantic-group node (`@spec:group(...)`).
    Group,
    /// Spec alias node introduced via a type alias or `@spec:` directive.
    SpecAlias,
    /// Constraint node (range / pattern / invariant / depends-on / custom).
    Constraint,
    /// Intent node carrying design/performance/security/business intent.
    Intent,
}

// ============================================================================
// Data Structures (SoA Components)
// ============================================================================

/// Group node data.
/// String is required for domain semantics labels.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GroupData {
    /// Group name (e.g., "ConfigGroup")
    pub name: String,
    /// Optional description
    pub description: Option<String>,
}

/// SpecAlias node data with pre-resolved names for DoD.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SpecAliasData {
    /// SymbolId of the type alias
    pub alias_id: SymbolId,
    /// Pre-resolved alias name (for DoD - no registry lookup needed)
    pub alias_name: String,
    /// Resolved wrapped type SymbolId
    pub wrapped_type_id: Option<SymbolId>,
    /// Pre-resolved wrapped type name (for DoD - no registry lookup needed)
    pub wrapped_type_name: Option<String>,
    /// Index into groups array
    pub group_idx: u32,
    /// Source of this spec
    pub source: SpecSource,
}

/// Constraint node data.
/// String is required for domain constraint expressions.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConstraintData {
    /// Constraint kind (contains String for patterns/invariants)
    pub kind: ConstraintKind,
}

/// Intent node data.
/// String is required for human-readable descriptions.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct IntentData {
    /// Intent description
    pub description: String,
    /// Intent kind
    pub kind: IntentKind,
}

// ============================================================================
// Lookup Table
// ============================================================================

/// Inverted indices for O(1) lookups.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SpecLookupTable {
    /// SymbolId → SpecAlias index (for specs with resolved alias_id)
    pub symbol_to_spec: HashMap<SymbolId, u32>,

    /// Group name → Group index
    pub name_to_group: HashMap<String, u32>,

    /// Group index → SpecAlias indices (inverted BelongsTo)
    pub group_to_specs: Vec<SmallVec<[u32; 8]>>,
}

// ============================================================================
// SpecFlowGraphV2 - Main Structure
// ============================================================================

/// SpecFlowGraph V2 - SoA + Side Tables design.
///
/// NOTE: Deserialize is NOT derived because SpecFlowGraphV2 contains
/// HashMap<SymbolId, ...>. SymbolId is process-specific.
/// Serialize is kept for debugging/inspection.
#[derive(Clone, Debug, Default, Serialize)]
pub struct SpecFlowGraphV2 {
    // =========================================================================
    // Data Storage (SoA)
    // =========================================================================
    /// Group nodes
    groups: Vec<GroupData>,

    /// SpecAlias nodes (String-free!)
    spec_aliases: Vec<SpecAliasData>,

    /// Constraint nodes
    constraints: Vec<ConstraintData>,

    /// Intent nodes
    intents: Vec<IntentData>,

    // =========================================================================
    // Edge Relations (Side Tables)
    // =========================================================================
    /// SpecAlias → SpecAlias dependencies (DependsOn)
    spec_dependencies: HashMap<u32, SmallVec<[u32; 2]>>,

    /// SpecAlias → Constraint indices (ConstrainedBy)
    spec_to_constraints: HashMap<u32, SmallVec<[u32; 2]>>,

    /// SpecAlias → Intent indices (HasIntent)
    spec_to_intents: HashMap<u32, SmallVec<[u32; 2]>>,

    /// SpecAlias → SpecAlias related (RelatedTo, bidirectional)
    spec_related: HashMap<u32, SmallVec<[u32; 2]>>,

    // =========================================================================
    // Lookup Tables
    // =========================================================================
    lookup: SpecLookupTable,
}

impl SpecFlowGraphV2 {
    /// Create a new empty graph.
    pub fn new() -> Self {
        Self::default()
    }

    // =========================================================================
    // Node Addition
    // =========================================================================

    /// Add a group, returning its ID. Reuses existing if name matches.
    pub fn add_group(
        &mut self,
        name: impl Into<String>,
        description: Option<String>,
    ) -> SpecNodeId {
        let name = name.into();

        // Check if exists
        if let Some(&idx) = self.lookup.name_to_group.get(&name) {
            // Update description if provided
            if description.is_some() {
                self.groups[idx as usize].description = description;
            }
            return SpecNodeId::group(idx);
        }

        // Add new
        let idx = self.groups.len() as u32;
        self.groups.push(GroupData {
            name: name.clone(),
            description,
        });
        self.lookup.name_to_group.insert(name, idx);
        self.lookup.group_to_specs.push(SmallVec::new());

        SpecNodeId::group(idx)
    }

    /// Add a spec alias.
    pub fn add_spec_alias(
        &mut self,
        alias_id: SymbolId,
        alias_name: String,
        group_name: &str,
        wrapped_type_id: Option<SymbolId>,
        wrapped_type_name: Option<String>,
        source: SpecSource,
    ) -> SpecNodeId {
        // Ensure group exists
        let group_node = self.add_group(group_name, None);
        let group_idx = group_node.index();

        // Add spec
        let spec_idx = self.spec_aliases.len() as u32;
        self.spec_aliases.push(SpecAliasData {
            alias_id,
            alias_name,
            wrapped_type_id,
            wrapped_type_name,
            group_idx,
            source,
        });

        // Update lookup tables
        self.lookup.symbol_to_spec.insert(alias_id, spec_idx);
        self.lookup.group_to_specs[group_idx as usize].push(spec_idx);

        SpecNodeId::spec(spec_idx)
    }

    /// Add a constraint.
    pub fn add_constraint(&mut self, kind: ConstraintKind) -> SpecNodeId {
        let idx = self.constraints.len() as u32;
        self.constraints.push(ConstraintData { kind });
        SpecNodeId::constraint(idx)
    }

    /// Add an intent.
    pub fn add_intent(&mut self, description: impl Into<String>, kind: IntentKind) -> SpecNodeId {
        let idx = self.intents.len() as u32;
        self.intents.push(IntentData {
            description: description.into(),
            kind,
        });
        SpecNodeId::intent(idx)
    }

    // =========================================================================
    // Edge Addition
    // =========================================================================

    /// Add dependency: from depends on to.
    pub fn add_dependency(&mut self, from: SpecNodeId, to: SpecNodeId) {
        debug_assert!(from.kind() == SpecNodeKind::SpecAlias);
        debug_assert!(to.kind() == SpecNodeKind::SpecAlias);
        self.spec_dependencies
            .entry(from.index())
            .or_default()
            .push(to.index());
    }

    /// Add related edge (bidirectional).
    pub fn add_related(&mut self, a: SpecNodeId, b: SpecNodeId) {
        debug_assert!(a.kind() == SpecNodeKind::SpecAlias);
        debug_assert!(b.kind() == SpecNodeKind::SpecAlias);
        self.spec_related
            .entry(a.index())
            .or_default()
            .push(b.index());
        self.spec_related
            .entry(b.index())
            .or_default()
            .push(a.index());
    }

    /// Link constraint to spec.
    pub fn link_constraint(&mut self, spec: SpecNodeId, constraint: SpecNodeId) {
        debug_assert!(spec.kind() == SpecNodeKind::SpecAlias);
        debug_assert!(constraint.kind() == SpecNodeKind::Constraint);
        self.spec_to_constraints
            .entry(spec.index())
            .or_default()
            .push(constraint.index());
    }

    /// Link intent to spec.
    pub fn link_intent(&mut self, spec: SpecNodeId, intent: SpecNodeId) {
        debug_assert!(spec.kind() == SpecNodeKind::SpecAlias);
        debug_assert!(intent.kind() == SpecNodeKind::Intent);
        self.spec_to_intents
            .entry(spec.index())
            .or_default()
            .push(intent.index());
    }

    // =========================================================================
    // Query Methods
    // =========================================================================

    /// Get group by name. O(1)
    pub fn group_by_name(&self, name: &str) -> Option<SpecNodeId> {
        self.lookup
            .name_to_group
            .get(name)
            .map(|&idx| SpecNodeId::group(idx))
    }

    /// Get spec by SymbolId. O(1)
    pub fn spec_by_symbol(&self, id: SymbolId) -> Option<SpecNodeId> {
        self.lookup
            .symbol_to_spec
            .get(&id)
            .map(|&idx| SpecNodeId::spec(idx))
    }

    /// Get all specs in a group. O(1)
    pub fn specs_in_group(&self, group: SpecNodeId) -> impl Iterator<Item = SpecNodeId> + '_ {
        debug_assert!(group.kind() == SpecNodeKind::Group);
        self.lookup
            .group_to_specs
            .get(group.index() as usize)
            .into_iter()
            .flat_map(|v| v.iter().map(|&idx| SpecNodeId::spec(idx)))
    }

    /// Get dependencies of a spec. O(1)
    pub fn dependencies(&self, spec: SpecNodeId) -> impl Iterator<Item = SpecNodeId> + '_ {
        debug_assert!(spec.kind() == SpecNodeKind::SpecAlias);
        self.spec_dependencies
            .get(&spec.index())
            .into_iter()
            .flat_map(|v| v.iter().map(|&idx| SpecNodeId::spec(idx)))
    }

    /// Get constraints of a spec. O(1)
    pub fn constraints(&self, spec: SpecNodeId) -> impl Iterator<Item = SpecNodeId> + '_ {
        debug_assert!(spec.kind() == SpecNodeKind::SpecAlias);
        self.spec_to_constraints
            .get(&spec.index())
            .into_iter()
            .flat_map(|v| v.iter().map(|&idx| SpecNodeId::constraint(idx)))
    }

    // =========================================================================
    // Data Access
    // =========================================================================

    /// Get group data.
    pub fn get_group(&self, id: SpecNodeId) -> Option<&GroupData> {
        debug_assert!(id.kind() == SpecNodeKind::Group);
        self.groups.get(id.index() as usize)
    }

    /// Get spec alias data.
    pub fn get_spec_alias(&self, id: SpecNodeId) -> Option<&SpecAliasData> {
        debug_assert!(id.kind() == SpecNodeKind::SpecAlias);
        self.spec_aliases.get(id.index() as usize)
    }

    /// Get constraint data.
    pub fn get_constraint(&self, id: SpecNodeId) -> Option<&ConstraintData> {
        debug_assert!(id.kind() == SpecNodeKind::Constraint);
        self.constraints.get(id.index() as usize)
    }

    /// Get intent data.
    pub fn get_intent(&self, id: SpecNodeId) -> Option<&IntentData> {
        debug_assert!(id.kind() == SpecNodeKind::Intent);
        self.intents.get(id.index() as usize)
    }

    // =========================================================================
    // Iteration
    // =========================================================================

    /// Iterate all groups.
    pub fn all_groups(&self) -> impl Iterator<Item = (SpecNodeId, &GroupData)> {
        self.groups
            .iter()
            .enumerate()
            .map(|(i, data)| (SpecNodeId::group(i as u32), data))
    }

    /// Iterate all spec aliases.
    pub fn all_spec_aliases(&self) -> impl Iterator<Item = (SpecNodeId, &SpecAliasData)> {
        self.spec_aliases
            .iter()
            .enumerate()
            .map(|(i, data)| (SpecNodeId::spec(i as u32), data))
    }

    // =========================================================================
    // Statistics
    // =========================================================================

    /// Number of groups.
    pub fn group_count(&self) -> usize {
        self.groups.len()
    }

    /// Number of spec aliases.
    pub fn spec_count(&self) -> usize {
        self.spec_aliases.len()
    }

    /// Number of constraints.
    pub fn constraint_count(&self) -> usize {
        self.constraints.len()
    }

    /// Total node count.
    pub fn node_count(&self) -> usize {
        self.groups.len() + self.spec_aliases.len() + self.constraints.len() + self.intents.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.node_count() == 0
    }

    // =========================================================================
    // CLI Compatibility Methods
    // =========================================================================

    /// Get all group names. O(N groups)
    pub fn group_names(&self) -> impl Iterator<Item = &str> {
        self.groups.iter().map(|g| g.name.as_str())
    }

    /// Get specs in a group by name. O(1)
    pub fn specs_in_group_by_name(&self, name: &str) -> impl Iterator<Item = SpecNodeId> + '_ {
        self.lookup
            .name_to_group
            .get(name)
            .and_then(|&idx| self.lookup.group_to_specs.get(idx as usize))
            .into_iter()
            .flat_map(|v| v.iter().map(|&idx| SpecNodeId::spec(idx)))
    }

    /// Get dependents of a spec (reverse dependencies). O(N specs)
    pub fn dependents(&self, spec: SpecNodeId) -> impl Iterator<Item = SpecNodeId> + '_ {
        debug_assert!(spec.kind() == SpecNodeKind::SpecAlias);
        let target_idx = spec.index();
        self.spec_dependencies
            .iter()
            .filter(move |(_, deps)| deps.contains(&target_idx))
            .map(|(&from_idx, _)| SpecNodeId::spec(from_idx))
    }

    /// Total edge count.
    pub fn edge_count(&self) -> usize {
        let dep_edges: usize = self.spec_dependencies.values().map(|v| v.len()).sum();
        let constraint_edges: usize = self.spec_to_constraints.values().map(|v| v.len()).sum();
        let intent_edges: usize = self.spec_to_intents.values().map(|v| v.len()).sum();
        let related_edges: usize = self.spec_related.values().map(|v| v.len()).sum();
        let belongs_to_edges = self.spec_aliases.len(); // Each spec belongs to exactly one group

        dep_edges + constraint_edges + intent_edges + related_edges + belongs_to_edges
    }

    /// Get related specs (bidirectional). O(1)
    pub fn related(&self, spec: SpecNodeId) -> impl Iterator<Item = SpecNodeId> + '_ {
        debug_assert!(spec.kind() == SpecNodeKind::SpecAlias);
        self.spec_related
            .get(&spec.index())
            .into_iter()
            .flat_map(|v| v.iter().map(|&idx| SpecNodeId::spec(idx)))
    }

    /// Get intents of a spec. O(1)
    pub fn intents(&self, spec: SpecNodeId) -> impl Iterator<Item = SpecNodeId> + '_ {
        debug_assert!(spec.kind() == SpecNodeKind::SpecAlias);
        self.spec_to_intents
            .get(&spec.index())
            .into_iter()
            .flat_map(|v| v.iter().map(|&idx| SpecNodeId::intent(idx)))
    }

    // =========================================================================
    // Name Resolution (DoD - pre-resolved, no registry needed)
    // =========================================================================

    /// Get spec alias name (pre-resolved during build).
    pub fn spec_name(&self, id: SpecNodeId) -> Option<&str> {
        self.get_spec_alias(id).map(|data| data.alias_name.as_str())
    }

    /// Get wrapped type name (pre-resolved during build).
    pub fn wrapped_type_name(&self, id: SpecNodeId) -> Option<&str> {
        self.get_spec_alias(id)
            .and_then(|data| data.wrapped_type_name.as_deref())
    }

    /// Get group name for a spec alias.
    pub fn spec_group_name(&self, id: SpecNodeId) -> Option<&str> {
        self.get_spec_alias(id)
            .and_then(|data| self.groups.get(data.group_idx as usize))
            .map(|g| g.name.as_str())
    }

    /// Find spec by name (DoD - uses pre-resolved names). O(N specs)
    pub fn spec_by_name(&self, name: &str) -> Option<SpecNodeId> {
        for (id, data) in self.all_spec_aliases() {
            if data.alias_name == name {
                return Some(id);
            }
        }
        None
    }
}

// ============================================================================
// SpecFlowBuilderV2 - Build from TypeAliasRegistry
// ============================================================================

use super::type_alias_registry::TypeAliasRegistry;
use crate::symbol::SymbolRegistry;

/// Builds SpecFlowGraphV2 from TypeAliasRegistry.
///
/// # Example
///
/// ```ignore
/// let builder = SpecFlowBuilderV2::new(&alias_registry, &symbol_registry);
/// let spec_graph = builder.build();
/// ```
pub struct SpecFlowBuilderV2<'a> {
    alias_registry: &'a TypeAliasRegistry,
    symbol_registry: &'a SymbolRegistry,
}

impl<'a> SpecFlowBuilderV2<'a> {
    /// Create a new builder.
    pub fn new(alias_registry: &'a TypeAliasRegistry, symbol_registry: &'a SymbolRegistry) -> Self {
        Self {
            alias_registry,
            symbol_registry,
        }
    }

    /// Build SpecFlowGraphV2 from TypeAliasRegistry.
    pub fn build(self) -> SpecFlowGraphV2 {
        let mut graph = SpecFlowGraphV2::new();

        // Extract Spec<G, T> patterns from TypeAliasRegistry
        for spec_info in self.alias_registry.spec_aliases() {
            // Pre-resolve names during build (DoD)
            let alias_name = self
                .symbol_registry
                .resolve(spec_info.entry.alias_id)
                .map(|path| path.name().to_string())
                .unwrap_or_default();

            let wrapped_type_name = spec_info.entry.resolved.and_then(|wrapped_id| {
                self.symbol_registry
                    .resolve(wrapped_id)
                    .map(|path| path.to_string())
            });

            graph.add_spec_alias(
                spec_info.entry.alias_id,
                alias_name,
                &spec_info.group_name,
                spec_info.entry.resolved,
                wrapped_type_name,
                SpecSource::TypeAlias,
            );
        }

        graph
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::symbol::{SymbolPath, SymbolRegistry};
    use crate::SymbolKind;

    fn create_test_symbol(registry: &mut SymbolRegistry, name: &str) -> SymbolId {
        registry
            .register(SymbolPath::parse(name).unwrap(), SymbolKind::TypeAlias)
            .unwrap()
    }

    #[test]
    fn test_empty_graph() {
        let graph = SpecFlowGraphV2::new();
        assert!(graph.is_empty());
        assert_eq!(graph.node_count(), 0);
    }

    #[test]
    fn test_add_group() {
        let mut graph = SpecFlowGraphV2::new();
        let g1 = graph.add_group("ConfigGroup", Some("Config types".to_string()));
        let g2 = graph.add_group("ConfigGroup", None); // Should return same

        assert_eq!(g1, g2);
        assert_eq!(graph.group_count(), 1);

        let data = graph.get_group(g1).unwrap();
        assert_eq!(data.name, "ConfigGroup");
        assert_eq!(data.description, Some("Config types".to_string()));
    }

    #[test]
    fn test_add_spec_alias() {
        let mut symbol_registry = SymbolRegistry::new();
        let alias_id = create_test_symbol(&mut symbol_registry, "test::DbConfig");
        let wrapped_id = create_test_symbol(&mut symbol_registry, "test::DatabaseConfig");

        let mut graph = SpecFlowGraphV2::new();
        let spec = graph.add_spec_alias(
            alias_id,
            "DbConfig".to_string(),
            "ConfigGroup",
            Some(wrapped_id),
            Some("test::DatabaseConfig".to_string()),
            SpecSource::TypeAlias,
        );

        assert_eq!(graph.spec_count(), 1);
        assert_eq!(graph.group_count(), 1); // Auto-created

        // Check spec data
        let data = graph.get_spec_alias(spec).unwrap();
        assert_eq!(data.alias_id, alias_id);
        assert_eq!(data.wrapped_type_id, Some(wrapped_id));

        // Check lookup
        assert_eq!(graph.spec_by_symbol(alias_id), Some(spec));

        // Check group membership
        let group = graph.group_by_name("ConfigGroup").unwrap();
        let specs: Vec<_> = graph.specs_in_group(group).collect();
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0], spec);
    }

    #[test]
    fn test_dependencies() {
        let mut symbol_registry = SymbolRegistry::new();
        let db_id = create_test_symbol(&mut symbol_registry, "test::DbConfig");
        let cache_id = create_test_symbol(&mut symbol_registry, "test::CacheConfig");

        let mut graph = SpecFlowGraphV2::new();
        let db_spec = graph.add_spec_alias(
            db_id,
            "DbConfig".to_string(),
            "ConfigGroup",
            None,
            None,
            SpecSource::TypeAlias,
        );
        let cache_spec = graph.add_spec_alias(
            cache_id,
            "CacheConfig".to_string(),
            "ConfigGroup",
            None,
            None,
            SpecSource::TypeAlias,
        );

        // CacheConfig depends on DbConfig
        graph.add_dependency(cache_spec, db_spec);

        let deps: Vec<_> = graph.dependencies(cache_spec).collect();
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0], db_spec);
    }

    #[test]
    fn test_constraints() {
        let mut symbol_registry = SymbolRegistry::new();
        let id = create_test_symbol(&mut symbol_registry, "test::UserId");

        let mut graph = SpecFlowGraphV2::new();
        let spec = graph.add_spec_alias(
            id,
            "UserId".to_string(),
            "DomainGroup",
            None,
            None,
            SpecSource::TypeAlias,
        );
        let constraint = graph.add_constraint(ConstraintKind::Range {
            min: Some(1),
            max: None,
        });

        graph.link_constraint(spec, constraint);

        let constraints: Vec<_> = graph.constraints(spec).collect();
        assert_eq!(constraints.len(), 1);

        let data = graph.get_constraint(constraints[0]).unwrap();
        assert!(matches!(
            data.kind,
            ConstraintKind::Range {
                min: Some(1),
                max: None
            }
        ));
    }
}