nixy-rs 0.3.2

Homebrew-style wrapper for Nix using flake.nix
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
//! Flake.nix template generation.
//!
//! This module generates `flake.nix` content from the package state or profile config.
//! It handles:
//! - Standard nixpkgs packages
//! - Custom packages from external flakes
//! - Local packages (`.nix` files in `packages/` directory)
//! - Local flakes (subdirectories with `flake.nix`)
//!
//! The generated flake uses `buildEnv` to create a unified environment with
//! all installed packages.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;

use super::parser::collect_local_packages;
use super::{LocalFlake, LocalPackage};
use crate::error::Result;
use crate::nixy_config::ProfileConfig;
use crate::state::{CustomPackage, PackageState, ResolvedNixpkgPackage};

/// A package path entry with optional platform restrictions
struct PathEntry {
    /// Package name (variable name in the flake)
    name: String,
    /// Platform restrictions (None means all platforms)
    platforms: Option<Vec<String>>,
}

/// Intermediate representation for building flake content
struct FlakeBuilder {
    /// Additional flake inputs (beyond nixpkgs)
    inputs: String,
    /// Set of input names already added
    seen_inputs: HashSet<String>,
    /// Overlay expressions for pkgs customization
    overlays: String,
    /// Standard package entries (pkg = pkgs.pkg) - legacy packages
    standard_entries: String,
    /// Resolved package entries from Nixhub (with specific nixpkgs commits)
    resolved_entries: String,
    /// Local package entries
    local_entries: String,
    /// Custom package entries from external flakes
    custom_entries: String,
    /// Package names for buildEnv paths with platform restrictions
    buildenv_paths: Vec<PathEntry>,
}

impl FlakeBuilder {
    fn new() -> Self {
        Self {
            inputs: String::new(),
            seen_inputs: HashSet::new(),
            overlays: String::new(),
            standard_entries: String::new(),
            resolved_entries: String::new(),
            local_entries: String::new(),
            custom_entries: String::new(),
            buildenv_paths: Vec::new(),
        }
    }

    /// Add standard nixpkgs packages (legacy, from default nixpkgs)
    fn add_standard_packages(&mut self, packages: &[&String]) {
        let entries: Vec<String> = packages
            .iter()
            .map(|pkg| format!("          {} = pkgs.{};", pkg, pkg))
            .collect();

        if !entries.is_empty() {
            self.standard_entries = format!("{}\n", entries.join("\n"));
        }

        self.buildenv_paths
            .extend(packages.iter().map(|p| PathEntry {
                name: p.to_string(),
                platforms: None,
            }));
    }

    /// Add resolved nixpkgs packages (with specific commits from Nixhub)
    fn add_resolved_packages(&mut self, packages: &[ResolvedNixpkgPackage]) {
        if packages.is_empty() {
            return;
        }

        // Group packages by commit hash
        let mut by_commit: HashMap<&str, Vec<&ResolvedNixpkgPackage>> = HashMap::new();
        for pkg in packages {
            by_commit.entry(&pkg.commit_hash).or_default().push(pkg);
        }

        // Add inputs and entries for each commit
        for (commit, pkgs) in &by_commit {
            let input_name = format!("nixpkgs-{}", &commit[..8.min(commit.len())]);

            // Add input if not already seen
            if self.seen_inputs.insert(input_name.clone()) {
                self.inputs.push_str(&format!(
                    "    {}.url = \"github:NixOS/nixpkgs/{}\";\n",
                    input_name, commit
                ));
            }

            // Add package entries
            for pkg in pkgs {
                self.resolved_entries.push_str(&format!(
                    "          {} = inputs.{}.legacyPackages.${{system}}.{};\n",
                    pkg.name, input_name, pkg.attribute_path
                ));
                self.buildenv_paths.push(PathEntry {
                    name: pkg.name.clone(),
                    platforms: pkg.platforms.clone(),
                });
            }
        }
    }

    /// Add local flake-type packages from packages/ directory
    fn add_local_flakes(&mut self, flakes: &[LocalFlake]) {
        for flake in flakes {
            self.inputs.push_str(&format!(
                "    {}.url = \"path:./packages/{}\";\n",
                flake.name, flake.name
            ));
            self.seen_inputs.insert(flake.name.clone());
            self.local_entries.push_str(&format!(
                "          {} = inputs.{}.packages.${{system}}.default;\n",
                flake.name, flake.name
            ));
            self.buildenv_paths.push(PathEntry {
                name: flake.name.clone(),
                platforms: None,
            });
        }
    }

    /// Add local flake-type packages with absolute paths (for new nixy.json format)
    fn add_local_flakes_with_absolute_paths(
        &mut self,
        flakes: &[LocalFlake],
        packages_dir: Option<&Path>,
    ) {
        for flake in flakes {
            let path = if let Some(dir) = packages_dir {
                // Use a URL-style path for flake URLs, handling spaces in the path
                let abs_path = dir.join(&flake.name);

                // Check if flake.nix inside the directory is a symlink.
                // When Nix copies the flake to the store, it can't follow absolute symlinks,
                // so we need to resolve to the directory containing the actual flake.nix.
                let flake_nix_path = abs_path.join("flake.nix");
                let resolved_path = if flake_nix_path.is_symlink() {
                    // If flake.nix is a symlink, use its target's parent directory
                    flake_nix_path
                        .canonicalize()
                        .ok()
                        .and_then(|p| p.parent().map(|parent| parent.to_path_buf()))
                        .unwrap_or_else(|| abs_path.canonicalize().unwrap_or(abs_path))
                } else {
                    // Fall back to canonicalizing the directory itself.
                    // This handles the case where the package directory is a symlink.
                    abs_path.canonicalize().unwrap_or(abs_path)
                };

                let path_str = resolved_path.to_string_lossy();
                // Escape spaces in the path for the flake URL
                let escaped_path = path_str.replace(' ', "%20");
                format!("path:{}", escaped_path)
            } else {
                format!("path:./packages/{}", flake.name)
            };
            self.inputs
                .push_str(&format!("    {}.url = \"{}\";\n", flake.name, path));
            self.seen_inputs.insert(flake.name.clone());
            self.local_entries.push_str(&format!(
                "          {} = inputs.{}.packages.${{system}}.default;\n",
                flake.name, flake.name
            ));
            self.buildenv_paths.push(PathEntry {
                name: flake.name.clone(),
                platforms: None,
            });
        }
    }

    /// Add local .nix file packages from packages/ directory
    fn add_local_packages(&mut self, packages: &[LocalPackage]) {
        for pkg in packages {
            if let (Some(input_name), Some(input_url)) = (&pkg.input_name, &pkg.input_url) {
                if self.seen_inputs.insert(input_name.clone()) {
                    self.inputs
                        .push_str(&format!("    {}.url = \"{}\";\n", input_name, input_url));
                }
            }

            if let Some(overlay) = &pkg.overlay {
                self.overlays.push_str(&format!("          {}\n", overlay));
            }

            self.local_entries
                .push_str(&format!("          {} = {};\n", pkg.name, pkg.package_expr));
            self.buildenv_paths.push(PathEntry {
                name: pkg.name.clone(),
                platforms: None,
            });
        }
    }

    /// Add local .nix file packages with absolute paths (for new nixy.json format)
    fn add_local_packages_with_absolute_paths(
        &mut self,
        packages: &[LocalPackage],
        packages_dir: Option<&Path>,
    ) {
        for pkg in packages {
            if let (Some(input_name), Some(input_url)) = (&pkg.input_name, &pkg.input_url) {
                if self.seen_inputs.insert(input_name.clone()) {
                    self.inputs
                        .push_str(&format!("    {}.url = \"{}\";\n", input_name, input_url));
                }
            }

            if let Some(overlay) = &pkg.overlay {
                self.overlays.push_str(&format!("          {}\n", overlay));
            }

            // Update package expression to use absolute path if needed
            let package_expr = if let Some(dir) = packages_dir {
                let abs_path = dir.join(format!("{}.nix", pkg.name));
                // Try to resolve symlinks to actual paths for Nix compatibility.
                // canonicalize() can also fail for reasons other than broken symlinks
                // (for example, missing intermediate directories or permission issues),
                // in which case we intentionally fall back to the original abs_path.
                let resolved_path = abs_path.canonicalize().unwrap_or(abs_path);
                let path_str = resolved_path.to_string_lossy();
                // Only replace if the expression is a simple ./packages/<name>.nix reference
                if pkg.package_expr == format!("pkgs.callPackage ./packages/{}.nix {{}}", pkg.name)
                {
                    // Use proper Nix path syntax
                    if path_str.contains(' ') {
                        // For paths with spaces, use a quoted string path (Nix coerces strings to paths)
                        format!("pkgs.callPackage \"{}\" {{}}", path_str)
                    } else {
                        format!("pkgs.callPackage {} {{}}", path_str)
                    }
                } else {
                    pkg.package_expr.clone()
                }
            } else {
                pkg.package_expr.clone()
            };

            self.local_entries
                .push_str(&format!("          {} = {};\n", pkg.name, package_expr));
            self.buildenv_paths.push(PathEntry {
                name: pkg.name.clone(),
                platforms: None,
            });
        }
    }

    /// Add custom packages from external flakes
    fn add_custom_packages(&mut self, packages: &[CustomPackage]) {
        for pkg in packages {
            if self.seen_inputs.insert(pkg.input_name.clone()) {
                self.inputs.push_str(&format!(
                    "    {}.url = \"{}\";\n",
                    pkg.input_name, pkg.input_url
                ));
            }

            self.custom_entries.push_str(&format!(
                "          {} = inputs.{}.{}.${{system}}.{};\n",
                pkg.name,
                pkg.input_name,
                pkg.package_output,
                pkg.source_package_name()
            ));
            self.buildenv_paths.push(PathEntry {
                name: pkg.name.clone(),
                platforms: pkg.platforms.clone(),
            });
        }
    }

    /// Build the output function parameters
    fn build_output_params(&self) -> String {
        if self.seen_inputs.is_empty() {
            "self, nixpkgs".to_string()
        } else {
            let mut inputs_list: Vec<_> = self.seen_inputs.iter().cloned().collect();
            inputs_list.sort();
            format!("self, nixpkgs, {}", inputs_list.join(", "))
        }
    }

    /// Build the pkgs definition (with or without overlays)
    fn build_pkgs_definition(&self) -> (String, &'static str) {
        if self.overlays.is_empty() {
            (
                String::new(),
                "let pkgs = nixpkgs.legacyPackages.${system};",
            )
        } else {
            let overlays_content = format!("overlays = [\n{}        ];", self.overlays);
            let pkgs_def = format!(
                "pkgsFor = system: import nixpkgs {{
        inherit system;
        {}
      }};
",
                overlays_content
            );
            (pkgs_def, "let pkgs = pkgsFor system;")
        }
    }

    /// Generate the final flake.nix content
    fn build(self) -> String {
        let output_params = self.build_output_params();
        let (pkgs_def, pkgs_binding) = self.build_pkgs_definition();
        let (paths_content, _has_platform_conditionals) = self.build_paths_section_with_info();

        let paths_section = format!("paths = [\n{}            ];", paths_content);

        format!(
            r#"{{
  description = "nixy managed packages";

  inputs = {{
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
{all_inputs}  }};

  outputs = {{ {output_params} }}@inputs:
    let
      systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
      forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f system);
      {pkgs_def}
    in {{
      packages = forAllSystems (system:
        {pkgs_binding}
        in rec {{
{pkg_entries}{resolved_entries}{local_entries}{custom_entries}
          default = pkgs.buildEnv {{
            name = "nixy-env";
            {paths_section}
            extraOutputsToInstall = [ "man" "doc" "info" "dev" ];
          }};
        }});
    }};
}}
"#,
            all_inputs = self.inputs,
            output_params = output_params,
            pkgs_def = pkgs_def,
            pkgs_binding = pkgs_binding,
            pkg_entries = self.standard_entries,
            resolved_entries = self.resolved_entries,
            local_entries = self.local_entries,
            custom_entries = self.custom_entries,
            paths_section = paths_section,
        )
    }

    /// Build the buildEnv paths section and return whether it has platform conditionals
    fn build_paths_section_with_info(&self) -> (String, bool) {
        if self.buildenv_paths.is_empty() {
            return (String::new(), false);
        }

        // Group packages by their platform restrictions
        // None means all platforms, Some([...]) means specific platforms
        let mut universal: Vec<&str> = Vec::new();
        let mut by_platforms: HashMap<Vec<String>, Vec<&str>> = HashMap::new();

        for entry in &self.buildenv_paths {
            match &entry.platforms {
                None => universal.push(&entry.name),
                Some(platforms) => {
                    let mut sorted_platforms = platforms.clone();
                    sorted_platforms.sort();
                    by_platforms
                        .entry(sorted_platforms)
                        .or_default()
                        .push(&entry.name);
                }
            }
        }

        let has_conditionals = !by_platforms.is_empty();
        let mut result = String::new();

        // Add universal packages (no platform restriction)
        for pkg in &universal {
            result.push_str(&format!("              {}\n", pkg));
        }

        // Add platform-specific packages with lib.optionals
        let mut platform_groups: Vec<_> = by_platforms.into_iter().collect();
        platform_groups.sort_by(|a, b| a.0.cmp(&b.0));

        for (platforms, packages) in platform_groups {
            let platforms_str = platforms
                .iter()
                .map(|p| format!("\"{}\"", p))
                .collect::<Vec<_>>()
                .join(" ");
            let packages_str = packages
                .iter()
                .map(|p| format!("\n                {}", p))
                .collect::<Vec<_>>()
                .join("");
            result.push_str(&format!(
                "            ] ++ pkgs.lib.optionals (builtins.elem system [ {} ]) [{}\n",
                platforms_str, packages_str
            ));
        }

        (result, has_conditionals)
    }
}

/// Generate flake.nix content from package state
///
/// # Arguments
/// * `state` - The package state (legacy format)
/// * `flake_dir` - Optional flake directory for collecting local packages (legacy)
pub fn generate_flake(state: &PackageState, flake_dir: Option<&Path>) -> String {
    // Collect local packages if flake_dir is provided
    let (local_packages, local_flakes) = if let Some(dir) = flake_dir {
        let packages_dir = dir.join("packages");
        if packages_dir.exists() {
            collect_local_packages(&packages_dir)
        } else {
            (Vec::new(), Vec::new())
        }
    } else {
        (Vec::new(), Vec::new())
    };

    // Filter out local packages from legacy packages list
    let filtered_legacy_packages: Vec<&String> = state
        .packages
        .iter()
        .filter(|pkg| {
            !local_packages.iter().any(|lp| &lp.name == *pkg)
                && !local_flakes.iter().any(|lf| &lf.name == *pkg)
        })
        .collect();

    // Filter out local packages from resolved packages list
    let filtered_resolved_packages: Vec<ResolvedNixpkgPackage> = state
        .resolved_packages
        .iter()
        .filter(|pkg| {
            !local_packages.iter().any(|lp| lp.name == pkg.name)
                && !local_flakes.iter().any(|lf| lf.name == pkg.name)
        })
        .cloned()
        .collect();

    let mut builder = FlakeBuilder::new();
    builder.add_standard_packages(&filtered_legacy_packages);
    builder.add_resolved_packages(&filtered_resolved_packages);
    builder.add_local_flakes(&local_flakes);
    builder.add_local_packages(&local_packages);
    builder.add_custom_packages(&state.custom_packages);
    builder.build()
}

/// Generate flake.nix content from profile config
///
/// # Arguments
/// * `profile` - The profile configuration (new nixy.json format)
/// * `global_packages_dir` - Optional global packages directory for local packages
/// * `_flake_dir` - Reserved for future use
pub fn generate_flake_from_profile(
    profile: &ProfileConfig,
    global_packages_dir: Option<&Path>,
    _flake_dir: &Path,
) -> String {
    // Collect local packages from global packages directory
    let (local_packages, local_flakes) = if let Some(dir) = global_packages_dir {
        if dir.exists() {
            collect_local_packages_with_paths(dir)
        } else {
            (Vec::new(), Vec::new())
        }
    } else {
        (Vec::new(), Vec::new())
    };

    // Filter out local packages from legacy packages list
    let filtered_legacy_packages: Vec<&String> = profile
        .packages
        .iter()
        .filter(|pkg| {
            !local_packages.iter().any(|lp| &lp.name == *pkg)
                && !local_flakes.iter().any(|lf| &lf.name == *pkg)
        })
        .collect();

    // Filter out local packages from resolved packages list
    let filtered_resolved_packages: Vec<ResolvedNixpkgPackage> = profile
        .resolved_packages
        .iter()
        .filter(|pkg| {
            !local_packages.iter().any(|lp| lp.name == pkg.name)
                && !local_flakes.iter().any(|lf| lf.name == pkg.name)
        })
        .cloned()
        .collect();

    let mut builder = FlakeBuilder::new();
    builder.add_standard_packages(&filtered_legacy_packages);
    builder.add_resolved_packages(&filtered_resolved_packages);
    builder.add_local_flakes_with_absolute_paths(&local_flakes, global_packages_dir);
    builder.add_local_packages_with_absolute_paths(&local_packages, global_packages_dir);
    builder.add_custom_packages(&profile.custom_packages);
    builder.build()
}

/// Collect local packages from the packages directory
fn collect_local_packages_with_paths(packages_dir: &Path) -> (Vec<LocalPackage>, Vec<LocalFlake>) {
    collect_local_packages(packages_dir)
}

/// Regenerate flake.nix from state (legacy format)
pub fn regenerate_flake(flake_dir: &Path, state: &PackageState) -> Result<()> {
    let flake_path = flake_dir.join("flake.nix");
    fs::create_dir_all(flake_dir)?;
    let content = generate_flake(state, Some(flake_dir));
    fs::write(&flake_path, content)?;
    Ok(())
}

/// Regenerate flake.nix from profile config (new nixy.json format)
pub fn regenerate_flake_from_profile(
    flake_dir: &Path,
    profile: &ProfileConfig,
    global_packages_dir: Option<&Path>,
) -> Result<()> {
    let flake_path = flake_dir.join("flake.nix");
    fs::create_dir_all(flake_dir)?;
    let content = generate_flake_from_profile(profile, global_packages_dir, flake_dir);
    fs::write(&flake_path, content)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::{CustomPackage, ResolvedNixpkgPackage};

    #[test]
    fn test_generate_empty_flake() {
        let state = PackageState::default();
        let flake = generate_flake(&state, None);

        // Should have buildEnv
        assert!(flake.contains("default = pkgs.buildEnv"));
        assert!(flake.contains("name = \"nixy-env\""));
        assert!(flake.contains("extraOutputsToInstall"));

        // Should NOT have markers
        assert!(!flake.contains("# [nixy:"));
        assert!(!flake.contains("# [/nixy:"));

        // Should NOT have devShells
        assert!(!flake.contains("devShells"));
    }

    #[test]
    fn test_generate_flake_with_packages() {
        let mut state = PackageState::default();
        state.add_package("ripgrep");
        state.add_package("fzf");
        state.add_package("bat");

        let flake = generate_flake(&state, None);

        // Should have package entries
        assert!(flake.contains("ripgrep = pkgs.ripgrep;"));
        assert!(flake.contains("fzf = pkgs.fzf;"));
        assert!(flake.contains("bat = pkgs.bat;"));

        // Should have packages in paths
        assert!(flake.contains("ripgrep"));
        assert!(flake.contains("fzf"));
        assert!(flake.contains("bat"));
    }

    #[test]
    fn test_generate_flake_with_custom_packages() {
        let mut state = PackageState::default();
        state.add_custom_package(CustomPackage {
            name: "neovim".to_string(),
            input_name: "neovim-nightly".to_string(),
            input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
            package_output: "packages".to_string(),
            source_name: None,
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Should have custom input
        assert!(
            flake.contains("neovim-nightly.url = \"github:nix-community/neovim-nightly-overlay\"")
        );

        // Should have custom package entry
        assert!(flake.contains("neovim = inputs.neovim-nightly.packages.${system}.neovim;"));

        // Should have neovim in paths
        assert!(flake.contains("neovim"));
    }

    #[test]
    fn test_flake_has_correct_nixpkgs_url() {
        let state = PackageState::default();
        let flake = generate_flake(&state, None);
        assert!(flake.contains("nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\""));
    }

    #[test]
    fn test_flake_has_all_systems() {
        let state = PackageState::default();
        let flake = generate_flake(&state, None);
        assert!(flake.contains("x86_64-linux"));
        assert!(flake.contains("aarch64-linux"));
        assert!(flake.contains("x86_64-darwin"));
        assert!(flake.contains("aarch64-darwin"));
    }

    #[test]
    fn test_flake_uses_legacy_packages() {
        let state = PackageState::default();
        let flake = generate_flake(&state, None);
        assert!(flake.contains("nixpkgs.legacyPackages.${system}"));
    }

    #[test]
    fn test_buildenv_has_extra_outputs() {
        let state = PackageState::default();
        let flake = generate_flake(&state, None);
        assert!(flake.contains("extraOutputsToInstall = [ \"man\" \"doc\" \"info\" \"dev\" ]"));
    }

    #[test]
    fn test_flake_has_no_devshells() {
        let mut state = PackageState::default();
        state.add_package("ripgrep");
        let flake = generate_flake(&state, None);

        // Flakes should NOT have devShells
        assert!(!flake.contains("devShells"));
        // But should have packages section
        assert!(flake.contains("packages = forAllSystems"));
    }

    #[test]
    fn test_flake_has_no_markers() {
        let mut state = PackageState::default();
        state.add_package("hello");
        state.add_custom_package(CustomPackage {
            name: "neovim".to_string(),
            input_name: "neovim-nightly".to_string(),
            input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
            package_output: "packages".to_string(),
            source_name: None,
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Should NOT have any markers
        assert!(!flake.contains("# [nixy:"));
        assert!(!flake.contains("# [/nixy:"));
    }

    #[test]
    fn test_multiple_custom_packages_share_input() {
        let mut state = PackageState::default();
        state.add_custom_package(CustomPackage {
            name: "hello".to_string(),
            input_name: "nixpkgs-unstable".to_string(),
            input_url: "github:NixOS/nixpkgs/nixos-unstable".to_string(),
            package_output: "legacyPackages".to_string(),
            source_name: None,
            platforms: None,
        });
        state.add_custom_package(CustomPackage {
            name: "world".to_string(),
            input_name: "nixpkgs-unstable".to_string(),
            input_url: "github:NixOS/nixpkgs/nixos-unstable".to_string(),
            package_output: "legacyPackages".to_string(),
            source_name: None,
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Input should only appear once
        let count = flake.matches("nixpkgs-unstable.url").count();
        assert_eq!(count, 1, "Input should only appear once");
    }

    #[test]
    fn test_buildenv_contains_all_packages() {
        let mut state = PackageState::default();
        state.add_package("ripgrep");
        state.add_package("fzf");
        state.add_custom_package(CustomPackage {
            name: "neovim".to_string(),
            input_name: "neovim-nightly".to_string(),
            input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
            package_output: "packages".to_string(),
            source_name: None,
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Extract paths section
        let paths_start = flake.find("paths = [").unwrap();
        let paths_end = flake[paths_start..].find("];").unwrap();
        let paths_section = &flake[paths_start..paths_start + paths_end];

        assert!(paths_section.contains("ripgrep"));
        assert!(paths_section.contains("fzf"));
        assert!(paths_section.contains("neovim"));
    }

    #[test]
    fn test_empty_flake_has_empty_buildenv() {
        let state = PackageState::default();
        let flake = generate_flake(&state, None);

        // Empty flake should have buildEnv structure with empty paths
        assert!(flake.contains("default = pkgs.buildEnv"));
        assert!(flake.contains("paths = ["));
        assert!(flake.contains("extraOutputsToInstall = [ \"man\" \"doc\" \"info\" \"dev\" ]"));
    }

    #[test]
    fn test_generate_flake_with_resolved_packages() {
        let mut state = PackageState::default();
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "nodejs".to_string(),
            version_spec: Some("20".to_string()),
            resolved_version: "20.11.0".to_string(),
            attribute_path: "nodejs_20".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Should have nixpkgs input with commit hash
        assert!(flake.contains("nixpkgs-abc123de.url = \"github:NixOS/nixpkgs/abc123def456\""));

        // Should have package entry using attribute_path
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );

        // Should have nodejs in paths
        let paths_start = flake.find("paths = [").unwrap();
        let paths_end = flake[paths_start..].find("];").unwrap();
        let paths_section = &flake[paths_start..paths_start + paths_end];
        assert!(paths_section.contains("nodejs"));
    }

    #[test]
    fn test_resolved_packages_share_commit_input() {
        let mut state = PackageState::default();
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "nodejs".to_string(),
            version_spec: Some("20".to_string()),
            resolved_version: "20.11.0".to_string(),
            attribute_path: "nodejs_20".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: None,
        });
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "python".to_string(),
            version_spec: Some("3.11".to_string()),
            resolved_version: "3.11.5".to_string(),
            attribute_path: "python311".to_string(),
            commit_hash: "abc123def456".to_string(), // Same commit
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Input should only appear once
        let count = flake.matches("nixpkgs-abc123de.url").count();
        assert_eq!(count, 1, "Same commit input should only appear once");

        // Both packages should use the same input
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );
        assert!(
            flake.contains("python = inputs.nixpkgs-abc123de.legacyPackages.${system}.python311;")
        );
    }

    #[test]
    fn test_resolved_packages_different_commits() {
        let mut state = PackageState::default();
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "nodejs".to_string(),
            version_spec: Some("20".to_string()),
            resolved_version: "20.11.0".to_string(),
            attribute_path: "nodejs_20".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: None,
        });
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "python".to_string(),
            version_spec: Some("3.11".to_string()),
            resolved_version: "3.11.5".to_string(),
            attribute_path: "python311".to_string(),
            commit_hash: "xyz789ghi012".to_string(), // Different commit
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Should have two different nixpkgs inputs
        assert!(flake.contains("nixpkgs-abc123de.url = \"github:NixOS/nixpkgs/abc123def456\""));
        assert!(flake.contains("nixpkgs-xyz789gh.url = \"github:NixOS/nixpkgs/xyz789ghi012\""));

        // Each package should use its own input
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );
        assert!(
            flake.contains("python = inputs.nixpkgs-xyz789gh.legacyPackages.${system}.python311;")
        );
    }

    #[test]
    fn test_mixed_legacy_and_resolved_packages() {
        let mut state = PackageState::default();
        // Legacy package (uses default nixpkgs)
        state.add_package("ripgrep");
        // Resolved package (uses specific commit)
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "nodejs".to_string(),
            version_spec: Some("20".to_string()),
            resolved_version: "20.11.0".to_string(),
            attribute_path: "nodejs_20".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: None,
        });

        let flake = generate_flake(&state, None);

        // Should have default nixpkgs for legacy
        assert!(flake.contains("nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\""));
        assert!(flake.contains("ripgrep = pkgs.ripgrep;"));

        // Should have specific commit for resolved
        assert!(flake.contains("nixpkgs-abc123de.url = \"github:NixOS/nixpkgs/abc123def456\""));
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );

        // Both should be in paths
        let paths_start = flake.find("paths = [").unwrap();
        let paths_end = flake[paths_start..].find("];").unwrap();
        let paths_section = &flake[paths_start..paths_start + paths_end];
        assert!(paths_section.contains("ripgrep"));
        assert!(paths_section.contains("nodejs"));
    }

    #[test]
    fn test_platform_specific_resolved_package() {
        let mut state = PackageState::default();
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "terminal-notifier".to_string(),
            version_spec: None,
            resolved_version: "2.0.0".to_string(),
            attribute_path: "terminal-notifier".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: Some(vec![
                "aarch64-darwin".to_string(),
                "x86_64-darwin".to_string(),
            ]),
        });

        let flake = generate_flake(&state, None);

        // Should have conditional path using lib.optionals
        assert!(
            flake.contains("lib.optionals"),
            "Should use lib.optionals for platform-specific packages"
        );
        assert!(
            flake.contains("aarch64-darwin") && flake.contains("x86_64-darwin"),
            "Should include darwin platforms"
        );
        assert!(
            flake.contains("terminal-notifier"),
            "Should include the package name"
        );
    }

    #[test]
    fn test_mixed_universal_and_platform_specific() {
        let mut state = PackageState::default();
        // Universal package
        state.add_package("hello");
        // Platform-specific package
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "terminal-notifier".to_string(),
            version_spec: None,
            resolved_version: "2.0.0".to_string(),
            attribute_path: "terminal-notifier".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: Some(vec![
                "aarch64-darwin".to_string(),
                "x86_64-darwin".to_string(),
            ]),
        });

        let flake = generate_flake(&state, None);

        // Universal package should be in the main paths list
        assert!(flake.contains("hello"));
        // Platform-specific should use lib.optionals
        assert!(flake.contains("lib.optionals"));
        assert!(flake.contains("terminal-notifier"));
    }

    #[test]
    fn test_platform_specific_custom_package() {
        let mut state = PackageState::default();
        state.add_custom_package(CustomPackage {
            name: "neovim".to_string(),
            input_name: "neovim-nightly".to_string(),
            input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
            package_output: "packages".to_string(),
            source_name: None,
            platforms: Some(vec![
                "x86_64-linux".to_string(),
                "aarch64-linux".to_string(),
            ]),
        });

        let flake = generate_flake(&state, None);

        // Should have conditional path
        assert!(flake.contains("lib.optionals"));
        assert!(flake.contains("x86_64-linux") && flake.contains("aarch64-linux"));
        assert!(flake.contains("neovim"));
    }

    #[test]
    fn test_generated_flake_has_balanced_brackets() {
        /// Validates that a string has balanced brackets
        fn validate_brackets(s: &str) -> std::result::Result<(), String> {
            let mut curly = 0i32;
            let mut square = 0i32;
            let mut paren = 0i32;

            for (i, c) in s.chars().enumerate() {
                match c {
                    '{' => curly += 1,
                    '}' => {
                        curly -= 1;
                        if curly < 0 {
                            return Err(format!("Unmatched '}}' at position {}", i));
                        }
                    }
                    '[' => square += 1,
                    ']' => {
                        square -= 1;
                        if square < 0 {
                            return Err(format!("Unmatched ']' at position {}", i));
                        }
                    }
                    '(' => paren += 1,
                    ')' => {
                        paren -= 1;
                        if paren < 0 {
                            return Err(format!("Unmatched ')' at position {}", i));
                        }
                    }
                    _ => {}
                }
            }

            if curly != 0 {
                return Err(format!("Unbalanced curly braces: {} unclosed", curly));
            }
            if square != 0 {
                return Err(format!("Unbalanced square brackets: {} unclosed", square));
            }
            if paren != 0 {
                return Err(format!("Unbalanced parentheses: {} unclosed", paren));
            }

            Ok(())
        }

        // Test case 1: Empty state
        let state = PackageState::default();
        let flake = generate_flake(&state, None);
        validate_brackets(&flake).expect("Empty state should produce balanced brackets");

        // Test case 2: Standard packages only
        let mut state = PackageState::default();
        state.add_package("hello");
        state.add_package("ripgrep");
        let flake = generate_flake(&state, None);
        validate_brackets(&flake).expect("Standard packages should produce balanced brackets");

        // Test case 3: Resolved packages only (universal)
        let mut state = PackageState::default();
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "hello".to_string(),
            version_spec: Some("2.10".to_string()),
            resolved_version: "2.10".to_string(),
            attribute_path: "hello".to_string(),
            commit_hash: "abc123".to_string(),
            platforms: None,
        });
        let flake = generate_flake(&state, None);
        validate_brackets(&flake).expect("Resolved packages should produce balanced brackets");

        // Test case 4: Platform-specific resolved package
        let mut state = PackageState::default();
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "terminal-notifier".to_string(),
            version_spec: None,
            resolved_version: "2.0.0".to_string(),
            attribute_path: "terminal-notifier".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: Some(vec![
                "aarch64-darwin".to_string(),
                "x86_64-darwin".to_string(),
            ]),
        });
        let flake = generate_flake(&state, None);
        validate_brackets(&flake)
            .expect("Platform-specific resolved package should produce balanced brackets");

        // Test case 5: Mixed universal and platform-specific
        let mut state = PackageState::default();
        state.add_package("hello");
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "terminal-notifier".to_string(),
            version_spec: None,
            resolved_version: "2.0.0".to_string(),
            attribute_path: "terminal-notifier".to_string(),
            commit_hash: "abc123def456".to_string(),
            platforms: Some(vec![
                "aarch64-darwin".to_string(),
                "x86_64-darwin".to_string(),
            ]),
        });
        let flake = generate_flake(&state, None);
        validate_brackets(&flake)
            .expect("Mixed universal and platform-specific should produce balanced brackets");

        // Test case 6: Custom package with platform restrictions
        let mut state = PackageState::default();
        state.add_custom_package(CustomPackage {
            name: "neovim".to_string(),
            input_name: "neovim-nightly".to_string(),
            input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
            package_output: "packages".to_string(),
            source_name: None,
            platforms: Some(vec![
                "x86_64-linux".to_string(),
                "aarch64-linux".to_string(),
            ]),
        });
        let flake = generate_flake(&state, None);
        validate_brackets(&flake)
            .expect("Custom package with platforms should produce balanced brackets");

        // Test case 7: Universal custom package
        let mut state = PackageState::default();
        state.add_custom_package(CustomPackage {
            name: "neovim".to_string(),
            input_name: "neovim-nightly".to_string(),
            input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
            package_output: "packages".to_string(),
            source_name: None,
            platforms: None,
        });
        let flake = generate_flake(&state, None);
        validate_brackets(&flake)
            .expect("Universal custom package should produce balanced brackets");

        // Test case 8: Complex mixed scenario
        let mut state = PackageState::default();
        state.add_package("hello");
        state.add_package("ripgrep");
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "jq".to_string(),
            version_spec: Some("1.6".to_string()),
            resolved_version: "1.6".to_string(),
            attribute_path: "jq".to_string(),
            commit_hash: "abc123".to_string(),
            platforms: None,
        });
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "terminal-notifier".to_string(),
            version_spec: None,
            resolved_version: "2.0.0".to_string(),
            attribute_path: "terminal-notifier".to_string(),
            commit_hash: "def456".to_string(),
            platforms: Some(vec!["aarch64-darwin".to_string()]),
        });
        state.add_custom_package(CustomPackage {
            name: "neovim".to_string(),
            input_name: "neovim-nightly".to_string(),
            input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
            package_output: "packages".to_string(),
            source_name: None,
            platforms: Some(vec!["x86_64-linux".to_string()]),
        });
        let flake = generate_flake(&state, None);
        validate_brackets(&flake).expect("Complex mixed scenario should produce balanced brackets");
    }

    #[test]
    #[cfg(unix)]
    fn test_local_flake_symlink_resolution() {
        use std::os::unix::fs::symlink;
        use tempfile::tempdir;

        // Create temp dirs: target dir with flake.nix, packages dir with symlink
        let temp = tempdir().unwrap();
        let target_dir = temp.path().join("real-package");
        let packages_dir = temp.path().join("packages");

        fs::create_dir_all(&target_dir).unwrap();
        fs::create_dir_all(&packages_dir).unwrap();
        fs::write(target_dir.join("flake.nix"), "{ }").unwrap();

        // Create symlink: packages/my-package -> real-package
        symlink(&target_dir, packages_dir.join("my-package")).unwrap();

        // Create a local flake entry
        let local_flakes = vec![LocalFlake {
            name: "my-package".to_string(),
        }];

        // Build using the method that resolves absolute paths
        let mut builder = FlakeBuilder::new();
        builder.add_local_flakes_with_absolute_paths(&local_flakes, Some(&packages_dir));

        // The generated input should use the resolved (real) path, not the symlink
        let resolved_target = target_dir.canonicalize().unwrap();
        let expected_path = format!("path:{}", resolved_target.to_string_lossy());
        assert!(
            builder.inputs.contains(&expected_path),
            "Expected path '{}' in inputs, got: {}",
            expected_path,
            builder.inputs
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_local_flake_with_symlinked_flake_nix() {
        use std::os::unix::fs::symlink;
        use tempfile::tempdir;

        // Create temp dirs: target flake with flake.nix, packages dir with symlinked flake.nix
        let temp = tempdir().unwrap();
        let target_flake_dir = temp.path().join("real-flake");
        let packages_dir = temp.path().join("packages");
        let symlink_dir = packages_dir.join("my-flake");

        fs::create_dir_all(&target_flake_dir).unwrap();
        fs::create_dir_all(&symlink_dir).unwrap();
        fs::write(target_flake_dir.join("flake.nix"), "{ }").unwrap();

        // Create symlink: packages/my-flake/flake.nix -> real-flake/flake.nix
        symlink(
            target_flake_dir.join("flake.nix"),
            symlink_dir.join("flake.nix"),
        )
        .unwrap();

        let local_flakes = vec![LocalFlake {
            name: "my-flake".to_string(),
        }];

        let mut builder = FlakeBuilder::new();
        builder.add_local_flakes_with_absolute_paths(&local_flakes, Some(&packages_dir));

        // Should use the target directory (where the actual flake.nix lives), not the symlink's directory
        let resolved_target = target_flake_dir.canonicalize().unwrap();
        let expected_path = format!("path:{}", resolved_target.to_string_lossy());
        assert!(
            builder.inputs.contains(&expected_path),
            "Expected path '{}' in inputs, got: {}",
            expected_path,
            builder.inputs
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_local_package_nix_file_symlink_resolution() {
        use std::os::unix::fs::symlink;
        use tempfile::tempdir;

        // Create temp dirs: target dir with .nix file, packages dir with symlink
        let temp = tempdir().unwrap();
        let target_file = temp.path().join("real-package.nix");
        let packages_dir = temp.path().join("packages");

        fs::create_dir_all(&packages_dir).unwrap();
        fs::write(&target_file, "{ pkgs }: pkgs.hello").unwrap();

        // Create symlink: packages/my-package.nix -> real-package.nix
        symlink(&target_file, packages_dir.join("my-package.nix")).unwrap();

        // Create a local package entry
        let local_packages = vec![LocalPackage {
            name: "my-package".to_string(),
            package_expr: "pkgs.callPackage ./packages/my-package.nix {}".to_string(),
            input_name: None,
            input_url: None,
            overlay: None,
        }];

        // Build using the method that resolves absolute paths
        let mut builder = FlakeBuilder::new();
        builder.add_local_packages_with_absolute_paths(&local_packages, Some(&packages_dir));

        // The generated entry should use the resolved (real) path, not the symlink
        let resolved_target = target_file.canonicalize().unwrap();
        let expected_expr = format!(
            "pkgs.callPackage {} {{}}",
            resolved_target.to_string_lossy()
        );
        assert!(
            builder.local_entries.contains(&expected_expr),
            "Expected expression '{}' in local_entries, got: {}",
            expected_expr,
            builder.local_entries
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_symlink_fallback_on_broken_link() {
        use std::os::unix::fs::symlink;
        use tempfile::tempdir;

        // Create temp dir with broken symlink
        let temp = tempdir().unwrap();
        let packages_dir = temp.path().join("packages");
        fs::create_dir_all(&packages_dir).unwrap();

        // Create broken symlink (target doesn't exist)
        let nonexistent = temp.path().join("nonexistent");
        symlink(&nonexistent, packages_dir.join("broken-package")).unwrap();

        // Create a local flake entry for the broken symlink
        let local_flakes = vec![LocalFlake {
            name: "broken-package".to_string(),
        }];

        // Build using the method that resolves absolute paths
        let mut builder = FlakeBuilder::new();
        builder.add_local_flakes_with_absolute_paths(&local_flakes, Some(&packages_dir));

        // Should fall back to the original path (symlink path) when canonicalize fails
        let expected_path = format!(
            "path:{}",
            packages_dir.join("broken-package").to_string_lossy()
        );
        assert!(
            builder.inputs.contains(&expected_path),
            "Expected fallback path '{}' in inputs, got: {}",
            expected_path,
            builder.inputs
        );
    }
}