xbp 10.46.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
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
//! Init command module
//!
//! Guides the user through creating a project-local XBP configuration
//! under `.xbp/` by detecting framework, port, and sensible defaults.
//! Writes the preferred project config (`.xbp/xbp.toml` by default; keeps
//! existing yaml/json paths) and optionally syncs legacy JSON when present.
//! Then always opens the interactive setup wizard.
//! Optionally commits/pushes the changes to git.

use crate::cli::auto_commit::{commit_paths, print_skip, AutoCommitRequest, AutoCommitResult};
use crate::commands::init_wizard::run_init_setup_wizard;
use crate::commands::project_services::{
    auto_populate_services, discover_service_version_targets_for_project,
};
use crate::strategies::deployment_config::XbpConfig;
use crate::strategies::project_detector::{
    infer_project_name as shared_infer_project_name, DeploymentRecommendations, PackageJsonInfo,
    ProjectDetector, ProjectType,
};
use crate::strategies::{
    legacy_service_from_config, normalize_config_paths_for_persistence, validate_services,
    DeploymentConfig, ServiceCommands, ServiceConfig,
};
use crate::utils::{
    collapse_project_path, default_project_config_path, find_xbp_config_upwards,
    load_project_xbp_ignore, migrate_package_json_pnpm_settings, parse_env_file,
    resolve_project_config_write_path, to_env_references, FoundXbpConfig,
    DEFAULT_PROJECT_CONFIG_KIND, DEFAULT_PROJECT_CONFIG_RELATIVE,
};

use colored::Colorize;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::{env, fs};

use dialoguer::{Confirm, Input, Select};
use regex::Regex;
use tokio::process::Command;
use tracing::debug;

const SERVICE_DISCOVERY_MARKERS: &[&str] = &[
    "package.json",
    "Cargo.toml",
    "pyproject.toml",
    "requirements.txt",
    "setup.py",
    "Dockerfile",
    "docker-compose.yml",
    "docker-compose.yaml",
    "compose.yml",
    "compose.yaml",
    "railway.json",
    "railway.toml",
    "vercel.json",
    "go.mod",
];

const SERVICE_VERSION_MANIFESTS: &[&str] = &[
    "package.json",
    "Cargo.toml",
    "pyproject.toml",
    "composer.json",
    "deno.json",
    "deno.jsonc",
    "Chart.yaml",
    "app.json",
    "manifest.json",
    "pom.xml",
    "build.gradle",
    "build.gradle.kts",
];

pub async fn run_init(_debug: bool) -> Result<(), String> {
    let current_dir: PathBuf =
        env::current_dir().map_err(|e| format!("Failed to read current directory: {}", e))?;

    let existing = find_xbp_config_upwards(&current_dir);
    // Greenfield + full re-detect always write the preferred format (`.xbp/xbp.toml`).
    // Only "open wizard" on an existing file keeps that file's path/format.
    let mut write_preferred_toml = existing.is_none();
    if let Some(found) = existing.as_ref() {
        if found.project_root != current_dir {
            return run_nested_service_init(found.clone(), current_dir).await;
        }

        // Config already present: open the wizard by default (do not exit on "no overwrite").
        let choice = Select::new()
            .with_prompt(format!(
                "XBP config already exists at {} — what next?",
                found.location
            ))
            .items(&[
                "Open setup wizard (release, Discord, publish, Workers, …)",
                "Re-detect project and overwrite base config as .xbp/xbp.toml, then open wizard",
                "Cancel",
            ])
            .default(0)
            .interact()
            .map_err(|e| format!("Prompt failed: {}", e))?;

        match choice {
            0 => {
                return finish_init_with_wizard(
                    &found.project_root,
                    &found.config_path,
                    DeploymentConfig::load_xbp_config(Some(found.config_path.clone())).await?,
                    vec![found.config_path.clone()],
                )
                .await;
            }
            1 => {
                // Fall through to full re-detect + wizard; write preferred `.xbp/xbp.toml`.
                write_preferred_toml = true;
            }
            _ => return Ok(()),
        }
    }

    let project_type: ProjectType = ProjectDetector::detect_project_type(&current_dir)
        .await
        .unwrap_or(ProjectType::Unknown);
    debug!(?project_type, "Detected project type");

    let recommendations: DeploymentRecommendations =
        ProjectDetector::get_deployment_recommendations(&current_dir, &project_type);
    let inferred_name: String = infer_project_name(&project_type, &current_dir, &recommendations);
    let app_type_guess: Option<String> = infer_app_type(&project_type);
    let port_guess: u16 = detect_port(&current_dir, &project_type, &recommendations);
    let env_vars: HashMap<String, String> = detect_environment_from_env_files(&current_dir);

    let project_name: String = Input::new()
        .with_prompt("Project name")
        .with_initial_text(inferred_name)
        .interact_text()
        .map_err(|e| format!("Prompt failed: {}", e))?;

    let app_type: String =
        select_app_type(app_type_guess.clone()).map_err(|e| format!("Prompt failed: {}", e))?;

    let port: u16 = Input::new()
        .with_prompt("Primary port")
        .default(port_guess)
        .interact_text()
        .map_err(|e| format!("Prompt failed: {}", e))?;

    let build_dir: String = collapse_project_path(&current_dir, &current_dir.to_string_lossy());

    let mut config: XbpConfig = XbpConfig {
        project_name,
        version: "0.1.0".to_string(),
        port,
        build_dir,
        app_type: Some(app_type.clone()),
        build_command: recommendations.build_command.clone(),
        start_command: recommendations.start_command.clone(),
        install_command: recommendations.install_command.clone(),
        environment: if env_vars.is_empty() {
            None
        } else {
            Some(env_vars)
        },
        services: None,
        openapi: None,
        workers: None,
        systemd_service_name: None,
        systemd: None,
        kafka_brokers: None,
        kafka_topic: None,
        kafka_public_url: None,
        log_files: None,
        monitor_url: None,
        monitor_method: None,
        monitor_expected_code: None,
        monitor_interval: None,
        database: None,
        oci: None,
        kubernetes: None,
        deploy: None,
        target: Some(app_type),
        branch: current_git_branch().await,
        crate_name: None,
        npm_script: None,
        port_storybook: None,
        url: None,
        url_storybook: None,
        linear: None,
        github: None,
        publish: None,
        version_targets: Vec::new(),
        version_domains: Vec::new(),
        ignore_paths: Vec::new(),
        watch_ignore_paths: Vec::new(),
        versioning_disabled: Vec::new(),
        release_disabled: Vec::new(),
        versioning: None,
        discord: None,
    };
    auto_populate_services(&mut config, &current_dir, &project_type).await?;

    let config_path: PathBuf = if write_preferred_toml {
        default_project_config_path(&current_dir, DEFAULT_PROJECT_CONFIG_KIND)
    } else {
        resolve_project_config_write_path(&current_dir, existing.as_ref())
    };
    let mut written_paths: Vec<PathBuf> = write_configs(&config, &current_dir, &config_path)?;
    if write_preferred_toml {
        if let Some(retired) = retire_non_primary_project_configs(&current_dir, &config_path) {
            println!(
                "{} {} → {}",
                "migrated".bright_cyan().bold(),
                retired.display().to_string().dimmed(),
                DEFAULT_PROJECT_CONFIG_RELATIVE.bright_white()
            );
        }
    }

    // pnpm 11+ ignores package.json#pnpm; move settings into pnpm-workspace.yaml.
    match migrate_package_json_pnpm_settings(&current_dir) {
        Ok(migration) if !migration.changed_paths.is_empty() => {
            for note in &migration.notes {
                println!("{} {}", "pnpm".bright_cyan().bold(), note.bright_white());
            }
            written_paths.extend(migration.changed_paths);
        }
        Ok(_) => {}
        Err(error) => {
            println!(
                "{} {}",
                "pnpm".bright_yellow().bold(),
                format!("package.json migration skipped: {error}").dimmed()
            );
        }
    }

    let legacy_json_path: PathBuf = config_path
        .parent()
        .map(|parent| parent.join("xbp.json"))
        .ok_or_else(|| "Invalid project config path".to_string())?;
    if legacy_json_path.exists() && legacy_json_path != config_path {
        println!(
            "Created {} (synced legacy {})",
            config_path.display(),
            legacy_json_path.display()
        );
    } else {
        println!("Created {}", config_path.display());
    }

    finish_init_with_wizard(&current_dir, &config_path, config, written_paths).await
}

async fn finish_init_with_wizard(
    project_root: &Path,
    config_path: &Path,
    mut config: XbpConfig,
    mut written_paths: Vec<PathBuf>,
) -> Result<(), String> {
    if !written_paths.iter().any(|p| p == config_path) {
        written_paths.push(config_path.to_path_buf());
    }

    // Full interactive setup: versioning, cargo-dist, publish, Workers, OCI/K8s, Discord, …
    match run_init_setup_wizard(project_root, &mut config).await {
        Ok(extra_paths) => {
            for p in extra_paths {
                let path = PathBuf::from(&p);
                if !written_paths.iter().any(|existing| existing == &path) {
                    written_paths.push(path);
                }
            }
        }
        Err(error) => {
            println!(
                "{} {}",
                "wizard".bright_yellow().bold(),
                format!("full setup failed: {error}").dimmed()
            );
            // Persist whatever we have so partial answers are not lost.
            write_configs(&config, project_root, config_path)?;
            return Err(error);
        }
    }

    match commit_paths(AutoCommitRequest {
        project_root,
        paths: written_paths,
        message: "chore(xbp): initialize project config".to_string(),
        action_label: "xbp init",
        push: false,
    })
    .await
    {
        Ok(AutoCommitResult::Committed(_)) => {}
        Ok(AutoCommitResult::Skipped(reason)) => print_skip("xbp init", &reason),
        Err(e) => print_skip("xbp init", &e),
    }

    Ok(())
}

#[derive(Debug, Clone)]
struct NestedServiceCandidate {
    service_root: PathBuf,
    project_type: ProjectType,
}

async fn run_nested_service_init(
    found: FoundXbpConfig,
    current_dir: PathBuf,
) -> Result<(), String> {
    let candidate = resolve_nested_service_candidate(&found.project_root, &current_dir)
        .await?
        .ok_or_else(|| {
            format!(
                "Found existing XBP project at {}, but no nested package/service markers were found between {} and the project root. Run `xbp init` from a folder that contains a package manifest such as package.json, Cargo.toml, or pyproject.toml.",
                found.project_root.display(),
                current_dir.display()
            )
        })?;

    let recommendations: DeploymentRecommendations =
        ProjectDetector::get_deployment_recommendations(
            &candidate.service_root,
            &candidate.project_type,
        );
    let inferred_name: String = infer_project_name(
        &candidate.project_type,
        &candidate.service_root,
        &recommendations,
    );
    let app_type_guess: Option<String> = infer_app_type(&candidate.project_type);
    let port_guess: u16 = detect_port(
        &candidate.service_root,
        &candidate.project_type,
        &recommendations,
    );
    let env_vars: HashMap<String, String> = detect_environment_from_env_files(&candidate.service_root);
    let version_targets: Vec<String> = discover_service_version_targets_for_project(
        &candidate.service_root,
        &found.project_root,
        &[],
    );

    let service_name: String = Input::new()
        .with_prompt("Service name")
        .with_initial_text(inferred_name)
        .interact_text()
        .map_err(|e| format!("Prompt failed: {}", e))?;

    let app_type: String =
        select_app_type(app_type_guess.clone()).map_err(|e| format!("Prompt failed: {}", e))?;

    let port: u16 = Input::new()
        .with_prompt("Primary port")
        .default(port_guess)
        .interact_text()
        .map_err(|e| format!("Prompt failed: {}", e))?;

    let versioning_enabled: bool = Confirm::new()
        .with_prompt("Enable versioning for this service? (xbp version bump)")
        .default(true)
        .interact()
        .map_err(|e| format!("Prompt failed: {}", e))?;
    let release_enabled = if versioning_enabled {
        Confirm::new()
            .with_prompt("Enable releasing for this service? (xbp version release)")
            .default(true)
            .interact()
            .map_err(|e| format!("Prompt failed: {}", e))?
    } else {
        false
    };

    let service_root_relative: String = collapse_project_path(
        &found.project_root,
        &candidate.service_root.to_string_lossy(),
    );
    let service_config: ServiceConfig = ServiceConfig {
        name: service_name.clone(),
        target: app_type.clone(),
        target_freeze: None,
        branch: current_git_branch()
            .await
            .unwrap_or_else(|| "main".to_string()),
        port,
        root_directory: Some(service_root_relative.clone()),
        environment: if env_vars.is_empty() {
            None
        } else {
            Some(env_vars)
        },
        url: None,
        healthcheck_path: None,
        restart_policy: Some("on_failure".to_string()),
        restart_policy_max_failure_count: Some(10),
        start_wrapper: Some("pm2".to_string()),
        commands: Some(ServiceCommands {
            pre: None,
            install: recommendations.install_command.clone(),
            build: recommendations.build_command.clone(),
            start: recommendations.start_command.clone(),
            dev: None,
            custom: Default::default(),
        }),
        force_run_from_root: Some(false),
        version_targets: if version_targets.is_empty() || !versioning_enabled {
            None
        } else {
            Some(version_targets.clone())
        },
        depends_on: None,
        watch_paths: None,
        versioning: if versioning_enabled {
            None
        } else {
            Some(false)
        },
        release: if release_enabled { None } else { Some(false) },
        systemd_service_name: None,
        systemd: None,
        openapi: None,
        oci: None,
        deploy: None,
        discord: None,
        file_associations: Vec::new(),
    };

    let mut config: XbpConfig = DeploymentConfig::load_xbp_config(Some(found.config_path.clone())).await?;
    ensure_root_service_entry(&mut config, &found.project_root, &version_targets);
    upsert_service_config(
        &mut config,
        service_config,
        &service_root_relative,
        &version_targets,
    );
    merge_project_version_targets(&mut config, &found.project_root, &version_targets);

    if let Some(services) = &config.services {
        validate_services(services)?;
    }

    let config_path = found.config_path.clone();
    let written_paths: Vec<PathBuf> = write_configs(&config, &found.project_root, &config_path)?;
    println!(
        "Updated {} and registered nested service `{}` at {}",
        config_path.display(),
        service_name,
        service_root_relative
    );

    match commit_paths(AutoCommitRequest {
        project_root: &found.project_root,
        paths: written_paths,
        message: format!("chore(xbp): register service {}", service_name),
        action_label: "xbp init",
        push: false,
    })
    .await
    {
        Ok(AutoCommitResult::Committed(_)) => {}
        Ok(AutoCommitResult::Skipped(reason)) => print_skip("xbp init", &reason),
        Err(e) => print_skip("xbp init", &e),
    }

    Ok(())
}

fn infer_project_name(
    project_type: &ProjectType,
    current_dir: &Path,
    recommendations: &DeploymentRecommendations,
) -> String {
    shared_infer_project_name(current_dir, project_type, recommendations)
}

fn infer_app_type(project_type: &ProjectType) -> Option<String> {
    match project_type {
        ProjectType::NextJs { .. } => Some("nextjs".to_string()),
        ProjectType::NodeJs { package_json } => {
            if has_express_dependency(package_json) {
                Some("expressjs".to_string())
            } else {
                Some("nodejs".to_string())
            }
        }
        ProjectType::Rust { .. } => Some("rust".to_string()),
        ProjectType::DockerCompose { .. } => Some("docker-compose".to_string()),
        ProjectType::Docker { .. } => Some("docker".to_string()),
        ProjectType::Railway { .. } => Some("railway".to_string()),
        ProjectType::Vercel { .. } => Some("vercel".to_string()),
        ProjectType::Python { .. } => Some("python".to_string()),
        _ => None,
    }
}

fn has_express_dependency(package_json: &PackageJsonInfo) -> bool {
    package_json
        .dependencies
        .keys()
        .any(|k| k.eq_ignore_ascii_case("express"))
        || package_json
            .dev_dependencies
            .keys()
            .any(|k| k.eq_ignore_ascii_case("express"))
}

fn select_app_type(detected: Option<String>) -> Result<String, String> {
    let mut options: Vec<String> = vec![
        "nextjs".to_string(),
        "expressjs".to_string(),
        "rust".to_string(),
        "nodejs".to_string(),
        "python".to_string(),
        "docker".to_string(),
        "railway".to_string(),
        "vercel".to_string(),
        "docker-compose".to_string(),
        "custom...".to_string(),
    ];

    let default_index = if let Some(ref guess) = detected {
        if let Some(pos) = options.iter().position(|o| o == guess) {
            pos
        } else {
            options.insert(0, format!("{} (detected)", guess));
            0
        }
    } else {
        0
    };

    let selection = Select::new()
        .with_prompt("App type")
        .items(&options)
        .default(default_index)
        .interact()
        .map_err(|e| format!("Prompt failed: {}", e))?;

    let choice = options
        .get(selection)
        .cloned()
        .unwrap_or_else(|| "nextjs".to_string());

    if choice == "custom..." {
        Input::<String>::new()
            .with_prompt("Enter app type")
            .interact_text()
            .map_err(|e| format!("Prompt failed: {}", e))
    } else if let Some(stripped) = choice.strip_suffix(" (detected)") {
        Ok(stripped.to_string())
    } else {
        Ok(choice)
    }
}

fn detect_port(
    project_root: &Path,
    project_type: &ProjectType,
    recommendations: &DeploymentRecommendations,
) -> u16 {
    if let Ok(port_env) = env::var("PORT") {
        if let Ok(port) = port_env.parse::<u16>() {
            return port;
        }
    }

    for name in [".env", ".env.local", ".env.development", ".env.production"] {
        if let Some(port) = parse_port_from_env_file(&project_root.join(name)) {
            return port;
        }
    }

    if let Some(port) = detect_port_from_package_json(project_root) {
        return port;
    }

    if let ProjectType::DockerCompose { detected_ports, .. } = project_type {
        if let Some(port) = detected_ports.first() {
            return *port;
        }
    }

    recommendations.default_port
}

fn parse_port_from_env_file(path: &Path) -> Option<u16> {
    if let Ok(parsed) = parse_env_file(path) {
        if let Some(port) = parsed
            .get("PORT")
            .and_then(|value| value.parse::<u16>().ok())
        {
            return Some(port);
        }
    }

    let contents = fs::read_to_string(path).ok()?;
    for line in contents.lines() {
        if let Some(port) = extract_port_from_str(line.trim()) {
            return Some(port);
        }
    }
    None
}

fn detect_port_from_package_json(project_root: &Path) -> Option<u16> {
    let pkg_path = project_root.join("package.json");
    let content = fs::read_to_string(&pkg_path).ok()?;
    let value: serde_json::Value = serde_json::from_str(&content).ok()?;

    if let Some(port) = value.get("port").and_then(|v| v.as_u64()) {
        return Some(port as u16);
    }

    if let Some(scripts) = value.get("scripts").and_then(|v| v.as_object()) {
        for script in scripts.values() {
            if let Some(text) = script.as_str() {
                if let Some(port) = extract_port_from_str(text) {
                    return Some(port);
                }
            }
        }
    }

    None
}

fn extract_port_from_str(text: &str) -> Option<u16> {
    let patterns = [
        r"PORT\s*[:=]\s*(\d{2,5})",
        r"port\s*[:=]\s*(\d{2,5})",
        r"--port\s+(\d{2,5})",
        r"-p\s+(\d{2,5})",
    ];

    for pat in patterns {
        if let Ok(re) = Regex::new(pat) {
            if let Some(caps) = re.captures(text) {
                if let Some(m) = caps.get(1) {
                    if let Ok(port) = m.as_str().parse::<u16>() {
                        return Some(port);
                    }
                }
            }
        }
    }
    None
}

fn detect_environment_from_env_files(project_root: &Path) -> HashMap<String, String> {
    let mut env_map = HashMap::new();
    for name in [".env", ".env.local", ".env.development", ".env.production"] {
        let path = project_root.join(name);
        if !path.exists() {
            continue;
        }
        if let Ok(parsed) = parse_env_file(&path) {
            for (key, value) in parsed {
                env_map.entry(key).or_insert(value);
            }
        }
    }
    to_env_references(&env_map)
}

fn write_configs(
    config: &XbpConfig,
    project_root: &Path,
    config_path: &Path,
) -> Result<Vec<PathBuf>, String> {
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?;
    }

    let mut persisted = config.clone();
    normalize_config_paths_for_persistence(&mut persisted, project_root);

    crate::utils::write_xbp_project_config_at_path(config_path, &persisted)?;

    let mut written_paths = vec![config_path.to_path_buf()];

    // If a parallel xbp.json already exists next to the written config, keep it in sync
    // without forcing JSON as the primary format.
    let json_path = config_path
        .parent()
        .map(|parent| parent.join("xbp.json"))
        .ok_or_else(|| "Invalid project config path".to_string())?;
    if json_path.exists() && json_path != config_path {
        crate::utils::write_xbp_project_config_at_path(&json_path, &persisted)
            .map_err(|e| format!("Failed to write {}: {}", json_path.display(), e))?;
        written_paths.push(json_path);
    }

    Ok(written_paths)
}

/// Remove legacy YAML project config siblings when migrating to `.xbp/xbp.toml`.
///
/// Leaves optional `xbp.json` mirrors alone (still dual-written when present).
/// Returns the first retired path (if any) so callers can print a migration note.
fn retire_non_primary_project_configs(
    project_root: &Path,
    primary: &Path,
) -> Option<PathBuf> {
    let primary_canon = primary.canonicalize().unwrap_or_else(|_| primary.to_path_buf());
    let mut retired = None;
    for name in ["xbp.yaml", "xbp.yml"] {
        for base in [project_root.join(".xbp"), project_root.to_path_buf()] {
            let candidate = base.join(name);
            if !candidate.exists() {
                continue;
            }
            let candidate_canon = candidate
                .canonicalize()
                .unwrap_or_else(|_| candidate.clone());
            if candidate_canon == primary_canon {
                continue;
            }
            if fs::remove_file(&candidate).is_ok() && retired.is_none() {
                retired = Some(candidate);
            }
        }
    }
    retired
}

async fn current_git_branch() -> Option<String> {
    let output = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .await
        .ok()?;

    if !output.status.success() {
        return None;
    }

    String::from_utf8(output.stdout)
        .ok()
        .map(|s| s.trim().to_string())
}

async fn resolve_nested_service_candidate(
    project_root: &Path,
    current_dir: &Path,
) -> Result<Option<NestedServiceCandidate>, String> {
    for candidate in ancestor_dirs_between(current_dir, project_root) {
        if !contains_service_discovery_marker(&candidate) {
            continue;
        }

        let project_type: ProjectType = ProjectDetector::detect_project_type(&candidate)
            .await
            .unwrap_or(ProjectType::Unknown);
        if !matches!(project_type, ProjectType::Unknown)
            || !discover_service_version_targets_for_project(&candidate, project_root, &[])
                .is_empty()
        {
            return Ok(Some(NestedServiceCandidate {
                service_root: candidate,
                project_type,
            }));
        }
    }

    Ok(None)
}

fn ancestor_dirs_between(current_dir: &Path, project_root: &Path) -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = Vec::new();
    let mut cursor: Option<&Path> = Some(current_dir);
    while let Some(dir) = cursor {
        if dir == project_root {
            break;
        }
        dirs.push(dir.to_path_buf());
        cursor = dir.parent();
    }
    dirs
}

fn contains_service_discovery_marker(dir: &Path) -> bool {
    SERVICE_DISCOVERY_MARKERS
        .iter()
        .any(|marker| dir.join(marker).exists())
}

fn ensure_root_service_entry(
    config: &mut XbpConfig,
    project_root: &Path,
    claimed_targets: &[String],
) {
    if config.services.is_some() {
        return;
    }

    let mut root_service: ServiceConfig = legacy_service_from_config(config);
    let claimed: HashSet<&str> = claimed_targets.iter().map(String::as_str).collect();
    let remaining_targets: Vec<String> = collect_service_manifest_targets_from_config(config, project_root)
        .into_iter()
        .filter(|target| !claimed.contains(target.as_str()))
        .collect::<Vec<_>>();

    root_service.version_targets = if remaining_targets.is_empty() {
        None
    } else {
        Some(remaining_targets)
    };
    config.services = Some(vec![root_service]);
}

fn collect_service_manifest_targets_from_config(
    config: &XbpConfig,
    project_root: &Path,
) -> Vec<String> {
    let mut seen: HashSet<String> = HashSet::new();
    let mut manifests: Vec<String> = Vec::new();

    for target in &config.version_targets {
        let relative: String = collapse_project_path(project_root, target);
        if is_service_version_manifest(&relative) && seen.insert(relative.clone()) {
            manifests.push(relative);
        }
    }

    if let Some(publish) = &config.publish {
        for manifest_path in [publish.npm.as_ref(), publish.crates.as_ref()]
            .into_iter()
            .flatten()
            .filter_map(|target| target.manifest_path.as_ref())
        {
            let relative: String = collapse_project_path(project_root, manifest_path);
            if is_service_version_manifest(&relative) && seen.insert(relative.clone()) {
                manifests.push(relative);
            }
        }
    }

    manifests
}

fn is_service_version_manifest(path: &str) -> bool {
    let file_name: &str = Path::new(path)
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or_default();
    SERVICE_VERSION_MANIFESTS.contains(&file_name)
}

fn upsert_service_config(
    config: &mut XbpConfig,
    service: ServiceConfig,
    service_root_relative: &str,
    version_targets: &[String],
) {
    let services: &mut Vec<ServiceConfig> = config.services.get_or_insert_with(Vec::new);
    let service_target_set: HashSet<&str> = version_targets.iter().map(String::as_str).collect();

    let existing_index: Option<usize> = services.iter().position(|existing| {
        existing.root_directory.as_deref() == Some(service_root_relative)
            || existing
                .version_targets
                .as_ref()
                .map(|targets| {
                    targets
                        .iter()
                        .any(|target| service_target_set.contains(target.as_str()))
                })
                .unwrap_or(false)
            || existing.name.eq_ignore_ascii_case(&service.name)
    });

    if let Some(index) = existing_index {
        let existing: ServiceConfig = services.remove(index);
        services.insert(index, merge_service_config(existing, service));
    } else {
        services.push(service);
    }
}

fn merge_service_config(existing: ServiceConfig, detected: ServiceConfig) -> ServiceConfig {
    let target_freeze: Option<bool> = existing.target_freeze.or(detected.target_freeze);
    let target: String = if existing.is_target_frozen() || target_freeze.unwrap_or(false) {
        existing.target
    } else {
        detected.target
    };
    ServiceConfig {
        name: detected.name,
        target,
        target_freeze,
        branch: detected.branch,
        port: detected.port,
        root_directory: detected.root_directory,
        environment: merge_environment_maps(existing.environment, detected.environment),
        url: existing.url.or(detected.url),
        healthcheck_path: existing.healthcheck_path.or(detected.healthcheck_path),
        restart_policy: existing.restart_policy.or(detected.restart_policy),
        restart_policy_max_failure_count: existing
            .restart_policy_max_failure_count
            .or(detected.restart_policy_max_failure_count),
        start_wrapper: existing.start_wrapper.or(detected.start_wrapper),
        commands: merge_service_commands(existing.commands, detected.commands),
        force_run_from_root: existing
            .force_run_from_root
            .or(detected.force_run_from_root),
        version_targets: detected.version_targets.or(existing.version_targets),
        depends_on: existing.depends_on.or(detected.depends_on),
        watch_paths: existing.watch_paths.or(detected.watch_paths),
        versioning: existing.versioning.or(detected.versioning),
        release: existing.release.or(detected.release),
        systemd_service_name: existing
            .systemd_service_name
            .or(detected.systemd_service_name),
        systemd: existing.systemd.or(detected.systemd),
        openapi: existing.openapi.or(detected.openapi),
        oci: existing.oci.or(detected.oci),
        deploy: existing.deploy.or(detected.deploy),
        discord: existing.discord.or(detected.discord),
        file_associations: if existing.file_associations.is_empty() {
            detected.file_associations
        } else {
            existing.file_associations
        },
    }
}

fn merge_environment_maps(
    existing: Option<HashMap<String, String>>,
    detected: Option<HashMap<String, String>>,
) -> Option<HashMap<String, String>> {
    match (existing, detected) {
        (None, None) => None,
        (Some(existing), None) => Some(existing),
        (None, Some(detected)) => Some(detected),
        (Some(mut existing), Some(detected)) => {
            for (key, value) in detected {
                existing.insert(key, value);
            }
            Some(existing)
        }
    }
}

fn merge_service_commands(
    existing: Option<ServiceCommands>,
    detected: Option<ServiceCommands>,
) -> Option<ServiceCommands> {
    match (existing, detected) {
        (None, None) => None,
        (Some(existing), None) => Some(existing),
        (None, Some(detected)) => Some(detected),
        (Some(mut existing), Some(detected)) => {
            existing.pre = existing.pre.or(detected.pre);
            existing.install = existing.install.or(detected.install);
            existing.build = existing.build.or(detected.build);
            existing.start = existing.start.or(detected.start);
            existing.dev = existing.dev.or(detected.dev);
            for (name, command) in detected.custom {
                existing.custom.entry(name).or_insert(command);
            }
            Some(existing)
        }
    }
}

fn merge_project_version_targets(
    config: &mut XbpConfig,
    project_root: &Path,
    version_targets: &[String],
) {
    let ignore = load_project_xbp_ignore(project_root, &config.ignore_paths);
    let mut seen: HashSet<String> = config.version_targets.iter().cloned().collect();
    for target in version_targets {
        if ignore.ignores_version_target(target) {
            continue;
        }
        if seen.insert(target.clone()) {
            config.version_targets.push(target.clone());
        }
    }
    config
        .version_targets
        .retain(|target| !ignore.ignores_version_target(target));
    config.version_targets.sort();
    config.version_targets.dedup();
}

#[cfg(test)]
mod tests {
    use super::{
        ancestor_dirs_between, contains_service_discovery_marker, ensure_root_service_entry,
        merge_project_version_targets, retire_non_primary_project_configs,
    };
    use crate::commands::project_services::discover_service_version_targets_for_project;
    use crate::strategies::{ServiceConfig, XbpConfig};
    use std::fs;
    use std::path::PathBuf;

    fn temp_dir(name: &str) -> PathBuf {
        let dir: PathBuf = std::env::temp_dir().join(format!("xbp-init-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("create temp dir");
        dir
    }

    #[test]
    fn greenfield_init_path_is_xbp_toml() {
        let root = temp_dir("greenfield-toml");
        let path = crate::utils::default_project_config_path(
            &root,
            crate::utils::DEFAULT_PROJECT_CONFIG_KIND,
        );
        assert!(
            path.ends_with(".xbp/xbp.toml") || path.ends_with(r".xbp\xbp.toml"),
            "expected .xbp/xbp.toml, got {}",
            path.display()
        );
        assert_eq!(crate::utils::DEFAULT_PROJECT_CONFIG_KIND, "toml");
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn retire_yaml_when_migrating_to_toml() {
        let root = temp_dir("retire-yaml");
        let dot = root.join(".xbp");
        fs::create_dir_all(&dot).unwrap();
        let yaml = dot.join("xbp.yaml");
        let toml = dot.join("xbp.toml");
        fs::write(&yaml, "project_name: demo\n").unwrap();
        fs::write(&toml, "project_name = \"demo\"\n").unwrap();

        let retired = retire_non_primary_project_configs(&root, &toml);
        assert!(retired.is_some());
        assert!(!yaml.exists());
        assert!(toml.exists());
        let _ = fs::remove_dir_all(root);
    }

    fn base_config() -> XbpConfig {
        XbpConfig {
            project_name: "demo".to_string(),
            version: "0.1.0".to_string(),
            port: 3000,
            build_dir: ".".to_string(),
            app_type: Some("rust".to_string()),
            build_command: Some("cargo build --release".to_string()),
            start_command: Some("./target/release/demo".to_string()),
            install_command: None,
            environment: None,
            services: None,
            openapi: None,
            workers: None,
            systemd_service_name: None,
            systemd: None,
            kafka_brokers: None,
            kafka_topic: None,
            kafka_public_url: None,
            log_files: None,
            monitor_url: None,
            monitor_method: None,
            monitor_expected_code: None,
            monitor_interval: None,
            database: None,
            oci: None,
            kubernetes: None,
            deploy: None,
            target: Some("rust".to_string()),
            branch: Some("main".to_string()),
            crate_name: None,
            npm_script: None,
            port_storybook: None,
            url: None,
            url_storybook: None,
            linear: None,
            github: None,
            publish: None,
            version_targets: vec![
                "crates/cli/Cargo.toml".to_string(),
                "apps/web/package.json".to_string(),
            ],
            version_domains: Vec::new(),
            ignore_paths: Vec::new(),
            watch_ignore_paths: Vec::new(),
            versioning_disabled: Vec::new(),
            release_disabled: Vec::new(),
            versioning: None,
            discord: None,
        }
    }

    #[test]
    fn ancestor_dir_scan_stops_before_project_root() {
        let root: PathBuf = PathBuf::from("C:/repo");
        let nested: PathBuf = PathBuf::from("C:/repo/apps/web/src");
        let dirs: Vec<PathBuf> = ancestor_dirs_between(&nested, &root);
        assert_eq!(
            dirs,
            vec![
                PathBuf::from("C:/repo/apps/web/src"),
                PathBuf::from("C:/repo/apps/web"),
                PathBuf::from("C:/repo/apps"),
            ]
        );
    }

    #[test]
    fn discovery_markers_and_version_targets_detect_nested_package() {
        let project_root: PathBuf = temp_dir("markers");
        let service_root: PathBuf = project_root.join("apps").join("web");
        fs::create_dir_all(&service_root).expect("create service root");
        fs::write(service_root.join("package.json"), "{ \"name\": \"web\" }")
            .expect("write package");

        assert!(contains_service_discovery_marker(&service_root));
        assert_eq!(
            discover_service_version_targets_for_project(&service_root, &project_root, &[]),
            vec!["apps/web/package.json".to_string()]
        );

        let _ = fs::remove_dir_all(project_root);
    }

    #[test]
    fn ensuring_root_service_claims_remaining_targets() {
        let project_root: PathBuf = temp_dir("root-service");
        let mut config: XbpConfig = base_config();
        ensure_root_service_entry(
            &mut config,
            &project_root,
            &["apps/web/package.json".to_string()],
        );

        let services: Vec<ServiceConfig> = config.services.expect("services");
        assert_eq!(services.len(), 1);
        assert_eq!(services[0].name, "demo");
        assert_eq!(
            services[0].version_targets,
            Some(vec!["crates/cli/Cargo.toml".to_string()])
        );

        let _ = fs::remove_dir_all(project_root);
    }

    #[test]
    fn project_version_targets_merge_without_duplicates() {
        let mut config: XbpConfig = base_config();
        let project_root: PathBuf = temp_dir("merge-targets");
        merge_project_version_targets(
            &mut config,
            &project_root,
            &[
                "apps/web/package.json".to_string(),
                "apps/api/pyproject.toml".to_string(),
            ],
        );

        assert_eq!(
            config.version_targets,
            vec![
                "apps/api/pyproject.toml".to_string(),
                "apps/web/package.json".to_string(),
                "crates/cli/Cargo.toml".to_string(),
            ]
        );
        let _ = fs::remove_dir_all(project_root);
    }

    #[test]
    fn merge_root_service_tests_reference_service_config_type() {
        let _: Option<ServiceConfig> = None;
    }
}