ggen-domain 3.2.0

Domain logic layer for ggen - pure business logic without CLI dependencies
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
//! Registry infrastructure for ggen marketplace
//!
//! This module implements the package registry and cache management system.
//! It provides production-ready infrastructure for:
//! - Loading and querying package indices
//! - LRU cache management for package metadata
//! - Async filesystem operations
//! - Package version resolution

use ggen_utils::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use tokio::fs;
use tracing::{debug, info, instrument, warn};

/// Package metadata in the registry index
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PackageMetadata {
    /// Package name
    pub name: String,

    /// Available versions
    pub versions: Vec<VersionMetadata>,

    /// Package description
    pub description: String,

    /// Package author
    pub author: Option<String>,

    /// Package category
    pub category: Option<String>,

    /// Package tags
    pub tags: Vec<String>,

    /// Repository URL
    pub repository: Option<String>,

    /// License
    pub license: Option<String>,

    /// Homepage URL
    pub homepage: Option<String>,

    /// 8020 Innovation: Whether this package is a critical 20% bundle
    /// Packages marked as 8020 cover 80% of real-world use cases with minimal hand-editing
    #[serde(default)]
    pub is_8020: bool,

    /// 8020 Innovation: Whether this package has passed all Guard8020Coverage checks
    /// Only true if is_8020 is true AND all 6+ validation checks pass
    #[serde(default)]
    pub is_8020_certified: bool,

    /// 8020 Innovation: Dark matter reduction target
    /// Measurable claim about what % of manual work this package eliminates
    /// Example: "Eliminates 70% of observability setup work (from 8 hours to 2.4 hours)"
    #[serde(default)]
    pub dark_matter_reduction_target: Option<String>,

    /// 8020 Innovation: Sector classification for bundle composition
    /// Examples: "observability", "microservice", "paper", "support", "api-gateway"
    /// Allows filtering and discovering sector-specific bundles
    #[serde(default)]
    pub sector: Option<String>,
}

/// Version-specific metadata
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VersionMetadata {
    /// Version string (e.g., "1.0.0")
    pub version: String,

    /// Download URL for this version
    pub download_url: String,

    /// Checksum (SHA256)
    pub checksum: String,

    /// Dependencies
    pub dependencies: Vec<Dependency>,

    /// Published timestamp (RFC3339 format)
    pub published_at: String,

    /// Size in bytes
    pub size_bytes: u64,
}

/// Package dependency specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Dependency {
    /// Dependency package name
    pub name: String,

    /// Version requirement (e.g., "^1.0.0")
    pub version_req: String,

    /// Whether this is an optional dependency
    pub optional: bool,
}

/// Registry index file format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryIndex {
    /// Registry version
    pub version: String,

    /// Last updated timestamp (RFC3339 format)
    pub updated_at: String,

    /// Map of package name to metadata
    pub packages: HashMap<String, PackageMetadata>,
}

impl RegistryIndex {
    /// Create a new empty registry index
    pub fn new() -> Self {
        Self {
            version: "1.0.0".to_string(),
            updated_at: chrono::Utc::now().to_rfc3339(),
            packages: HashMap::new(),
        }
    }

    /// Add or update a package in the index
    /// Add package to index
    ///
    /// FM16 (RPN 320): Duplicate version check - prevents overwriting existing versions silently
    /// If package already exists, versions are merged (no duplicates)
    pub fn add_package(&mut self, metadata: PackageMetadata) {
        if let Some(existing) = self.packages.get_mut(&metadata.name) {
            // Package exists - merge versions, checking for duplicates
            for new_version in &metadata.versions {
                // Check if this version already exists
                if existing
                    .versions
                    .iter()
                    .any(|v| v.version == new_version.version)
                {
                    tracing::warn!(
                        "Package {} version {} already exists in registry - skipping duplicate",
                        metadata.name,
                        new_version.version
                    );
                    continue;
                }
                existing.versions.push(new_version.clone());
            }
            self.updated_at = chrono::Utc::now().to_rfc3339();
        } else {
            // New package - add it
            self.packages.insert(metadata.name.clone(), metadata);
            self.updated_at = chrono::Utc::now().to_rfc3339();
        }
    }

    /// Get package metadata by name
    pub fn get_package(&self, name: &str) -> Option<&PackageMetadata> {
        self.packages.get(name)
    }

    /// List all package names
    pub fn list_packages(&self) -> Vec<String> {
        self.packages.keys().cloned().collect()
    }
}

impl Default for RegistryIndex {
    fn default() -> Self {
        Self::new()
    }
}

/// LRU cache entry
/// NOTE: Currently unused - CacheManager uses HashMap directly
/// FUTURE: May be used if LRU queue implementation changes
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct CacheEntry {
    key: String,
    value: PackageMetadata,
}

/// Cache manager with LRU eviction policy
#[derive(Debug, Clone)]
pub struct CacheManager {
    /// Maximum cache capacity (number of entries)
    capacity: usize,

    /// Cache storage (name -> metadata)
    cache: Arc<RwLock<HashMap<String, PackageMetadata>>>,

    /// LRU queue for eviction (most recent at back)
    lru_queue: Arc<RwLock<VecDeque<String>>>,
}

impl CacheManager {
    /// Create a new cache manager with specified capacity
    pub fn new(capacity: usize) -> Self {
        Self {
            capacity,
            cache: Arc::new(RwLock::new(HashMap::new())),
            lru_queue: Arc::new(RwLock::new(VecDeque::new())),
        }
    }

    /// Get package metadata from cache
    #[instrument(skip(self))]
    pub fn get(&self, name: &str) -> Option<PackageMetadata> {
        let cache = self.cache.read().ok()?;
        let metadata = cache.get(name).cloned();

        if metadata.is_some() {
            // Move to back of LRU queue (most recently used)
            if let Ok(mut queue) = self.lru_queue.write() {
                queue.retain(|k| k != name);
                queue.push_back(name.to_string());
            }
            debug!("Cache hit for package: {}", name);
        } else {
            debug!("Cache miss for package: {}", name);
        }

        metadata
    }

    /// Put package metadata into cache
    #[instrument(skip(self, metadata))]
    pub fn put(&self, name: String, metadata: PackageMetadata) {
        let mut cache = match self.cache.write() {
            Ok(c) => c,
            Err(e) => {
                warn!("Failed to acquire cache write lock: {}", e);
                return;
            }
        };

        let mut queue = match self.lru_queue.write() {
            Ok(q) => q,
            Err(e) => {
                warn!("Failed to acquire LRU queue write lock: {}", e);
                return;
            }
        };

        // Remove from queue if already exists
        queue.retain(|k| k != &name);

        // Evict least recently used if at capacity
        if cache.len() >= self.capacity && !cache.contains_key(&name) {
            if let Some(lru_key) = queue.pop_front() {
                cache.remove(&lru_key);
                debug!("Evicted LRU package: {}", lru_key);
            }
        }

        // Insert into cache and queue
        cache.insert(name.clone(), metadata);
        queue.push_back(name.clone());
        debug!("Cached package: {}", name);
    }

    /// Clear all cache entries
    pub fn clear(&self) {
        if let Ok(mut cache) = self.cache.write() {
            cache.clear();
        }
        if let Ok(mut queue) = self.lru_queue.write() {
            queue.clear();
        }
        debug!("Cache cleared");
    }

    /// Get current cache size
    pub fn size(&self) -> usize {
        self.cache.read().map(|c| c.len()).unwrap_or(0)
    }

    /// Get cache capacity
    pub fn capacity(&self) -> usize {
        self.capacity
    }
}

/// Registry for package discovery and metadata queries
#[derive(Debug, Clone)]
pub struct Registry {
    /// Path to registry index file
    index_path: PathBuf,

    /// In-memory registry index
    index: Arc<RwLock<Option<RegistryIndex>>>,

    /// Cache manager for package metadata
    cache: CacheManager,
}

impl Registry {
    /// Create a new registry with default paths
    pub fn new() -> Result<Self> {
        let home_dir =
            dirs::home_dir().ok_or_else(|| Error::new("Failed to determine home directory"))?;

        let index_path = home_dir.join(".ggen").join("registry").join("index.json");

        Ok(Self {
            index_path,
            index: Arc::new(RwLock::new(None)),
            cache: CacheManager::new(100), // Default cache capacity: 100 packages
        })
    }

    /// Create a registry with custom index path (for testing)
    pub fn with_path(index_path: PathBuf) -> Self {
        Self {
            index_path,
            index: Arc::new(RwLock::new(None)),
            cache: CacheManager::new(100),
        }
    }

    /// Create a registry with custom cache capacity
    pub fn with_cache_capacity(capacity: usize) -> Result<Self> {
        let home_dir =
            dirs::home_dir().ok_or_else(|| Error::new("Failed to determine home directory"))?;

        let index_path = home_dir.join(".ggen").join("registry").join("index.json");

        Ok(Self {
            index_path,
            index: Arc::new(RwLock::new(None)),
            cache: CacheManager::new(capacity),
        })
    }

    /// Load registry index from filesystem with strict validation
    ///
    /// **DETERMINISTIC**: Fails fast on any error to maintain determinism
    /// - Registry file MUST exist
    /// - JSON MUST be valid
    /// - Structure MUST be correct
    /// - Corruption is detected and reported (not silently fixed)
    ///
    /// This ensures predictable behavior and early failure detection.
    #[instrument(skip(self))]
    pub async fn load(&self) -> Result<()> {
        info!("Loading registry index from: {}", self.index_path.display());

        // Create parent directories if they don't exist
        if let Some(parent) = self.index_path.parent() {
            fs::create_dir_all(parent).await?;
        }

        // Load index file - FAIL if missing or corrupted
        let index = if self.index_path.exists() {
            // Try to load and parse the index
            let contents = fs::read_to_string(&self.index_path).await.map_err(|e| {
                Error::new(&format!(
                    "Failed to read registry index from {}: {}. Registry may be corrupted.",
                    self.index_path.display(),
                    e
                ))
            })?;

            serde_json::from_str::<RegistryIndex>(&contents).map_err(|e| {
                Error::new(&format!(
                    "Failed to parse registry index from {} - invalid JSON: {}. Registry is corrupted. Delete {} and re-sync.",
                    self.index_path.display(),
                    e,
                    self.index_path.display()
                ))
            })?
        } else {
            return Err(Error::new(&format!(
                "Registry index not found at {}. Run 'ggen marketplace sync' to download the registry.",
                self.index_path.display()
            )));
        };

        // Store in memory
        let mut guard = self
            .index
            .write()
            .map_err(|e| Error::new(&format!("Failed to acquire index write lock: {}", e)))?;
        *guard = Some(index);

        info!("Registry index loaded successfully");
        Ok(())
    }

    /// Save registry index to filesystem
    #[instrument(skip(self))]
    /// Save registry index with file locking and atomic writes
    ///
    /// FM23 (RPN 450): Concurrent registry writes cause data corruption
    /// FM24 (RPN 400): Registry save fails silently leaving stale in-memory state
    /// - Uses file locking to prevent concurrent writes
    /// - Atomic write (temp + rename) for crash safety
    /// - Verifies write succeeded before returning
    pub async fn save(&self) -> Result<()> {
        // Extract index data before await to avoid holding lock across await
        let index_data = {
            let guard = self
                .index
                .read()
                .map_err(|e| Error::new(&format!("Failed to acquire index read lock: {}", e)))?;

            guard
                .as_ref()
                .ok_or_else(|| Error::new("Registry index not loaded"))?
                .clone()
        };

        // Create parent directories if they don't exist
        if let Some(parent) = self.index_path.parent() {
            fs::create_dir_all(parent).await?;
        }

        // FM23: Create lock file to prevent concurrent writes
        let lock_path = self.index_path.with_extension("index.lock");
        let lock_file = tokio::task::spawn_blocking({
            let lock_path = lock_path.clone();
            move || {
                use std::fs::OpenOptions;
                use std::io::Write;

                // Create lock file with exclusive access
                let mut lock_file = OpenOptions::new()
                    .create(true)
                    .write(true)
                    .truncate(true)
                    .open(&lock_path)
                    .map_err(|e| {
                        Error::new(&format!(
                            "Failed to create registry lock at {}: {}. Another process may be writing.",
                            lock_path.display(),
                            e
                        ))
                    })?;

                // Write PID to lock file for debugging
                let pid = std::process::id();
                writeln!(lock_file, "{}", pid).map_err(|e| {
                    Error::new(&format!("Failed to write to registry lock: {}", e))
                })?;
                lock_file.sync_all().map_err(|e| {
                    Error::new(&format!("Failed to sync registry lock: {}", e))
                })?;

                Ok::<std::fs::File, Error>(lock_file)
            }
        })
        .await
        .map_err(|e| Error::new(&format!("Task join error acquiring lock: {}", e)))??;

        // Lock file is held until this function returns
        let _lock_guard = lock_file;

        // Serialize and write to file atomically
        let contents = serde_json::to_string_pretty(&index_data)?;
        let temp_path = self.index_path.with_extension("index.tmp");

        // Write to temp file first
        fs::write(&temp_path, contents)
            .await
            .map_err(|e| Error::new(&format!("Failed to write registry temp file: {}", e)))?;

        // Atomic rename
        fs::rename(&temp_path, &self.index_path)
            .await
            .map_err(|e| {
                // Cleanup temp file on error
                std::mem::drop(fs::remove_file(&temp_path));
                Error::new(&format!("Failed to atomically update registry: {}", e))
            })?;

        // FM24: Verify write succeeded by reading back
        let verify_content = fs::read_to_string(&self.index_path).await.map_err(|e| {
            Error::new(&format!(
                "Failed to verify registry write: {}. Registry may be corrupted.",
                e
            ))
        })?;

        // Verify JSON is valid
        serde_json::from_str::<RegistryIndex>(&verify_content).map_err(|e| {
            Error::new(&format!(
                "Registry verification failed - saved file is invalid JSON: {}. Registry may be corrupted.",
                e
            ))
        })?;

        info!(
            "Registry index saved and verified at: {}",
            self.index_path.display()
        );
        Ok(())
    }

    /// Get package metadata by name (checks cache first, then index)
    #[instrument(skip(self))]
    pub async fn get_package(&self, name: &str) -> Result<Option<PackageMetadata>> {
        // Check cache first
        if let Some(cached) = self.cache.get(name) {
            return Ok(Some(cached));
        }

        // Load from index if not in cache
        let guard = self
            .index
            .read()
            .map_err(|e| Error::new(&format!("Failed to acquire index read lock: {}", e)))?;

        let index = guard
            .as_ref()
            .ok_or_else(|| Error::new("Registry index not loaded"))?;

        if let Some(metadata) = index.get_package(name) {
            let metadata = metadata.clone();
            // Cache the result
            self.cache.put(name.to_string(), metadata.clone());
            Ok(Some(metadata))
        } else {
            Ok(None)
        }
    }

    /// List all versions for a package
    #[instrument(skip(self))]
    pub async fn list_versions(&self, name: &str) -> Result<Vec<String>> {
        let metadata = self
            .get_package(name)
            .await?
            .ok_or_else(|| Error::new(&format!("Package not found: {}", name)))?;

        Ok(metadata
            .versions
            .iter()
            .map(|v| v.version.clone())
            .collect())
    }

    /// Get specific version metadata
    #[instrument(skip(self))]
    pub async fn get_version(&self, name: &str, version: &str) -> Result<Option<VersionMetadata>> {
        let metadata = self.get_package(name).await?;

        Ok(metadata.and_then(|m| m.versions.iter().find(|v| v.version == version).cloned()))
    }

    /// List all packages in registry
    #[instrument(skip(self))]
    pub async fn list_packages(&self) -> Result<Vec<String>> {
        let guard = self
            .index
            .read()
            .map_err(|e| Error::new(&format!("Failed to acquire index read lock: {}", e)))?;

        let index = guard
            .as_ref()
            .ok_or_else(|| Error::new("Registry index not loaded"))?;

        Ok(index.list_packages())
    }

    /// Add or update a package in the registry
    ///
    /// FM16 (RPN 320): Duplicate version check - prevents overwriting existing versions silently
    /// Returns error if version already exists (unless explicitly allowed)
    #[instrument(skip(self, metadata))]
    pub async fn add_package(&self, metadata: PackageMetadata) -> Result<()> {
        let mut guard = self
            .index
            .write()
            .map_err(|e| Error::new(&format!("Failed to acquire index write lock: {}", e)))?;

        let index = guard
            .as_mut()
            .ok_or_else(|| Error::new("Registry index not loaded"))?;

        // FM16: Check for duplicate versions before adding
        if let Some(existing) = index.get_package(&metadata.name) {
            for new_version in &metadata.versions {
                if existing
                    .versions
                    .iter()
                    .any(|v| v.version == new_version.version)
                {
                    return Err(Error::new(&format!(
                        "❌ Package {} version {} already exists in registry. Cannot add duplicate version.",
                        metadata.name, new_version.version
                    )));
                }
            }
        }

        let name = metadata.name.clone();
        index.add_package(metadata.clone());

        // Update cache
        self.cache.put(name.clone(), metadata);

        info!("Added package to registry: {}", name);
        Ok(())
    }

    /// Get the cache manager
    pub fn cache(&self) -> &CacheManager {
        &self.cache
    }

    /// Get the index path
    pub fn index_path(&self) -> &Path {
        &self.index_path
    }

    /// Validate registry index integrity with strict checks
    ///
    /// **DETERMINISTIC**: Fails fast if registry is invalid
    ///
    /// Checks for:
    /// - Registry is loaded
    /// - Packages array exists and is not empty
    /// - All package metadata is valid (name, versions, download URLs, checksums)
    /// - No invalid state
    ///
    /// Returns error on ANY validation failure - no silent degradation
    pub async fn validate(&self) -> Result<()> {
        let guard = self
            .index
            .read()
            .map_err(|e| Error::new(&format!("Failed to acquire index read lock: {}", e)))?;

        let index = guard
            .as_ref()
            .ok_or_else(|| Error::new("Registry index not loaded"))?;

        // STRICT: Empty registry is an error, not just a warning
        if index.packages.is_empty() {
            return Err(Error::new(
                "Registry index is empty. Run 'ggen marketplace sync' to download the registry.",
            ));
        }

        // Validate package metadata integrity - STRICT
        for (name, metadata) in &index.packages {
            if metadata.versions.is_empty() {
                return Err(Error::new(&format!(
                    "Package {} has no versions defined - registry is corrupted",
                    name
                )));
            }

            for version in &metadata.versions {
                // STRICT: Download URL MUST exist
                if version.download_url.is_empty() {
                    return Err(Error::new(&format!(
                        "Package {}@{} has empty download URL - registry is corrupted",
                        name, version.version
                    )));
                }

                // STRICT: Checksum MUST exist
                if version.checksum.is_empty() {
                    return Err(Error::new(&format!(
                        "Package {}@{} has empty checksum - registry is corrupted",
                        name, version.version
                    )));
                }
            }
        }

        Ok(())
    }
}

impl Default for Registry {
    fn default() -> Self {
        // Default implementation returns error if home directory not found
        // This is handled by Registry::new() which returns Result
        Self::new().unwrap_or_else(|_| {
            // Fallback to temp directory if home not available
            let temp_path = std::env::temp_dir()
                .join("ggen")
                .join("registry")
                .join("index.json");
            Self::with_path(temp_path)
        })
    }
}

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

    /// Helper to create test package metadata
    fn create_test_package(name: &str, version: &str) -> PackageMetadata {
        PackageMetadata {
            name: name.to_string(),
            versions: vec![VersionMetadata {
                version: version.to_string(),
                download_url: format!("https://example.com/{}/{}.tar.gz", name, version),
                checksum: "abcd1234".to_string(),
                dependencies: vec![],
                published_at: chrono::Utc::now().to_rfc3339(),
                size_bytes: 1024,
            }],
            description: format!("Test package {}", name),
            author: Some("Test Author".to_string()),
            category: Some("testing".to_string()),
            tags: vec!["test".to_string()],
            repository: Some("https://github.com/test/repo".to_string()),
            license: Some("MIT".to_string()),
            homepage: Some("https://example.com".to_string()),
        }
    }

    #[test]
    fn test_registry_index_creation() {
        let index = RegistryIndex::new();
        assert_eq!(index.version, "1.0.0");
        assert!(index.packages.is_empty());
    }

    #[test]
    fn test_registry_index_add_package() {
        let mut index = RegistryIndex::new();
        let package = create_test_package("test-pkg", "1.0.0");

        index.add_package(package.clone());

        assert_eq!(index.packages.len(), 1);
        assert_eq!(index.get_package("test-pkg"), Some(&package));
    }

    #[test]
    fn test_cache_manager_basic_operations() {
        let cache = CacheManager::new(3);
        let pkg1 = create_test_package("pkg1", "1.0.0");
        let pkg2 = create_test_package("pkg2", "1.0.0");

        // Initially empty
        assert_eq!(cache.size(), 0);

        // Add packages
        cache.put("pkg1".to_string(), pkg1.clone());
        cache.put("pkg2".to_string(), pkg2.clone());

        assert_eq!(cache.size(), 2);

        // Get from cache
        assert_eq!(cache.get("pkg1"), Some(pkg1));
        assert_eq!(cache.get("pkg2"), Some(pkg2));
        assert_eq!(cache.get("pkg3"), None);
    }

    #[test]
    fn test_cache_manager_lru_eviction() {
        let cache = CacheManager::new(2);
        let pkg1 = create_test_package("pkg1", "1.0.0");
        let pkg2 = create_test_package("pkg2", "1.0.0");
        let pkg3 = create_test_package("pkg3", "1.0.0");

        // Fill cache to capacity
        cache.put("pkg1".to_string(), pkg1.clone());
        cache.put("pkg2".to_string(), pkg2.clone());
        assert_eq!(cache.size(), 2);

        // Access pkg1 to make it most recently used
        let _ = cache.get("pkg1");

        // Add pkg3, should evict pkg2 (least recently used)
        cache.put("pkg3".to_string(), pkg3.clone());

        assert_eq!(cache.size(), 2);
        assert_eq!(cache.get("pkg1"), Some(pkg1)); // Still in cache
        assert_eq!(cache.get("pkg2"), None); // Evicted
        assert_eq!(cache.get("pkg3"), Some(pkg3)); // Newly added
    }

    #[test]
    fn test_cache_manager_clear() {
        let cache = CacheManager::new(5);
        cache.put("pkg1".to_string(), create_test_package("pkg1", "1.0.0"));
        cache.put("pkg2".to_string(), create_test_package("pkg2", "1.0.0"));

        assert_eq!(cache.size(), 2);

        cache.clear();

        assert_eq!(cache.size(), 0);
        assert_eq!(cache.get("pkg1"), None);
    }

    #[tokio::test]
    async fn test_registry_load_and_save_real_filesystem() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");

        // Create empty but valid registry index
        let empty_index =
            r#"{"version":"1.0.0","updated_at":"2024-01-01T00:00:00Z","packages":{}}"#;
        std::fs::write(&index_path, empty_index).unwrap();

        // Create registry
        let registry = Registry::with_path(index_path.clone());

        // Load existing index
        registry.load().await.unwrap();

        // Add a package
        let package = create_test_package("real-pkg", "2.0.0");
        registry.add_package(package.clone()).await.unwrap();

        // Save to filesystem
        registry.save().await.unwrap();

        // Verify file exists
        assert!(index_path.exists());

        // Create new registry and load from file
        let registry2 = Registry::with_path(index_path);
        registry2.load().await.unwrap();

        // Verify package is loaded
        let loaded = registry2.get_package("real-pkg").await.unwrap();
        assert_eq!(loaded, Some(package));
    }

    #[tokio::test]
    async fn test_registry_get_package_with_cache() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");
        // Create empty but valid registry index
        let empty_index =
            r#"{"version":"1.0.0","updated_at":"2024-01-01T00:00:00Z","packages":{}}"#;
        std::fs::write(&index_path, empty_index).unwrap();

        let registry = Registry::with_path(index_path);
        registry.load().await.unwrap();

        let package = create_test_package("cached-pkg", "1.5.0");
        registry.add_package(package.clone()).await.unwrap();

        // First get - loads from index and caches
        let result1 = registry.get_package("cached-pkg").await.unwrap();
        assert_eq!(result1, Some(package.clone()));

        // Second get - should come from cache
        let result2 = registry.get_package("cached-pkg").await.unwrap();
        assert_eq!(result2, Some(package));

        // Verify it's in cache
        assert_eq!(registry.cache().size(), 1);
    }

    #[tokio::test]
    async fn test_registry_list_versions() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");
        // Create empty but valid registry index
        let empty_index =
            r#"{"version":"1.0.0","updated_at":"2024-01-01T00:00:00Z","packages":{}}"#;
        std::fs::write(&index_path, empty_index).unwrap();

        let registry = Registry::with_path(index_path);
        registry.load().await.unwrap();

        // Create package with multiple versions
        let mut package = create_test_package("multi-ver", "1.0.0");
        package.versions.push(VersionMetadata {
            version: "1.1.0".to_string(),
            download_url: "https://example.com/multi-ver/1.1.0.tar.gz".to_string(),
            checksum: "efgh5678".to_string(),
            dependencies: vec![],
            published_at: chrono::Utc::now().to_rfc3339(),
            size_bytes: 2048,
        });
        package.versions.push(VersionMetadata {
            version: "2.0.0".to_string(),
            download_url: "https://example.com/multi-ver/2.0.0.tar.gz".to_string(),
            checksum: "ijkl9012".to_string(),
            dependencies: vec![],
            published_at: chrono::Utc::now().to_rfc3339(),
            size_bytes: 4096,
        });

        registry.add_package(package).await.unwrap();

        let versions = registry.list_versions("multi-ver").await.unwrap();
        assert_eq!(versions.len(), 3);
        assert!(versions.contains(&"1.0.0".to_string()));
        assert!(versions.contains(&"1.1.0".to_string()));
        assert!(versions.contains(&"2.0.0".to_string()));
    }

    #[tokio::test]
    async fn test_registry_get_specific_version() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");
        // Create empty but valid registry index
        let empty_index =
            r#"{"version":"1.0.0","updated_at":"2024-01-01T00:00:00Z","packages":{}}"#;
        std::fs::write(&index_path, empty_index).unwrap();

        let registry = Registry::with_path(index_path);
        registry.load().await.unwrap();

        let package = create_test_package("versioned-pkg", "3.2.1");
        registry.add_package(package).await.unwrap();

        let version = registry
            .get_version("versioned-pkg", "3.2.1")
            .await
            .unwrap();
        assert!(version.is_some());
        assert_eq!(version.unwrap().version, "3.2.1");

        let nonexistent = registry
            .get_version("versioned-pkg", "9.9.9")
            .await
            .unwrap();
        assert!(nonexistent.is_none());
    }

    #[tokio::test]
    async fn test_registry_list_packages() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");
        // Create empty but valid registry index
        let empty_index =
            r#"{"version":"1.0.0","updated_at":"2024-01-01T00:00:00Z","packages":{}}"#;
        std::fs::write(&index_path, empty_index).unwrap();

        let registry = Registry::with_path(index_path);
        registry.load().await.unwrap();

        registry
            .add_package(create_test_package("pkg-a", "1.0.0"))
            .await
            .unwrap();
        registry
            .add_package(create_test_package("pkg-b", "2.0.0"))
            .await
            .unwrap();
        registry
            .add_package(create_test_package("pkg-c", "3.0.0"))
            .await
            .unwrap();

        let packages = registry.list_packages().await.unwrap();
        assert_eq!(packages.len(), 3);
        assert!(packages.contains(&"pkg-a".to_string()));
        assert!(packages.contains(&"pkg-b".to_string()));
        assert!(packages.contains(&"pkg-c".to_string()));
    }

    #[tokio::test]
    async fn test_registry_persistence_across_instances() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("shared-index.json");

        // Create empty but valid registry index
        let empty_index =
            r#"{"version":"1.0.0","updated_at":"2024-01-01T00:00:00Z","packages":{}}"#;
        std::fs::write(&index_path, empty_index).unwrap();

        // First registry instance
        {
            let registry1 = Registry::with_path(index_path.clone());
            registry1.load().await.unwrap();
            registry1
                .add_package(create_test_package("persistent-pkg", "1.0.0"))
                .await
                .unwrap();
            registry1.save().await.unwrap();
        }

        // Second registry instance (simulates restart)
        {
            let registry2 = Registry::with_path(index_path);
            registry2.load().await.unwrap();

            let loaded = registry2.get_package("persistent-pkg").await.unwrap();
            assert!(loaded.is_some());
            assert_eq!(loaded.unwrap().name, "persistent-pkg");
        }
    }

    #[tokio::test]
    async fn test_registry_with_dependencies() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");
        // Create empty but valid registry index
        let empty_index =
            r#"{"version":"1.0.0","updated_at":"2024-01-01T00:00:00Z","packages":{}}"#;
        std::fs::write(&index_path, empty_index).unwrap();

        let registry = Registry::with_path(index_path);
        registry.load().await.unwrap();

        let mut package = create_test_package("dep-pkg", "1.0.0");
        package.versions[0].dependencies = vec![
            Dependency {
                name: "dep1".to_string(),
                version_req: "^1.0.0".to_string(),
                optional: false,
            },
            Dependency {
                name: "dep2".to_string(),
                version_req: ">=2.0.0".to_string(),
                optional: true,
            },
        ];

        registry.add_package(package).await.unwrap();

        let loaded = registry.get_package("dep-pkg").await.unwrap().unwrap();
        assert_eq!(loaded.versions[0].dependencies.len(), 2);
        assert_eq!(loaded.versions[0].dependencies[0].name, "dep1");
        assert!(!loaded.versions[0].dependencies[0].optional);
        assert_eq!(loaded.versions[0].dependencies[1].name, "dep2");
        assert!(loaded.versions[0].dependencies[1].optional);
    }

    #[tokio::test]
    async fn test_registry_load_corrupted_index_fails() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");

        // Write corrupted JSON to index file
        std::fs::write(&index_path, "{ invalid json }").unwrap();

        // DETERMINISTIC: Should FAIL, not silently fallback
        let registry = Registry::with_path(index_path);
        assert!(registry.load().await.is_err());
    }

    #[tokio::test]
    async fn test_registry_load_missing_index_fails() {
        let temp_dir = TempDir::new().unwrap();
        let index_path = temp_dir.path().join("index.json");

        // DETERMINISTIC: Missing index should FAIL
        let registry = Registry::with_path(index_path);
        assert!(registry.load().await.is_err());
    }

    #[tokio::test]
    async fn test_registry_validate_empty_fails() {
        let temp_dir = TempDir::new().unwrap();
        let registry = Registry::with_path(temp_dir.path().join("index.json"));

        // Create valid (but empty) registry
        let index = RegistryIndex::new();
        let mut guard = registry.index.write().unwrap();
        *guard = Some(index);
        drop(guard);

        // DETERMINISTIC: Empty registry FAILS validation
        assert!(registry.validate().await.is_err());
    }

    #[tokio::test]
    async fn test_registry_validate_success_with_valid_packages() {
        let temp_dir = TempDir::new().unwrap();
        let registry = Registry::with_path(temp_dir.path().join("index.json"));

        // Create valid registry with packages
        let mut index = RegistryIndex::new();
        let package = create_test_package("test-pkg", "1.0.0");
        index.add_package(package);
        let mut guard = registry.index.write().unwrap();
        *guard = Some(index);
        drop(guard);

        // Should validate successfully
        assert!(registry.validate().await.is_ok());
    }

    #[tokio::test]
    async fn test_registry_validate_detects_missing_checksum() {
        let temp_dir = TempDir::new().unwrap();
        let registry = Registry::with_path(temp_dir.path().join("index.json"));

        // Create registry with invalid package (empty checksum)
        let mut index = RegistryIndex::new();
        let mut package = create_test_package("invalid-pkg", "1.0.0");
        package.versions[0].checksum = String::new();
        index.add_package(package);
        let mut guard = registry.index.write().unwrap();
        *guard = Some(index);
        drop(guard);

        // DETERMINISTIC: FAILS on missing checksum
        assert!(registry.validate().await.is_err());
    }
}