flyboat 2.0.0

Container environment manager for development
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
//! Integration tests for flyboat
//!
//! These tests use temporary directories to simulate a flyboat environment
//! without affecting the real system.

use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;

/// Helper to create a test environment structure
struct TestEnv {
    temp_dir: TempDir,
}

impl TestEnv {
    /// Create a new test environment with a fake home directory
    fn new() -> Self {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        Self { temp_dir }
    }

    fn home(&self) -> PathBuf {
        self.temp_dir.path().to_path_buf()
    }

    /// Create the flyboat directory structure
    fn init_flyboat(&self) -> PathBuf {
        let flyboat_dir = self.home().join(".flyboat");
        let env_dir = flyboat_dir.join("env");
        fs::create_dir_all(&env_dir).expect("Failed to create flyboat dirs");
        env_dir
    }

    /// Create an environment with Dockerfile and dev_env.yaml
    /// Supports nested paths like "my_collection/rust"
    fn create_env(&self, name: &str, dev_env_yaml: &str) {
        let env_dir = self.init_flyboat();
        let env_path = env_dir.join(name);
        fs::create_dir_all(&env_path).expect("Failed to create env dir");

        // Write Dockerfile
        let dockerfile = env_path.join("Dockerfile");
        fs::write(&dockerfile, "FROM alpine:latest\n").expect("Failed to write Dockerfile");

        // Write dev_env.yaml
        let dev_env = env_path.join("dev_env.yaml");
        fs::write(&dev_env, dev_env_yaml).expect("Failed to write dev_env.yaml");
    }

    /// Create a folder without environment files (for namespace-only folders)
    fn create_folder(&self, name: &str) {
        let env_dir = self.init_flyboat();
        let folder_path = env_dir.join(name);
        fs::create_dir_all(&folder_path).expect("Failed to create folder");
    }

    /// Create global config
    fn create_config(&self, content: &str) {
        let flyboat_dir = self.home().join(".flyboat");
        fs::create_dir_all(&flyboat_dir).expect("Failed to create flyboat dir");

        let config_path = flyboat_dir.join("config.yaml");
        fs::write(&config_path, content).expect("Failed to write config");
    }
}

mod config_tests {
    use super::*;
    use flyboat::config::{EnvConfig, GlobalConfig};

    #[test]
    fn test_load_dev_env_from_file() {
        let env = TestEnv::new();
        let yaml = r#"
name: python
description: Python development
aliases:
  - py
"#;
        env.create_env("python", yaml);

        let dev_env_path = env.home().join(".flyboat/env/python/dev_env.yaml");
        let config = EnvConfig::load(&dev_env_path).unwrap();

        assert_eq!(config.name, "python");
        assert_eq!(config.description, "Python development");
        assert_eq!(config.aliases, vec!["py"]);
    }

    #[test]
    fn test_load_global_config() {
        let env = TestEnv::new();
        env.create_config(
            r#"
container_engine: podman
arch: arm64
"#,
        );

        let config_path = env.home().join(".flyboat/config.yaml");
        let config = GlobalConfig::load(&config_path).unwrap();

        assert_eq!(config.container_engine, "podman");
        assert_eq!(config.arch, Some("arm64".to_string()));
    }

    #[test]
    fn test_missing_dev_env_yaml_error() {
        let env = TestEnv::new();
        let dev_env_path = env.home().join(".flyboat/env/nonexistent/dev_env.yaml");

        let result = EnvConfig::load(&dev_env_path);
        assert!(result.is_err());
    }
}

mod environment_tests {
    use super::*;
    use flyboat::config::Paths;
    use flyboat::environment::{EnvironmentManager, EnvironmentSearch};

    /// Helper to extract single match from EnvironmentSearch
    fn unwrap_single(search: EnvironmentSearch) -> std::rc::Rc<flyboat::environment::Environment> {
        match search {
            EnvironmentSearch::SingleMatch(env) => env,
            other => panic!(
                "Expected SingleMatch, got {:?}",
                std::mem::discriminant(&other)
            ),
        }
    }

    /// Helper to check if search found a single match
    fn is_single_match(search: &EnvironmentSearch) -> bool {
        matches!(search, EnvironmentSearch::SingleMatch(_))
    }

    /// Helper to check if search found multiple matches
    fn is_multi_match(search: &EnvironmentSearch) -> bool {
        matches!(search, EnvironmentSearch::MultiMatch(_))
    }

    #[test]
    fn test_discover_environments() {
        let env = TestEnv::new();

        env.create_env("python", "name: python\n");
        env.create_env("rust", "name: rust\n");
        env.create_env("node", "name: node\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let envs = manager.list();

        assert_eq!(envs.len(), 3);

        let names: Vec<&str> = envs.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"python"));
        assert!(names.contains(&"rust"));
        assert!(names.contains(&"node"));

        // Root-level envs should have empty namespace and name == full_name()
        for e in envs {
            assert!(e.namespace.is_empty());
            assert_eq!(e.name, e.full_name());
        }
    }

    #[test]
    fn test_get_by_name() {
        let env = TestEnv::new();
        env.create_env("python", "name: python\ndescription: Python env\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let python = unwrap_single(manager.get("python"));

        assert_eq!(python.name, "python");
        assert_eq!(python.config.description, "Python env");
    }

    #[test]
    fn test_get_by_alias() {
        let env = TestEnv::new();
        env.create_env(
            "python",
            r#"
name: python
aliases:
  - py
  - python3
"#,
        );

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Should find by alias
        assert!(is_single_match(&manager.get("py")));
        assert!(is_single_match(&manager.get("python3")));
        assert!(is_single_match(&manager.get("python")));
    }

    #[test]
    fn test_fuzzy_suggestion() {
        let env = TestEnv::new();
        env.create_env("python", "name: python\n");
        env.create_env("rust", "name: rust\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Typo should return fuzzy match
        let result = manager.search("pythn");
        assert!(
            matches!(result, EnvironmentSearch::FuzzyMatch(_)),
            "Expected FuzzyMatch for typo"
        );
    }

    #[test]
    fn test_fuzzy_suggestion_no_match() {
        let env = TestEnv::new();
        env.create_env("python", "name: python\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Very different name should return NoFound
        let result = manager.search("xyz");
        assert!(
            matches!(result, EnvironmentSearch::NoFound),
            "Expected NoFound for completely different name"
        );
    }

    #[test]
    fn test_empty_environment() {
        let env = TestEnv::new();
        env.init_flyboat(); // Create empty env dir

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        assert!(manager.is_empty());
    }

    #[test]
    fn test_skip_incomplete_env() {
        let env = TestEnv::new();
        let env_dir = env.init_flyboat();

        // Create env without Dockerfile
        let incomplete = env_dir.join("incomplete");
        fs::create_dir_all(&incomplete).unwrap();
        fs::write(incomplete.join("dev_env.yaml"), "name: incomplete\n").unwrap();
        // No Dockerfile!

        // Create complete env
        env.create_env("complete", "name: complete\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let envs = manager.list();

        // Should only find complete env
        assert_eq!(envs.len(), 1);
        assert_eq!(envs[0].name, "complete");
    }

    #[test]
    fn test_nested_environments() {
        let env = TestEnv::new();

        // Create nested environments
        env.create_env("my_collection/rust", "name: rust\n");
        env.create_env("my_collection/python", "name: python\n");
        env.create_env("standalone", "name: standalone\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let envs = manager.list();

        assert_eq!(envs.len(), 3);

        // Check nested env
        let rust = unwrap_single(manager.get("my_collection/rust"));
        assert_eq!(rust.name, "rust");
        assert_eq!(rust.namespace, vec!["my_collection"]);
        assert_eq!(rust.full_name(), "my_collection/rust");

        // Check standalone env
        let standalone = unwrap_single(manager.get("standalone"));
        assert_eq!(standalone.name, "standalone");
        assert!(standalone.namespace.is_empty());
        assert_eq!(standalone.full_name(), "standalone");
    }

    #[test]
    fn test_unique_short_name_resolution() {
        let env = TestEnv::new();

        // Only one "rust" exists
        env.create_env("my_collection/rust", "name: rust\n");
        env.create_env("python", "name: python\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Should resolve short name to full name when unambiguous
        let rust = unwrap_single(manager.get("rust"));
        assert_eq!(rust.full_name(), "my_collection/rust");
    }

    #[test]
    fn test_ambiguous_short_name() {
        let env = TestEnv::new();

        // Two environments named "rust"
        env.create_env("collection_a/rust", "name: rust\n");
        env.create_env("collection_b/rust", "name: rust\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Short name should be ambiguous (MultiMatch)
        assert!(is_multi_match(&manager.get("rust")));

        // search_result should return error for ambiguous
        let result = manager.search_result("rust");
        assert!(result.is_err());

        // Full names should still work
        assert!(is_single_match(&manager.get("collection_a/rust")));
        assert!(is_single_match(&manager.get("collection_b/rust")));
    }

    #[test]
    fn test_deeply_nested_environments() {
        let env = TestEnv::new();

        // Create deeply nested environment
        env.create_env("a/b/c/rust", "name: rust\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        let rust = unwrap_single(manager.get("a/b/c/rust"));
        assert_eq!(rust.name, "rust");
        assert_eq!(rust.namespace, vec!["a", "b", "c"]);
        assert_eq!(rust.full_name(), "a/b/c/rust");

        // Short name should work when unambiguous
        let rust2 = unwrap_single(manager.get("rust"));
        assert_eq!(rust2.full_name(), "a/b/c/rust");
    }

    #[test]
    fn test_nested_containers_both_valid() {
        let env = TestEnv::new();

        // Parent folder is a container AND has a nested container
        env.create_env("parent", "name: parent\n");
        env.create_env("parent/child", "name: child\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let envs = manager.list();

        // Both should be discovered
        assert_eq!(envs.len(), 2);
        assert!(is_single_match(&manager.get("parent")));
        assert!(is_single_match(&manager.get("parent/child")));
    }

    #[test]
    fn test_empty_namespace_folder_ignored() {
        let env = TestEnv::new();

        // Create an empty namespace folder (no Dockerfile/dev_env.yaml)
        env.create_folder("empty_collection");
        // Create valid env inside it
        env.create_env("empty_collection/rust", "name: rust\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let envs = manager.list();

        // Only the valid env should be found
        assert_eq!(envs.len(), 1);
        assert_eq!(envs[0].full_name(), "empty_collection/rust");
    }

    #[test]
    fn test_disabled_environment_not_discovered() {
        let env = TestEnv::new();

        // Create disabled environment
        env.create_env(
            "disabled",
            r#"
name: disabled
disable: true
"#,
        );

        // Create enabled environment
        env.create_env("enabled", "name: enabled\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let envs = manager.list();

        // Only enabled environment should be found
        assert_eq!(envs.len(), 1);
        assert_eq!(envs[0].name, "enabled");

        // Disabled environment should not be found
        assert!(matches!(
            manager.get("disabled"),
            EnvironmentSearch::NoFound
        ));
    }

    #[test]
    fn test_symlinked_environment_preserves_namespace() {
        let env = TestEnv::new();
        let env_dir = env.init_flyboat();

        // Create actual environment outside the namespace structure
        let actual_rust = env.home().join("actual-rust-env");
        fs::create_dir_all(&actual_rust).unwrap();
        fs::write(actual_rust.join("Dockerfile"), "FROM alpine:latest\n").unwrap();
        fs::write(actual_rust.join("dev_env.yaml"), "name: rust\n").unwrap();

        // Create symlink inside namespace: my_collection/rust -> /actual-rust-env
        let namespace_dir = env_dir.join("my_collection");
        fs::create_dir_all(&namespace_dir).unwrap();
        std::os::unix::fs::symlink(&actual_rust, namespace_dir.join("rust")).unwrap();

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Should find the env with correct namespace (from symlink location, not target)
        let rust = unwrap_single(manager.get("my_collection/rust"));
        assert_eq!(rust.name, "rust");
        assert_eq!(rust.namespace, vec!["my_collection"]);
        assert_eq!(rust.full_name(), "my_collection/rust");

        // The actual path should be the resolved canonical path
        assert_eq!(
            rust.path.canonicalize().unwrap(),
            actual_rust.canonicalize().unwrap()
        );
    }
}

mod docker_command_tests {
    use flyboat::docker::Engine;
    use flyboat::docker::build::BuildCommand;
    use flyboat::docker::run::{MountSpec, RunCommand};

    #[test]
    fn test_full_build_command() {
        let cmd = BuildCommand {
            engine: Engine::Docker,
            image_name: "flyboat-python-arm64".to_string(),
            context_path: "/home/user/.flyboat/env/python".to_string(),
            dockerfile_path: "/home/user/.flyboat/env/python/Dockerfile".to_string(),
            platform: Some("linux/arm64".to_string()),
            no_cache: true,
        };

        let display = format!("{}", cmd);
        assert!(display.contains("docker build"));
        assert!(display.contains("--tag flyboat-python-arm64"));
        assert!(display.contains("--platform linux/arm64"));
        assert!(display.contains("--no-cache"));
    }

    #[test]
    fn test_full_run_command() {
        let cmd = RunCommand {
            engine: Engine::Podman,
            image_name: "flyboat-python".to_string(),
            container_name: "flyboat-python-0".to_string(),
            working_dir: Some("/project".to_string()),
            network: "bridge".to_string(),
            ports: vec!["8080:80".to_string()],
            mounts: vec![MountSpec {
                host_path: "/home/user/project".to_string(),
                container_path: "/project".to_string(),
                readonly: false,
            }],
            custom_args: vec!["-e".to_string(), "DEBUG=1".to_string()],
            entrypoint: Some("python".to_string()),
            interactive: true,
            remove_on_exit: true,
        };

        let display = format!("{}", cmd);
        assert!(display.contains("podman run"));
        assert!(display.contains("-it"));
        assert!(display.contains("--rm"));
        assert!(display.contains("--userns keep-id:uid=3400,gid=3400"));
        assert!(display.contains("127.0.0.1:8080:80"));
        assert!(display.contains("-e DEBUG=1"));
        assert!(display.contains("--entrypoint python"));
    }
}

mod port_validation_tests {
    use clap::Parser;
    use flyboat::cli::{Cli, Command};

    fn parse(args: &[&str]) -> Cli {
        let mut full_args = vec!["flyboat"];
        full_args.extend_from_slice(args);
        Cli::parse_from(full_args)
    }

    #[test]
    fn test_single_port_parsing() {
        let cli = parse(&["run", "test", "-p", "8080"]);
        match cli.command {
            Command::Run(args) => {
                assert_eq!(args.port, vec!["8080"]);
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_port_mapping_parsing() {
        let cli = parse(&["run", "test", "-p", "8080:80"]);
        match cli.command {
            Command::Run(args) => {
                assert_eq!(args.port, vec!["8080:80"]);
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_multiple_ports() {
        let cli = parse(&["run", "test", "-p", "8080", "-p", "3000", "-p", "5432:5432"]);
        match cli.command {
            Command::Run(args) => {
                assert_eq!(args.port.len(), 3);
            }
            _ => panic!("Expected Run command"),
        }
    }
}

mod security_tests {
    #[test]
    fn test_dangerous_paths_documentation() {
        // These paths should be blocked by check_safe_directory:
        // - "/" (root)
        // - "/root" (root home)
        // - "/home" (all homes)
        // - $HOME (user home)

        // The actual validation happens at runtime in commands/run.rs
        // This test documents the expected behavior

        let dangerous_paths = ["/", "/root", "/home"];
        for path in dangerous_paths {
            assert!(
                ["/", "/root", "/home"].contains(&path),
                "Path {} should be in dangerous list",
                path
            );
        }
    }
}

mod template_tests {
    use super::*;
    use flyboat::config::Paths;
    use flyboat::environment::{EnvironmentManager, EnvironmentSearch};
    use flyboat::template::{ProcessContext, process_templates};

    fn unwrap_single(search: EnvironmentSearch) -> std::rc::Rc<flyboat::environment::Environment> {
        match search {
            EnvironmentSearch::SingleMatch(env) => env,
            other => panic!(
                "Expected SingleMatch, got {:?}",
                std::mem::discriminant(&other)
            ),
        }
    }

    #[test]
    fn test_template_processing_from_dev_env_yaml() {
        let env = TestEnv::new();
        let env_dir = env.init_flyboat();

        // Create environment with templates
        let env_path = env_dir.join("test");
        fs::create_dir_all(&env_path).unwrap();

        // Write Dockerfile
        fs::write(env_path.join("Dockerfile"), "FROM alpine:latest\n").unwrap();

        // Write dev_env.yaml with templates
        let dev_env_yaml = r#"
name: test
templates:
  - source: "config.example.toml"
    overwrite: on_build
    variables:
      db_password:
        type: fixed
        value: "test_password_123"
      api_url:
        type: fixed
        value: "https://api.test.com"
"#;
        fs::write(env_path.join("dev_env.yaml"), dev_env_yaml).unwrap();

        // Write template file
        let template_content = r#"
[database]
password = "{{db_password}}"

[api]
url = "{{api_url}}"
"#;
        fs::write(env_path.join("config.example.toml"), template_content).unwrap();

        // Load environment
        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let found_env = unwrap_single(manager.get("test"));

        // Process templates
        process_templates(
            &found_env.path,
            &found_env.config.templates,
            ProcessContext::Build,
            false,
        )
        .unwrap();

        // Verify output
        let output_path = env_path.join("config.toml");
        assert!(output_path.exists(), "Output file should exist");

        let output_content = fs::read_to_string(&output_path).unwrap();
        assert!(output_content.contains("password = \"test_password_123\""));
        assert!(output_content.contains("url = \"https://api.test.com\""));
    }

    #[test]
    fn test_template_random_generation() {
        let env = TestEnv::new();
        let env_dir = env.init_flyboat();

        let env_path = env_dir.join("test-random");
        fs::create_dir_all(&env_path).unwrap();

        fs::write(env_path.join("Dockerfile"), "FROM alpine:latest\n").unwrap();

        let dev_env_yaml = r#"
name: test-random
templates:
  - source: "secret.example.txt"
    overwrite: on_build
    variables:
      random_key:
        type: random
        charset: alphanumeric
        length: 32
"#;
        fs::write(env_path.join("dev_env.yaml"), dev_env_yaml).unwrap();
        fs::write(env_path.join("secret.example.txt"), "KEY={{random_key}}").unwrap();

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let found_env = unwrap_single(manager.get("test-random"));

        process_templates(
            &found_env.path,
            &found_env.config.templates,
            ProcessContext::Build,
            false,
        )
        .unwrap();

        let output = fs::read_to_string(env_path.join("secret.txt")).unwrap();
        assert!(output.starts_with("KEY="));
        // Random value should be 32 characters
        let key = &output[4..];
        assert_eq!(key.len(), 32);
        assert!(key.chars().all(|c| c.is_ascii_alphanumeric()));
    }

    #[test]
    fn test_template_if_not_exists_skips() {
        let env = TestEnv::new();
        let env_dir = env.init_flyboat();

        let env_path = env_dir.join("test-skip");
        fs::create_dir_all(&env_path).unwrap();

        fs::write(env_path.join("Dockerfile"), "FROM alpine:latest\n").unwrap();

        let dev_env_yaml = r#"
name: test-skip
templates:
  - source: "config.example.toml"
    overwrite: if_not_exists
    variables:
      value:
        type: fixed
        value: "new_value"
"#;
        fs::write(env_path.join("dev_env.yaml"), dev_env_yaml).unwrap();
        fs::write(env_path.join("config.example.toml"), "VALUE={{value}}").unwrap();
        // Pre-create output file
        fs::write(env_path.join("config.toml"), "EXISTING_CONTENT").unwrap();

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let found_env = unwrap_single(manager.get("test-skip"));

        process_templates(
            &found_env.path,
            &found_env.config.templates,
            ProcessContext::Build,
            false,
        )
        .unwrap();

        // Should NOT be overwritten
        let output = fs::read_to_string(env_path.join("config.toml")).unwrap();
        assert_eq!(output, "EXISTING_CONTENT");
    }

    #[test]
    fn test_template_on_run_only_processes_in_run_context() {
        let env = TestEnv::new();
        let env_dir = env.init_flyboat();

        let env_path = env_dir.join("test-run");
        fs::create_dir_all(&env_path).unwrap();

        fs::write(env_path.join("Dockerfile"), "FROM alpine:latest\n").unwrap();

        let dev_env_yaml = r#"
name: test-run
templates:
  - source: "runtime.example.txt"
    overwrite: on_run
    variables:
      session_id:
        type: fixed
        value: "session123"
"#;
        fs::write(env_path.join("dev_env.yaml"), dev_env_yaml).unwrap();
        fs::write(
            env_path.join("runtime.example.txt"),
            "SESSION={{session_id}}",
        )
        .unwrap();

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();
        let found_env = unwrap_single(manager.get("test-run"));

        // Process in Build context - should NOT create output
        process_templates(
            &found_env.path,
            &found_env.config.templates,
            ProcessContext::Build,
            false,
        )
        .unwrap();
        assert!(
            !env_path.join("runtime.txt").exists(),
            "Output should NOT exist after Build context"
        );

        // Process in Run context - should create output
        process_templates(
            &found_env.path,
            &found_env.config.templates,
            ProcessContext::Run,
            false,
        )
        .unwrap();
        assert!(
            env_path.join("runtime.txt").exists(),
            "Output should exist after Run context"
        );

        let output = fs::read_to_string(env_path.join("runtime.txt")).unwrap();
        assert_eq!(output, "SESSION=session123");
    }
}

mod alias_tests {
    use super::*;
    use flyboat::config::Paths;
    use flyboat::environment::{EnvironmentManager, EnvironmentSearch};

    fn unwrap_single(search: EnvironmentSearch) -> std::rc::Rc<flyboat::environment::Environment> {
        match search {
            EnvironmentSearch::SingleMatch(env) => env,
            other => panic!(
                "Expected SingleMatch, got {:?}",
                std::mem::discriminant(&other)
            ),
        }
    }

    #[test]
    fn test_multiple_aliases() {
        let env = TestEnv::new();
        env.create_env(
            "python",
            r#"
name: python
aliases:
  - py
  - python3
  - pydev
"#,
        );

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // All aliases should resolve to python
        for alias in ["py", "python3", "pydev", "python"] {
            let found = unwrap_single(manager.get(alias));
            assert_eq!(found.name, "python", "Should find env by '{}'", alias);
        }
    }

    #[test]
    fn test_alias_priority_over_fuzzy() {
        let env = TestEnv::new();
        env.create_env("test", "name: test\naliases: [t]\n");

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // 't' should find by alias, not fuzzy match
        let result = unwrap_single(manager.get("t"));
        assert_eq!(result.name, "test");
    }

    #[test]
    fn test_alias_with_invalid_chars_rejects_environment() {
        let env = TestEnv::new();
        // Alias with invalid characters should cause the environment to NOT be registered
        env.create_env(
            "python",
            r#"
name: python
aliases:
  - py
  - my/alias
"#,
        );

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Environment should NOT be registered due to invalid alias
        assert!(
            manager.is_empty(),
            "Environment with invalid alias should not be registered"
        );
        assert!(
            matches!(manager.get("python"), EnvironmentSearch::NoFound),
            "Environment should not be found"
        );
    }

    #[test]
    fn test_alias_with_space_rejects_environment() {
        let env = TestEnv::new();
        // Alias with space should cause the environment to NOT be registered
        env.create_env(
            "rust",
            r#"
name: rust
aliases:
  - rs
  - "my alias"
"#,
        );

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Environment should NOT be registered due to invalid alias
        assert!(
            manager.is_empty(),
            "Environment with invalid alias should not be registered"
        );
    }

    #[test]
    fn test_valid_aliases_work_normally() {
        let env = TestEnv::new();
        // Valid aliases with only alphanumeric, '-', '_' should work
        env.create_env(
            "python",
            r#"
name: python
aliases:
  - py
  - python3
  - py_dev
  - py-dev
  - Py123
"#,
        );

        let paths = Paths::with_home(env.home());
        let manager = EnvironmentManager::with_paths(paths).unwrap();

        // Environment should be registered with all aliases
        assert!(!manager.is_empty());
        for alias in ["python", "py", "python3", "py_dev", "py-dev", "Py123"] {
            let result = unwrap_single(manager.get(alias));
            assert_eq!(result.name, "python");
        }
    }
}