kopi 0.0.9

Kopi is a JDK version management tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// Copyright 2025 dentsusoken
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::error::{KopiError, Result};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

pub mod file;
pub mod parser;
pub mod resolver;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Version {
    pub components: Vec<u32>,        // All numeric components
    pub build: Option<Vec<u32>>,     // Build numbers as numeric array
    pub pre_release: Option<String>, // Pre-release string
}

impl Version {
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            components: vec![major, minor, patch],
            build: None,
            pre_release: None,
        }
    }

    pub fn from_components(major: u32, minor: Option<u32>, patch: Option<u32>) -> Self {
        let mut components = vec![major];
        if let Some(minor) = minor {
            components.push(minor);
            if let Some(patch) = patch {
                components.push(patch);
            }
        }
        Self {
            components,
            build: None,
            pre_release: None,
        }
    }

    pub fn with_build(mut self, build: String) -> Self {
        // Parse build string into numeric components if possible
        let build_parts: Vec<u32> = build
            .split('.')
            .filter_map(|s| s.parse::<u32>().ok())
            .collect();

        if !build_parts.is_empty() {
            self.build = Some(build_parts);
        } else {
            // If build is not numeric, store it as pre-release
            self.pre_release = Some(build);
        }
        self
    }

    // Helper methods for backward compatibility
    pub fn major(&self) -> u32 {
        self.components.first().copied().unwrap_or(0)
    }

    pub fn minor(&self) -> Option<u32> {
        self.components.get(1).copied()
    }

    pub fn patch(&self) -> Option<u32> {
        self.components.get(2).copied()
    }

    /// Matches a version string against this version.
    /// When the user specifies "21", it matches cache entries like "21.0" and "21.0.0".
    /// When the user specifies "21.0.0", it does NOT match cache entries like "21".
    /// When the user specifies "21.0", it matches cache entries like "21.0.0" and "21.0+32".
    pub fn matches_pattern(&self, pattern: &str) -> bool {
        if let Ok(pattern_version) = Version::from_str(pattern) {
            // Compare components up to the length specified in pattern
            for (i, pattern_comp) in pattern_version.components.iter().enumerate() {
                match self.components.get(i) {
                    Some(self_comp) => {
                        if pattern_comp != self_comp {
                            return false;
                        }
                    }
                    None => {
                        // Pattern specifies more components than self has
                        return false;
                    }
                }
            }

            // Build matching if specified
            if let Some(pattern_build) = &pattern_version.build {
                if let Some(self_build) = &self.build {
                    if pattern_build != self_build {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            // Pre-release matching if specified
            if let Some(pattern_pre) = &pattern_version.pre_release {
                if let Some(self_pre) = &self.pre_release {
                    if pattern_pre != self_pre {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            true
        } else {
            false
        }
    }
}

impl FromStr for Version {
    type Err = KopiError;

    fn from_str(s: &str) -> Result<Self> {
        if s.is_empty() {
            return Err(KopiError::InvalidVersionFormat(s.to_string()));
        }

        let mut remaining = s;
        let mut pre_release = None;
        let mut build = None;

        // Check for pre-release part (after '-')
        // But we need to be careful not to split build metadata that contains '-'
        // First check if there's a '+' and handle that first
        let plus_pos = remaining.find('+');
        let dash_pos = remaining.find('-');

        match (plus_pos, dash_pos) {
            (Some(p), Some(d)) => {
                if p < d {
                    // '+' comes before '-', so everything after '+' is build/pre-release
                    let (before_plus, after_plus) = remaining.split_at(p);
                    remaining = before_plus;
                    let build_str = &after_plus[1..];

                    // Check if build string is empty
                    if build_str.is_empty() {
                        return Err(KopiError::InvalidVersionFormat(s.to_string()));
                    }

                    // Check if build string is purely numeric
                    let parts: Vec<&str> = build_str.split('.').collect();
                    if parts
                        .iter()
                        .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()))
                    {
                        let build_parts: Vec<u32> =
                            parts.iter().map(|s| s.parse().unwrap()).collect();
                        build = Some(build_parts);
                    } else {
                        // Not purely numeric, treat as pre-release
                        pre_release = Some(build_str.to_string());
                    }
                } else {
                    // '-' comes before '+', handle pre-release first
                    let (before_dash, after_dash) = remaining.split_at(d);
                    remaining = before_dash;
                    let pre_str = &after_dash[1..];

                    // Check if pre-release string is empty
                    if pre_str.is_empty() {
                        return Err(KopiError::InvalidVersionFormat(s.to_string()));
                    }

                    pre_release = Some(pre_str.to_string());
                }
            }
            (Some(p), None) => {
                // Only '+' present
                let (before_plus, after_plus) = remaining.split_at(p);
                remaining = before_plus;
                let build_str = &after_plus[1..];

                // Check if build string is empty
                if build_str.is_empty() {
                    return Err(KopiError::InvalidVersionFormat(s.to_string()));
                }

                // Check if build string is purely numeric
                let parts: Vec<&str> = build_str.split('.').collect();
                if parts
                    .iter()
                    .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()))
                {
                    let build_parts: Vec<u32> = parts.iter().map(|s| s.parse().unwrap()).collect();
                    build = Some(build_parts);
                } else {
                    // Not purely numeric, treat as pre-release
                    pre_release = Some(build_str.to_string());
                }
            }
            (None, Some(d)) => {
                // Only '-' present
                let (before_dash, after_dash) = remaining.split_at(d);
                remaining = before_dash;
                let pre_str = &after_dash[1..];

                // Check if pre-release string is empty
                if pre_str.is_empty() {
                    return Err(KopiError::InvalidVersionFormat(s.to_string()));
                }

                pre_release = Some(pre_str.to_string());
            }
            (None, None) => {
                // Neither '+' nor '-' present
            }
        }

        // Parse numeric components
        let components: Result<Vec<u32>> = remaining
            .split('.')
            .map(|s| {
                s.parse::<u32>()
                    .map_err(|_| KopiError::InvalidVersionFormat(s.to_string()))
            })
            .collect();

        let components = components?;

        if components.is_empty() {
            return Err(KopiError::InvalidVersionFormat(s.to_string()));
        }

        Ok(Version {
            components,
            build,
            pre_release,
        })
    }
}

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Write components separated by dots
        for (i, component) in self.components.iter().enumerate() {
            if i > 0 {
                write!(f, ".")?;
            }
            write!(f, "{component}")?;
        }

        // Write build if present
        if let Some(build) = &self.build {
            write!(f, "+")?;
            for (i, component) in build.iter().enumerate() {
                if i > 0 {
                    write!(f, ".")?;
                }
                write!(f, "{component}")?;
            }
        }

        // Write pre-release if present
        if let Some(pre_release) = &self.pre_release {
            write!(f, "-{pre_release}")?;
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionRequest {
    pub version_pattern: String,
    pub distribution: Option<String>,
    pub package_type: Option<crate::models::package::PackageType>,
}

impl VersionRequest {
    pub fn new(version_pattern: String) -> Result<Self> {
        // Special handling for "latest" - not allowed for local command
        if version_pattern.eq_ignore_ascii_case("latest") {
            return Err(KopiError::InvalidVersionFormat(
                "Local command requires a specific version, not 'latest'".to_string(),
            ));
        }

        // Validate that the pattern can be parsed as a version
        Version::from_str(&version_pattern)?;
        Ok(Self {
            version_pattern,
            distribution: None,
            package_type: None,
        })
    }

    pub fn with_distribution(mut self, distribution: String) -> Self {
        self.distribution = Some(distribution);
        self
    }

    pub fn with_package_type(mut self, package_type: crate::models::package::PackageType) -> Self {
        self.package_type = Some(package_type);
        self
    }
}

impl std::fmt::Display for VersionRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.distribution {
            Some(dist) => write!(f, "{}@{}", dist, self.version_pattern),
            None => write!(f, "{}", self.version_pattern),
        }
    }
}

impl FromStr for VersionRequest {
    type Err = KopiError;

    fn from_str(s: &str) -> Result<Self> {
        if s.contains('@') {
            let parts: Vec<&str> = s.split('@').collect();
            match parts.len() {
                2 => {
                    // Legacy format: distribution@version
                    Ok(VersionRequest::new(parts[1].to_string())?
                        .with_distribution(parts[0].to_string()))
                }
                3 => {
                    // New format: package_type@version@distribution
                    let package_type = crate::models::package::PackageType::from_str(parts[0])?;
                    Ok(VersionRequest::new(parts[1].to_string())?
                        .with_distribution(parts[2].to_string())
                        .with_package_type(package_type))
                }
                _ => Err(KopiError::InvalidVersionFormat(s.to_string())),
            }
        } else {
            VersionRequest::new(s.to_string())
        }
    }
}

/// Format version in minimal representation
/// - Just major version if minor and patch are 0 (e.g., "21" instead of "21.0.0")
/// - Major.minor if patch is 0 (e.g., "21.1" instead of "21.1.0")
/// - Full version otherwise
pub fn format_version_minimal(version: &Version) -> String {
    if version.minor() == Some(0) && version.patch() == Some(0) {
        // Just major version (e.g., "21" instead of "21.0.0")
        version.major().to_string()
    } else if version.patch() == Some(0) {
        // Major.minor (e.g., "21.1" instead of "21.1.0")
        format!("{}.{}", version.major(), version.minor().unwrap())
    } else {
        // Full version
        version.to_string()
    }
}

/// Common validation for version commands
pub fn validate_version_for_command<'a>(
    version: &'a Option<Version>,
    command_name: &str,
) -> Result<&'a Version> {
    version.as_ref().ok_or_else(|| {
        KopiError::InvalidVersionFormat(format!(
            "{command_name} command requires a specific version (e.g., '21' or 'temurin@21')"
        ))
    })
}

/// Build a VersionRequest for auto-installation
pub fn build_install_request(
    distribution: &crate::models::distribution::Distribution,
    version: &Version,
) -> VersionRequest {
    VersionRequest {
        distribution: Some(distribution.id().to_string()),
        version_pattern: version.to_string(),
        package_type: None,
    }
}

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

    #[test]
    fn test_version_parsing() {
        // Basic versions
        assert_eq!(
            Version::from_str("21").unwrap(),
            Version::from_components(21, None, None)
        );
        assert_eq!(
            Version::from_str("21.0").unwrap(),
            Version::from_components(21, Some(0), None)
        );
        assert_eq!(Version::from_str("21.0.0").unwrap(), Version::new(21, 0, 0));
        assert_eq!(Version::from_str("17.0.9").unwrap(), Version::new(17, 0, 9));

        // Version with numeric build
        let v = Version::from_str("11.0.2+9").unwrap();
        assert_eq!(v.components, vec![11, 0, 2]);
        assert_eq!(v.build, Some(vec![9]));

        // Extended versions (Corretto format)
        let v = Version::from_str("21.0.7.6.1").unwrap();
        assert_eq!(v.components, vec![21, 0, 7, 6, 1]);
        assert_eq!(v.build, None);

        // Dragonwell 6-component format
        let v = Version::from_str("21.0.7.0.7.6").unwrap();
        assert_eq!(v.components, vec![21, 0, 7, 0, 7, 6]);

        // Multi-component build
        let v = Version::from_str("21.0.7+9.1").unwrap();
        assert_eq!(v.components, vec![21, 0, 7]);
        assert_eq!(v.build, Some(vec![9, 1]));

        // Pre-release version
        let v = Version::from_str("21.0.7-ea").unwrap();
        assert_eq!(v.components, vec![21, 0, 7]);
        assert_eq!(v.pre_release, Some("ea".to_string()));

        assert!(Version::from_str("invalid").is_err());
        assert!(Version::from_str("").is_err());
    }

    #[test]
    fn test_version_display() {
        assert_eq!(Version::from_components(21, None, None).to_string(), "21");
        assert_eq!(
            Version::from_components(21, Some(0), None).to_string(),
            "21.0"
        );
        assert_eq!(Version::new(21, 0, 0).to_string(), "21.0.0");
        assert_eq!(Version::new(17, 0, 9).to_string(), "17.0.9");

        // Version with single-component build
        let v = Version::from_str("11.0.2+9").unwrap();
        assert_eq!(v.to_string(), "11.0.2+9");

        // Extended Corretto version
        let v = Version::from_str("21.0.7.6.1").unwrap();
        assert_eq!(v.to_string(), "21.0.7.6.1");

        // Multi-component build
        let v = Version::from_str("21.0.7+9.1.3").unwrap();
        assert_eq!(v.to_string(), "21.0.7+9.1.3");

        // Pre-release version
        let v = Version::from_str("21.0.7-ea").unwrap();
        assert_eq!(v.to_string(), "21.0.7-ea");
    }

    #[test]
    fn test_version_matching() {
        // Test matching with full version
        let v21_0_1 = Version::new(21, 0, 1);
        assert!(v21_0_1.matches_pattern("21")); // User specifies 21, matches 21.0.1
        assert!(!v21_0_1.matches_pattern("17"));

        let v17_0_9 = Version::new(17, 0, 9);
        assert!(v17_0_9.matches_pattern("17"));
        assert!(v17_0_9.matches_pattern("17.0"));
        assert!(v17_0_9.matches_pattern("17.0.9"));
        assert!(!v17_0_9.matches_pattern("17.0.8"));

        // Test that cache entries with fewer components don't match specific user values
        let v21 = Version::from_components(21, None, None);
        assert!(v21.matches_pattern("21"));
        assert!(!v21.matches_pattern("21.0")); // User specifies 21.0, cache has only 21
        assert!(!v21.matches_pattern("21.0.0")); // User specifies 21.0.0, cache has only 21

        let v21_0 = Version::from_components(21, Some(0), None);
        assert!(v21_0.matches_pattern("21")); // User specifies 21, matches 21.0
        assert!(v21_0.matches_pattern("21.0")); // User specifies 21.0, matches 21.0
        assert!(!v21_0.matches_pattern("21.0.0")); // User specifies 21.0.0, cache has only 21.0

        // Test extended version matching (Corretto)
        let v_corretto = Version::from_str("21.0.7.6.1").unwrap();
        assert!(v_corretto.matches_pattern("21"));
        assert!(v_corretto.matches_pattern("21.0"));
        assert!(v_corretto.matches_pattern("21.0.7"));
        assert!(v_corretto.matches_pattern("21.0.7.6"));
        assert!(v_corretto.matches_pattern("21.0.7.6.1"));
        assert!(!v_corretto.matches_pattern("21.0.7.6.2"));
    }

    #[test]
    fn test_matches_pattern() {
        // Test with complete version in cache
        let v21_0_0_build = Version::new(21, 0, 0).with_build("37".to_string());
        assert!(v21_0_0_build.matches_pattern("21")); // User: 21, Cache: 21.0.0+37 - match
        assert!(v21_0_0_build.matches_pattern("21.0")); // User: 21.0, Cache: 21.0.0+37 - match
        assert!(v21_0_0_build.matches_pattern("21.0.0")); // User: 21.0.0, Cache: 21.0.0+37 - match
        assert!(v21_0_0_build.matches_pattern("21.0.0+37")); // With build - match
        assert!(!v21_0_0_build.matches_pattern("21.0.0+38")); // Different build - no match
        assert!(!v21_0_0_build.matches_pattern("22")); // Different major - no match

        // Test with non-zero minor/patch
        let v21_0_7_build = Version::new(21, 0, 7).with_build("9".to_string());
        assert!(v21_0_7_build.matches_pattern("21")); // User: 21, Cache: 21.0.7+9 - match
        assert!(v21_0_7_build.matches_pattern("21.0")); // User: 21.0, Cache: 21.0.7+9 - match  
        assert!(!v21_0_7_build.matches_pattern("21.0.0")); // User: 21.0.0, Cache: 21.0.7 - no match (different patch)
        assert!(v21_0_7_build.matches_pattern("21.0.7")); // Exact match
        assert!(v21_0_7_build.matches_pattern("21.0.7+9")); // Exact match with build
        assert!(!v21_0_7_build.matches_pattern("21.0.7+10")); // Different build

        // Test version without build
        let v17_0_9 = Version::new(17, 0, 9);
        assert!(v17_0_9.matches_pattern("17")); // User: 17, Cache: 17.0.9 - match
        assert!(v17_0_9.matches_pattern("17.0")); // User: 17.0, Cache: 17.0.9 - match
        assert!(v17_0_9.matches_pattern("17.0.9")); // Exact match
        assert!(!v17_0_9.matches_pattern("17.0.8")); // Different patch
        assert!(!v17_0_9.matches_pattern("17.1")); // Different minor

        // Test incomplete versions in cache
        let v21 = Version::from_components(21, None, None);
        assert!(v21.matches_pattern("21")); // User: 21, Cache: 21 - match
        assert!(!v21.matches_pattern("21.0")); // User: 21.0, Cache: 21 - no match
        assert!(!v21.matches_pattern("21.0.0")); // User: 21.0.0, Cache: 21 - no match

        let v21_0 = Version::from_components(21, Some(0), None);
        assert!(v21_0.matches_pattern("21")); // User: 21, Cache: 21.0 - match
        assert!(v21_0.matches_pattern("21.0")); // User: 21.0, Cache: 21.0 - match
        assert!(!v21_0.matches_pattern("21.0.0")); // User: 21.0.0, Cache: 21.0 - no match

        // Test major-only version with build
        let v23_build = Version::from_components(23, None, None).with_build("38".to_string());
        assert!(v23_build.matches_pattern("23")); // User: 23, Cache: 23+38 - match
        assert!(v23_build.matches_pattern("23+38")); // With build - match
        assert!(!v23_build.matches_pattern("23+37")); // Different build - no match
        assert!(!v23_build.matches_pattern("23.0")); // User: 23.0, Cache: 23+38 - no match
    }

    #[test]
    fn test_version_request_parsing() {
        let req = VersionRequest::from_str("21").unwrap();
        assert_eq!(req.version_pattern, "21");
        assert_eq!(req.distribution, None);
        assert_eq!(req.package_type, None);

        // Legacy format: distribution@version
        let req = VersionRequest::from_str("corretto@17").unwrap();
        assert_eq!(req.version_pattern, "17");
        assert_eq!(req.distribution, Some("corretto".to_string()));
        assert_eq!(req.package_type, None);

        // New format: package_type@version@distribution
        let req = VersionRequest::from_str("jre@21@temurin").unwrap();
        assert_eq!(req.version_pattern, "21");
        assert_eq!(req.distribution, Some("temurin".to_string()));
        assert_eq!(
            req.package_type,
            Some(crate::models::package::PackageType::Jre)
        );

        let req = VersionRequest::from_str("jdk@17.0.9@corretto").unwrap();
        assert_eq!(req.version_pattern, "17.0.9");
        assert_eq!(req.distribution, Some("corretto".to_string()));
        assert_eq!(
            req.package_type,
            Some(crate::models::package::PackageType::Jdk)
        );

        // Invalid formats
        assert!(VersionRequest::from_str("invalid@format@").is_err());
        assert!(VersionRequest::from_str("too@many@parts@here").is_err());
        assert!(VersionRequest::from_str("invalid_type@21@temurin").is_err()); // Invalid package type
    }

    #[test]
    fn test_corretto_version_formats() {
        // Corretto 4-component format
        let v = Version::from_str("21.0.7.6").unwrap();
        assert_eq!(v.components, vec![21, 0, 7, 6]);
        assert_eq!(v.build, None);
        assert_eq!(v.pre_release, None);

        // Corretto 5-component format
        let v = Version::from_str("21.0.7.6.1").unwrap();
        assert_eq!(v.components, vec![21, 0, 7, 6, 1]);
        assert_eq!(v.build, None);
        assert_eq!(v.pre_release, None);

        // Corretto Java 8 special format (no leading zero)
        let v = Version::from_str("8.452.9.1").unwrap();
        assert_eq!(v.components, vec![8, 452, 9, 1]);
        assert_eq!(v.major(), 8);

        // Corretto with build number
        let v = Version::from_str("21.0.7.6.1+13").unwrap();
        assert_eq!(v.components, vec![21, 0, 7, 6, 1]);
        assert_eq!(v.build, Some(vec![13]));
    }

    #[test]
    fn test_dragonwell_version_formats() {
        // Dragonwell 6-component format
        let v = Version::from_str("21.0.7.0.7.6").unwrap();
        assert_eq!(v.components, vec![21, 0, 7, 0, 7, 6]);
        assert_eq!(v.build, None);
        assert_eq!(v.pre_release, None);

        // Dragonwell with build
        let v = Version::from_str("17.0.13.0.13.11+11").unwrap();
        assert_eq!(v.components, vec![17, 0, 13, 0, 13, 11]);
        assert_eq!(v.build, Some(vec![11]));
    }

    #[test]
    fn test_jetbrains_large_build_numbers() {
        // JetBrains Runtime with large build numbers
        let v = Version::from_str("21.0.5+13.674.11").unwrap();
        assert_eq!(v.components, vec![21, 0, 5]);
        assert_eq!(v.build, Some(vec![13, 674, 11]));

        // JetBrains Runtime with b prefix (not numeric, so becomes pre-release)
        let v = Version::from_str("21.0.5+13-b674.11").unwrap();
        assert_eq!(v.components, vec![21, 0, 5]);
        assert_eq!(v.build, None);
        assert_eq!(v.pre_release, Some("13-b674.11".to_string()));
    }

    #[test]
    fn test_graalvm_complex_identifiers() {
        // GraalVM CE with jvmci identifier
        let v = Version::from_str("21.0.5+11-jvmci-24.1-b01").unwrap();
        assert_eq!(v.components, vec![21, 0, 5]);
        assert_eq!(v.build, None);
        assert_eq!(v.pre_release, Some("11-jvmci-24.1-b01".to_string()));

        // GraalVM EE with complex pre-release
        let v = Version::from_str("21.0.5-ea+11").unwrap();
        assert_eq!(v.components, vec![21, 0, 5]);
        assert_eq!(v.build, None);
        assert_eq!(v.pre_release, Some("ea+11".to_string()));
    }

    #[test]
    fn test_edge_cases() {
        // Single component
        let v = Version::from_str("8").unwrap();
        assert_eq!(v.components, vec![8]);
        assert_eq!(v.major(), 8);
        assert_eq!(v.minor(), None);
        assert_eq!(v.patch(), None);

        // Many components (theoretical case)
        let v = Version::from_str("1.2.3.4.5.6.7.8.9").unwrap();
        assert_eq!(v.components, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);

        // Zero values
        let v = Version::from_str("0.0.0").unwrap();
        assert_eq!(v.components, vec![0, 0, 0]);

        // Mixed zeros and non-zeros
        let v = Version::from_str("21.0.0.0.1").unwrap();
        assert_eq!(v.components, vec![21, 0, 0, 0, 1]);
    }

    #[test]
    fn test_invalid_formats() {
        // Empty string
        assert!(Version::from_str("").is_err());

        // Non-numeric components
        assert!(Version::from_str("abc").is_err());
        assert!(Version::from_str("21.x.0").is_err());
        assert!(Version::from_str("21.0.0.beta").is_err());

        // Invalid separators
        assert!(Version::from_str("21_0_7").is_err());
        assert!(Version::from_str("21,0,7").is_err());

        // Leading/trailing dots
        assert!(Version::from_str(".21.0.7").is_err());
        assert!(Version::from_str("21.0.7.").is_err());
        assert!(Version::from_str("21..0").is_err());

        // Invalid build/pre-release
        assert!(Version::from_str("21.0.7+").is_err());
        assert!(Version::from_str("21.0.7-").is_err());
    }

    #[test]
    fn test_version_pattern_matching_extended() {
        // Test Corretto 4-5 component matching
        let v_corretto = Version::from_str("21.0.7.6.1").unwrap();
        assert!(v_corretto.matches_pattern("21"));
        assert!(v_corretto.matches_pattern("21.0"));
        assert!(v_corretto.matches_pattern("21.0.7"));
        assert!(v_corretto.matches_pattern("21.0.7.6"));
        assert!(v_corretto.matches_pattern("21.0.7.6.1"));
        assert!(!v_corretto.matches_pattern("21.0.7.6.2"));
        assert!(!v_corretto.matches_pattern("21.0.7.5"));

        // Test Dragonwell 6-component matching
        let v_dragonwell = Version::from_str("21.0.7.0.7.6").unwrap();
        assert!(v_dragonwell.matches_pattern("21"));
        assert!(v_dragonwell.matches_pattern("21.0"));
        assert!(v_dragonwell.matches_pattern("21.0.7"));
        assert!(v_dragonwell.matches_pattern("21.0.7.0"));
        assert!(v_dragonwell.matches_pattern("21.0.7.0.7"));
        assert!(v_dragonwell.matches_pattern("21.0.7.0.7.6"));
        assert!(!v_dragonwell.matches_pattern("21.0.7.0.7.5"));

        // Test build number matching
        let v_with_build = Version::from_str("21.0.5+13.674.11").unwrap();
        assert!(v_with_build.matches_pattern("21"));
        assert!(v_with_build.matches_pattern("21.0"));
        assert!(v_with_build.matches_pattern("21.0.5"));
        assert!(v_with_build.matches_pattern("21.0.5+13.674.11"));
        assert!(!v_with_build.matches_pattern("21.0.5+13.674"));
        assert!(!v_with_build.matches_pattern("21.0.5+13.674.12"));

        // Test pre-release matching
        let v_pre = Version::from_str("21.0.5-ea").unwrap();
        assert!(v_pre.matches_pattern("21"));
        assert!(v_pre.matches_pattern("21.0"));
        assert!(v_pre.matches_pattern("21.0.5"));
        assert!(v_pre.matches_pattern("21.0.5-ea"));
        assert!(!v_pre.matches_pattern("21.0.5-beta"));
    }

    #[test]
    fn test_version_ordering() {
        // Basic ordering
        assert!(Version::from_str("21").unwrap() < Version::from_str("22").unwrap());
        assert!(Version::from_str("21.0").unwrap() < Version::from_str("21.1").unwrap());
        assert!(Version::from_str("21.0.0").unwrap() < Version::from_str("21.0.1").unwrap());

        // Extended component ordering
        assert!(Version::from_str("21.0.7.6").unwrap() < Version::from_str("21.0.7.6.1").unwrap());
        assert!(
            Version::from_str("21.0.7.5.9").unwrap() < Version::from_str("21.0.7.6.1").unwrap()
        );

        // Same version different component count
        assert!(Version::from_str("21").unwrap() < Version::from_str("21.0").unwrap());
        assert!(Version::from_str("21.0").unwrap() < Version::from_str("21.0.0").unwrap());

        // Build number ordering
        assert!(Version::from_str("21.0.5+9").unwrap() < Version::from_str("21.0.5+10").unwrap());
        assert!(Version::from_str("21.0.5").unwrap() < Version::from_str("21.0.5+1").unwrap());
    }

    #[test]
    fn test_semeru_and_other_formats() {
        // IBM Semeru format
        let v = Version::from_str("21.0.5+11.0.572").unwrap();
        assert_eq!(v.components, vec![21, 0, 5]);
        assert_eq!(v.build, Some(vec![11, 0, 572]));

        // Temurin standard format
        let v = Version::from_str("21.0.5+11").unwrap();
        assert_eq!(v.components, vec![21, 0, 5]);
        assert_eq!(v.build, Some(vec![11]));

        // Zulu format with build
        let v = Version::from_str("21.0.5+11.0.25").unwrap();
        assert_eq!(v.components, vec![21, 0, 5]);
        assert_eq!(v.build, Some(vec![11, 0, 25]));
    }

    #[test]
    fn test_format_version_minimal() {
        // Test major only
        let v1 = Version::new(21, 0, 0);
        assert_eq!(format_version_minimal(&v1), "21");

        // Test major.minor
        let v2 = Version::new(17, 1, 0);
        assert_eq!(format_version_minimal(&v2), "17.1");

        // Test full version
        let v3 = Version::new(11, 0, 21);
        assert_eq!(format_version_minimal(&v3), "11.0.21");
    }

    #[test]
    fn test_validate_version_for_command() {
        let version = Some(Version::new(21, 0, 0));
        let result = validate_version_for_command(&version, "test");
        assert!(result.is_ok());

        let none_version: Option<Version> = None;
        let result = validate_version_for_command(&none_version, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_build_install_request() {
        use crate::models::distribution::Distribution;

        let dist = Distribution::Temurin;
        let version = Version::new(21, 0, 0);
        let request = build_install_request(&dist, &version);

        assert_eq!(request.distribution, Some("temurin".to_string()));
        assert_eq!(request.version_pattern, "21.0.0");
    }
}