clever-project 0.0.4

Declare Clever Cloud resources in a YAML/JSON file and sync them via the clever-tools CLI.
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
use std::path::Path;
use std::sync::LazyLock;

use anyhow::{Context, Result, anyhow, bail};
use indexmap::IndexMap;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_yaml::Value;
use tracing::debug;

use crate::interpolate::Resolver;
use crate::issues::{self, Issue, IssueSink};

static SECRET_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\$\{secrets\.([A-Za-z_][A-Za-z0-9_]*)\}").unwrap());

/// Valid values for `app.kind`, as accepted by `clever create --type`.
/// See https://www.clever.cloud/developers/doc/.
pub const ALLOWED_APP_KINDS: &[&str] = &[
    "docker",
    "dotnet",
    "elixir",
    "frankenphp",
    "go",
    "gradle",
    "haskell",
    "jar",
    "linux",
    "maven",
    "meteor",
    "node",
    "php",
    "play1",
    "play2",
    "python",
    "ruby",
    "rust",
    "sbt",
    "static",
    "static-apache",
    "v",
    "war",
];

/// Lowercase + map common aliases to the canonical kind. `java` becomes
/// `jar` (Clever reports java apps with `type: jar`).
pub fn normalize_app_kind(kind: &str) -> String {
    let lower = kind.to_lowercase();
    match lower.as_str() {
        "java" => "jar".to_string(),
        _ => lower,
    }
}

/// Valid values for `region` (project root, app, or addon).
pub const ALLOWED_REGIONS: &[&str] = &[
    "par", "parhds", "scw", "grahds", "ldn", "mtl", "rbx", "rbxhds", "sgp", "syd", "wsw",
];

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub org: String,
    pub region: String,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub variables: IndexMap<String, String>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub apps: IndexMap<String, App>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub addons: IndexMap<String, Addon>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub network_groups: IndexMap<String, NetworkGroup>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkGroup {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Project keys (in `apps:` or `addons:`) of the resources to attach to
    /// this network group.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub link: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct App {
    pub name: String,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<Source>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub domains: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scalability: Option<Scalability>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependencies: Vec<String>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub config: IndexMap<String, String>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub env: IndexMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Source {
    pub from: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Scalability {
    #[serde(default)]
    pub auto: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instances: Option<Instances>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Instances {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_number: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_number: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_size: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_size: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Addon {
    pub name: String,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size: Option<String>,
    #[serde(default)]
    pub crypted: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<serde_yaml::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backup_path: Option<String>,
}

#[derive(Debug, Clone, Copy)]
pub enum Format {
    Yaml,
    Json,
}

impl Format {
    pub fn from_path(path: &Path) -> Result<Self> {
        match path.extension().and_then(|e| e.to_str()) {
            Some("yaml") | Some("yml") => Ok(Format::Yaml),
            Some("json") => Ok(Format::Json),
            Some(other) => Err(anyhow!(
                "unsupported file extension `.{other}` (expected .yaml, .yml or .json)"
            )),
            None => Err(anyhow!(
                "missing file extension on `{}` (expected .yaml, .yml or .json)",
                path.display()
            )),
        }
    }
}

impl Project {
    /// Load and parse without interpolation. Used by tests; in production
    /// callers usually want `load_and_resolve`.
    #[allow(dead_code)]
    pub fn load(path: &Path) -> Result<Self> {
        let value = load_value(path)?;
        let project: Project = serde_yaml::from_value(value)
            .with_context(|| format!("deserializing project from `{}`", path.display()))?;
        Ok(project)
    }

    /// Load the project file, run variable interpolation, and return both the
    /// resolved project and the resolver. Fails fast — all accumulated soft
    /// issues (missing vars/secrets, unknown kinds/regions, etc.) are
    /// rendered as a single error.
    pub fn load_and_resolve(
        path: &Path,
        org_override: Option<String>,
        region_override: Option<String>,
        cli_vars: &[(String, String)],
        secrets_path: Option<&Path>,
    ) -> Result<(Self, Resolver)> {
        let (project, resolver, issues) =
            load_inner(path, org_override, region_override, cli_vars, secrets_path)?;
        if !issues.is_empty() {
            bail!("{}", issues::render(&issues));
        }
        Ok((project, resolver))
    }

    /// Like `load_and_resolve` but does not bail on soft issues. Returns the
    /// (partially resolved) project plus every accumulated issue, so callers
    /// like `check` can run further cross-resource validators on top before
    /// rendering one combined report. Still returns `Err` for fatal failures
    /// that prevent producing a `Project` at all (I/O, syntax, missing
    /// `org`/`region`, mixed variables shape, reserved variable name).
    pub fn load_collecting(
        path: &Path,
        org_override: Option<String>,
        region_override: Option<String>,
        cli_vars: &[(String, String)],
        secrets_path: Option<&Path>,
    ) -> Result<(Self, Vec<Issue>)> {
        let (project, _resolver, issues) =
            load_inner(path, org_override, region_override, cli_vars, secrets_path)?;
        Ok((project, issues))
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        let serialized = match Format::from_path(path)? {
            Format::Yaml => serde_yaml::to_string(self).context("serializing to YAML")?,
            Format::Json => serde_json::to_string_pretty(self).context("serializing to JSON")?,
        };
        std::fs::write(path, serialized)
            .with_context(|| format!("writing project file `{}`", path.display()))?;
        Ok(())
    }
}

/// Shared loading pipeline: parse the file, build the resolver, interpolate,
/// deserialize, run the model-level validators. Soft issues (missing
/// variables, unknown kinds/regions, ...) are collected into the returned
/// `Vec<Issue>`; only truly fatal failures (I/O, syntax, mixed-shape
/// variables, missing `org`/`region`) return `Err`.
fn load_inner(
    path: &Path,
    org_override: Option<String>,
    region_override: Option<String>,
    cli_vars: &[(String, String)],
    secrets_path: Option<&Path>,
) -> Result<(Project, Resolver, Vec<Issue>)> {
    let mut issues: Vec<Issue> = Vec::new();

    let mut value = load_value(path)?;
    let map = value
        .as_mapping_mut()
        .ok_or_else(|| anyhow!("project file root must be a mapping"))?;

    let org = match org_override {
        Some(v) => v,
        None => map
            .get(Value::String("org".into()))
            .and_then(Value::as_str)
            .map(str::to_string)
            .ok_or_else(|| anyhow!("missing `org` at project root (and no --org override)"))?,
    };
    let region = match region_override {
        Some(v) => v,
        None => map
            .get(Value::String("region".into()))
            .and_then(Value::as_str)
            .map(str::to_string)
            .ok_or_else(|| {
                anyhow!("missing `region` at project root (and no --region override)")
            })?,
    };

    let effective_env = cli_vars
        .iter()
        .rev()
        .find(|(k, _)| k == "env")
        .map(|(_, v)| v.clone())
        .unwrap_or_else(|| "prod".to_string());

    let secrets = load_secrets(path, &effective_env, secrets_path)?;

    let raw_variables = map
        .remove(Value::String("variables".into()))
        .unwrap_or(Value::Null);
    let file_vars = parse_variables(&raw_variables, &effective_env)?;
    // Allow `${secrets.X}` inside variable values. Missing secrets become
    // empty strings and an issue.
    let file_vars = expand_secrets(file_vars, &secrets, &mut issues);

    // Build the merged map: file vars first, then secrets exposed under
    // their `secrets.<key>` namespace. Resolver::build will layer
    // cli_vars on top and add env/org/region.
    let mut combined = file_vars;
    for (k, v) in &secrets {
        combined.insert(format!("secrets.{k}"), v.clone());
    }
    let resolver = Resolver::build(&combined, cli_vars, org.clone(), region.clone())?;

    // Apply CLI overrides into the value tree so the deserialized Project
    // reflects them. The `variables` section was removed earlier — the
    // resolver carries the merged values now.
    map.insert(Value::String("org".into()), Value::String(org));
    map.insert(Value::String("region".into()), Value::String(region));

    resolver.resolve_value(&mut value, &mut issues);

    let mut project: Project = serde_yaml::from_value(value)
        .with_context(|| format!("deserializing project from `{}`", path.display()))?;
    validate_and_normalize_app_kinds(&mut project, &mut issues);
    validate_regions(&project, &mut issues);
    Ok((project, resolver, issues))
}

/// Parse the project file's `variables` section. Two shapes are accepted:
///
/// - **flat**: `Map<String, scalar>` — used as-is.
/// - **per-env**: `Map<String, Map<String, scalar>>` — entries under the
///   special key `common` are always included, then entries under the key
///   matching the resolved `${env}` value are merged on top (overriding
///   common).
///
/// Mixing scalar and mapping values at the top level is rejected.
fn parse_variables(raw: &Value, env: &str) -> Result<IndexMap<String, String>> {
    let mapping = match raw {
        Value::Null => return Ok(IndexMap::new()),
        Value::Mapping(m) => m,
        _ => bail!("`variables` must be a mapping"),
    };
    if mapping.is_empty() {
        return Ok(IndexMap::new());
    }

    let mut saw_scalar = false;
    let mut saw_mapping = false;
    for (_, v) in mapping {
        match v {
            Value::Mapping(_) => saw_mapping = true,
            Value::String(_) | Value::Bool(_) | Value::Number(_) | Value::Null => saw_scalar = true,
            _ => bail!("variable values must be scalars or mappings"),
        }
    }
    if saw_scalar && saw_mapping {
        bail!(
            "`variables` must be either a flat map (key=scalar) or a per-env map (key=mapping), not both"
        );
    }

    if saw_mapping {
        let mut out = IndexMap::new();
        if let Some(Value::Mapping(common)) = mapping.get(Value::String("common".into())) {
            collect_scalar_entries(common, &mut out, "common")?;
        }
        if let Some(Value::Mapping(env_group)) = mapping.get(Value::String(env.into())) {
            collect_scalar_entries(env_group, &mut out, env)?;
        }
        Ok(out)
    } else {
        let mut out = IndexMap::new();
        collect_scalar_entries(mapping, &mut out, "variables")?;
        Ok(out)
    }
}

fn collect_scalar_entries(
    m: &serde_yaml::Mapping,
    out: &mut IndexMap<String, String>,
    where_: &str,
) -> Result<()> {
    for (k, v) in m {
        let key = k
            .as_str()
            .ok_or_else(|| anyhow!("variable keys must be strings (in `{where_}`)"))?
            .to_string();
        let val = match v {
            Value::String(s) => s.clone(),
            Value::Bool(b) => b.to_string(),
            Value::Number(n) => n.to_string(),
            Value::Null => String::new(),
            _ => bail!("variable `{key}` in `{where_}` must be a scalar (string/number/bool)"),
        };
        out.insert(key, val);
    }
    Ok(())
}

/// Load the secrets map for a project.
///
/// - If `explicit` is `Some(path)`, only that file is loaded and it must exist.
/// - Otherwise, both `<project>.secrets` (the env-agnostic defaults) and
///   `<project>.<env>.secrets` (env-specific overrides) are auto-discovered
///   next to the project file. Either or both may be absent — that's fine.
///   When both are present, the env-specific entries override the defaults.
fn load_secrets(
    project_path: &Path,
    env: &str,
    explicit: Option<&Path>,
) -> Result<IndexMap<String, String>> {
    if let Some(p) = explicit {
        return read_secrets_file(p, /* required */ true);
    }

    let mut out = IndexMap::new();
    let stem = project_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    let dir = project_path.parent().unwrap_or(Path::new("."));
    if !stem.is_empty() {
        let default_path = dir.join(format!("{stem}.secrets"));
        if default_path.exists() {
            debug!("loading secrets from `{}`", default_path.display());
            for (k, v) in read_secrets_file(&default_path, false)? {
                out.insert(k, v);
            }
        }
        let env_path = dir.join(format!("{stem}.{env}.secrets"));
        if env_path.exists() {
            debug!("loading env-specific secrets from `{}`", env_path.display());
            for (k, v) in read_secrets_file(&env_path, false)? {
                out.insert(k, v);
            }
        }
    }
    Ok(out)
}

fn read_secrets_file(path: &Path, required: bool) -> Result<IndexMap<String, String>> {
    if !path.exists() {
        if required {
            bail!("secrets file `{}` not found", path.display());
        }
        return Ok(IndexMap::new());
    }
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("reading secrets file `{}`", path.display()))?;
    let value = parse_yaml_or_json(&raw).with_context(|| {
        format!(
            "parsing secrets file `{}` (neither YAML nor JSON)",
            path.display()
        )
    })?;
    let mapping = match value {
        Value::Mapping(m) => m,
        Value::Null => return Ok(IndexMap::new()),
        _ => bail!("secrets file `{}` must be a mapping", path.display()),
    };
    let mut out = IndexMap::new();
    for (k, v) in mapping {
        let key = k
            .as_str()
            .ok_or_else(|| anyhow!("secret keys must be strings (in `{}`)", path.display()))?
            .to_string();
        let val = match v {
            Value::String(s) => s,
            Value::Bool(b) => b.to_string(),
            Value::Number(n) => n.to_string(),
            Value::Null => String::new(),
            _ => bail!(
                "secret `{key}` in `{}` must be a scalar (string/number/bool)",
                path.display()
            ),
        };
        out.insert(key, val);
    }
    Ok(out)
}

/// Try parsing `raw` as YAML, then as JSON; return the first successful one.
/// JSON is technically a subset of YAML 1.2, so this is mostly a no-op in
/// practice — but it lets us surface both parser errors when neither works,
/// and makes the dual support explicit at the call site.
fn parse_yaml_or_json(raw: &str) -> Result<Value> {
    match serde_yaml::from_str::<Value>(raw) {
        Ok(v) => Ok(v),
        Err(yaml_err) => match serde_json::from_str::<serde_json::Value>(raw) {
            Ok(jv) => serde_yaml::to_value(&jv).context("converting parsed JSON to YAML value"),
            Err(json_err) => Err(anyhow!(
                "could not parse as YAML or JSON\n  YAML error: {yaml_err}\n  JSON error: {json_err}"
            )),
        },
    }
}

/// Expand `${secrets.X}` references inside the values of the project's
/// variables section, before they're handed to the resolver. References to
/// other variables (`${foo}`) are left untouched here — they're handled by
/// the resolver during the value-tree walk. Missing secrets are recorded in
/// `issues` and replaced by empty so resolution can continue.
fn expand_secrets(
    vars: IndexMap<String, String>,
    secrets: &IndexMap<String, String>,
    issues: &mut Vec<Issue>,
) -> IndexMap<String, String> {
    let mut out = IndexMap::with_capacity(vars.len());
    for (k, v) in vars {
        let resolved = SECRET_RE.replace_all(&v, |caps: &regex::Captures| {
            let name = &caps[1];
            match secrets.get(name) {
                Some(val) => val.clone(),
                None => {
                    issues.push_issue(format!(
                        "undefined secret `{name}` referenced in variable `{k}`"
                    ));
                    String::new()
                }
            }
        });
        out.insert(k, resolved.into_owned());
    }
    out
}

/// Load a `--variable-path FILE` as a flat list of `(key, value)` pairs.
/// Accepts YAML or JSON (detected by extension); the file must be a mapping
/// of scalars (matching the shape of `--variable foo=bar` overrides).
pub fn load_variables_file(path: &Path) -> Result<Vec<(String, String)>> {
    let _ = Format::from_path(path)?; // validate extension up front
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("reading variables file `{}`", path.display()))?;
    let value: Value = serde_yaml::from_str(&raw)
        .with_context(|| format!("parsing variables file `{}`", path.display()))?;
    let mapping = match value {
        Value::Mapping(m) => m,
        Value::Null => return Ok(Vec::new()),
        _ => bail!("variables file `{}` must be a mapping", path.display()),
    };
    let mut out = Vec::new();
    for (k, v) in mapping {
        let key = k
            .as_str()
            .ok_or_else(|| anyhow!("variable keys must be strings (in `{}`)", path.display()))?
            .to_string();
        let val = match v {
            Value::String(s) => s,
            Value::Bool(b) => b.to_string(),
            Value::Number(n) => n.to_string(),
            Value::Null => String::new(),
            _ => bail!(
                "variable `{key}` in `{}` must be a scalar (string/number/bool)",
                path.display()
            ),
        };
        out.push((key, val));
    }
    Ok(out)
}

/// Normalize each app's `kind` (lowercase + `java` → `jar`) and record any
/// kind that isn't in `ALLOWED_APP_KINDS`. The mutation happens regardless so
/// downstream code sees the canonical form even when the kind is unknown.
fn validate_and_normalize_app_kinds(project: &mut Project, issues: &mut Vec<Issue>) {
    for (key, app) in project.apps.iter_mut() {
        let normalized = normalize_app_kind(&app.kind);
        if !ALLOWED_APP_KINDS.contains(&normalized.as_str()) {
            issues.push_issue(format!(
                "app `{key}` has unknown kind `{}`. Valid kinds: {} (or `java` as an alias for `jar`)",
                app.kind,
                ALLOWED_APP_KINDS.join(", ")
            ));
        }
        app.kind = normalized;
    }
}

/// Reject any unknown region — root, per-app, or per-addon.
fn validate_regions(project: &Project, issues: &mut Vec<Issue>) {
    check_region("project root", &project.region, issues);
    for (key, app) in &project.apps {
        if let Some(r) = &app.region {
            check_region(&format!("app `{key}`"), r, issues);
        }
    }
    for (key, addon) in &project.addons {
        if let Some(r) = &addon.region {
            check_region(&format!("addon `{key}`"), r, issues);
        }
    }
}

fn check_region(where_: &str, value: &str, issues: &mut Vec<Issue>) {
    if !ALLOWED_REGIONS.contains(&value) {
        issues.push_issue(format!(
            "{where_} has unknown region `{value}`. Valid regions: {}",
            ALLOWED_REGIONS.join(", ")
        ));
    }
}

fn load_value(path: &Path) -> Result<Value> {
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("reading project file `{}`", path.display()))?;
    // JSON is a subset of YAML 1.2, so the YAML parser handles both.
    let _ = Format::from_path(path)?; // validate extension up front
    let value: Value =
        serde_yaml::from_str(&raw).with_context(|| format!("parsing `{}`", path.display()))?;
    Ok(value)
}

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

    const SAMPLE: &str = r#"
name: My Project
description: "....."
org: orga_orga-clevercloud-cible
region: par
variables:
  foo: bar
  bar: qix
apps:
  app1:
    name: frontend
    kind: java
    region: par
    source:
      from: https://github.com/MAIF/otoroshi.git
      branch: master
    domains:
      - foo.${foo}.qix
    scalability:
      auto: true
      instances:
        minNumber: 1
        maxNumber: 2
        minSize: S
        maxSize: M
    dependencies:
      - addon1
      - addon2
      - app2
    config:
      foo: bar
    env:
      PORT: "8080"
addons:
  addon1:
    name: ${env}-pg
    kind: postgresql
    size: S_BIG
    crypted: true
    region: par
    version: 17
"#;

    fn write_tmp(ext: &str, contents: &str) -> std::path::PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!(
            "clever-project-test-{}-{}.{ext}",
            std::process::id(),
            rand_suffix()
        ));
        std::fs::write(&p, contents).unwrap();
        p
    }

    fn rand_suffix() -> String {
        use std::time::{SystemTime, UNIX_EPOCH};
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos()
            .to_string()
    }

    #[test]
    fn loads_and_resolves_spec_sample() {
        let p = write_tmp("yaml", SAMPLE);
        let (project, _r) =
            Project::load_and_resolve(&p, None, None, &[], None).expect("load failed");
        assert_eq!(project.name, "My Project");
        assert_eq!(project.org, "orga_orga-clevercloud-cible");
        assert_eq!(project.region, "par");
        let app = project.apps.get("app1").unwrap();
        assert_eq!(app.domains[0], "foo.bar.qix");
        let addon = project.addons.get("addon1").unwrap();
        assert_eq!(addon.name, "prod-pg"); // ${env} -> prod default
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn cli_overrides_apply_to_project() {
        let p = write_tmp("yaml", SAMPLE);
        let (project, _r) = Project::load_and_resolve(
            &p,
            Some("override_org".into()),
            Some("rbx".into()),
            &[("env".to_string(), "staging".to_string())],
            None,
        )
        .unwrap();
        assert_eq!(project.org, "override_org");
        assert_eq!(project.region, "rbx");
        assert_eq!(project.addons.get("addon1").unwrap().name, "staging-pg");
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn missing_var_propagates() {
        let bad = "name: x\norg: o\nregion: r\napps:\n  a:\n    name: ${missing}\n    kind: node\n";
        let p = write_tmp("yaml", bad);
        let err = Project::load_and_resolve(&p, None, None, &[], None).unwrap_err();
        assert!(err.to_string().contains("missing"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn unknown_root_region_is_rejected() {
        let bad = "name: P\norg: o\nregion: atlantis\napps: {}\n";
        let p = write_tmp("yaml", bad);
        let err = Project::load_and_resolve(&p, None, None, &[], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("atlantis"));
        assert!(msg.contains("Valid regions"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn unknown_app_region_is_rejected() {
        let bad = "name: P\norg: o\nregion: par\napps:\n  a:\n    name: x\n    kind: node\n    region: zzz\n";
        let p = write_tmp("yaml", bad);
        let err = Project::load_and_resolve(&p, None, None, &[], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("app `a`"));
        assert!(msg.contains("zzz"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn multiple_load_time_issues_are_all_reported() {
        // bad root region + bad app kind + bad app region: 3 problems
        let bad = "name: P\norg: o\nregion: atlantis\napps:\n  a:\n    name: x\n    kind: cobol\n    region: zzz\n";
        let p = write_tmp("yaml", bad);
        let err = Project::load_and_resolve(&p, None, None, &[], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("3 validation problems"), "got: {msg}");
        assert!(msg.contains("atlantis"));
        assert!(msg.contains("cobol"));
        assert!(msg.contains("zzz"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn unknown_addon_region_is_rejected() {
        let bad = "name: P\norg: o\nregion: par\napps: {}\naddons:\n  db:\n    name: x\n    kind: postgresql\n    region: nope\n";
        let p = write_tmp("yaml", bad);
        let err = Project::load_and_resolve(&p, None, None, &[], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("addon `db`"));
        assert!(msg.contains("nope"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn cli_region_override_is_validated() {
        let yaml = "name: P\norg: o\nregion: par\napps: {}\n";
        let p = write_tmp("yaml", yaml);
        let err =
            Project::load_and_resolve(&p, None, Some("mars".to_string()), &[], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("mars"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn unknown_app_kind_is_rejected() {
        let bad = "name: P\norg: o\nregion: par\napps:\n  a:\n    name: x\n    kind: cobol\n";
        let p = write_tmp("yaml", bad);
        let err = Project::load_and_resolve(&p, None, None, &[], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("cobol"));
        assert!(msg.contains("Valid kinds"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn java_alias_normalises_to_jar() {
        let yaml = "name: P\norg: o\nregion: par\napps:\n  a:\n    name: x\n    kind: java\n";
        let p = write_tmp("yaml", yaml);
        let (project, _r) = Project::load_and_resolve(&p, None, None, &[], None).unwrap();
        assert_eq!(project.apps.get("a").unwrap().kind, "jar");
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn kind_is_lowercased() {
        let yaml = "name: P\norg: o\nregion: par\napps:\n  a:\n    name: x\n    kind: NODE\n";
        let p = write_tmp("yaml", yaml);
        let (project, _r) = Project::load_and_resolve(&p, None, None, &[], None).unwrap();
        assert_eq!(project.apps.get("a").unwrap().kind, "node");
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn json_format_works_too() {
        let json = r#"{"name":"P","org":"o","region":"par","apps":{"a":{"name":"${env}-app","kind":"node"}}}"#;
        let p = write_tmp("json", json);
        let (project, _r) = Project::load_and_resolve(&p, None, None, &[], None).unwrap();
        assert_eq!(project.apps.get("a").unwrap().name, "prod-app");
        std::fs::remove_file(&p).ok();
    }

    const PER_ENV: &str = r#"
name: PE
org: o
region: par
variables:
  common:
    domain: foo.bar
  prod:
    apikey: secret_for_prod
  dev:
    apikey: secret_for_dev
    domain: dev.bar
apps:
  a:
    name: ${env}-app
    kind: node
    env:
      DOMAIN: ${domain}
      APIKEY: ${apikey}
"#;

    #[test]
    fn per_env_picks_default_prod_group() {
        let p = write_tmp("yaml", PER_ENV);
        let (project, _r) = Project::load_and_resolve(&p, None, None, &[], None).unwrap();
        let app = project.apps.get("a").unwrap();
        assert_eq!(app.env.get("DOMAIN").unwrap(), "foo.bar");
        assert_eq!(app.env.get("APIKEY").unwrap(), "secret_for_prod");
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn per_env_dev_group_overrides_common() {
        let p = write_tmp("yaml", PER_ENV);
        let (project, _r) = Project::load_and_resolve(
            &p,
            None,
            None,
            &[("env".to_string(), "dev".to_string())],
            None,
        )
        .unwrap();
        let app = project.apps.get("a").unwrap();
        assert_eq!(app.env.get("DOMAIN").unwrap(), "dev.bar");
        assert_eq!(app.env.get("APIKEY").unwrap(), "secret_for_dev");
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn per_env_unknown_env_uses_common_only_and_errors_on_unknown_ref() {
        let p = write_tmp("yaml", PER_ENV);
        // `staging` doesn't match any per-env group, so only `common` is
        // available. The reference to `${apikey}` in the app's env must error.
        let err = Project::load_and_resolve(
            &p,
            None,
            None,
            &[("env".to_string(), "staging".to_string())],
            None,
        )
        .unwrap_err();
        assert!(err.to_string().contains("apikey"));
        std::fs::remove_file(&p).ok();
    }

    fn write_named(name: &str, contents: &str) -> std::path::PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!(
            "clever-project-test-{}-{}",
            std::process::id(),
            rand_suffix()
        ));
        std::fs::create_dir_all(&p).unwrap();
        p.push(name);
        std::fs::write(&p, contents).unwrap();
        p
    }

    #[test]
    fn secrets_auto_discover_default_file() {
        let project_path = write_named(
            "myproj.yaml",
            "name: P\norg: o\nregion: par\napps:\n  a:\n    name: ${secrets.apikey}-app\n    kind: node\n",
        );
        let dir = project_path.parent().unwrap();
        std::fs::write(dir.join("myproj.secrets"), "apikey: deadbeef\n").unwrap();

        let (project, _r) =
            Project::load_and_resolve(&project_path, None, None, &[], None).unwrap();
        assert_eq!(project.apps.get("a").unwrap().name, "deadbeef-app");
    }

    #[test]
    fn secrets_env_specific_overrides_default() {
        let project_path = write_named(
            "p.yaml",
            "name: P\norg: o\nregion: par\napps:\n  a:\n    name: x\n    kind: node\n    env:\n      K: ${secrets.token}\n",
        );
        let dir = project_path.parent().unwrap();
        std::fs::write(dir.join("p.secrets"), "token: default-token\n").unwrap();
        std::fs::write(dir.join("p.dev.secrets"), "token: dev-token\n").unwrap();

        let (project, _r) = Project::load_and_resolve(
            &project_path,
            None,
            None,
            &[("env".to_string(), "dev".to_string())],
            None,
        )
        .unwrap();
        assert_eq!(
            project.apps.get("a").unwrap().env.get("K").unwrap(),
            "dev-token"
        );
    }

    #[test]
    fn secrets_usable_inside_variables_section() {
        let project_path = write_named(
            "x.yaml",
            "name: P\norg: o\nregion: par\nvariables:\n  apikey: ${secrets.real}\napps:\n  a:\n    name: x\n    kind: node\n    env:\n      K: ${apikey}\n",
        );
        let dir = project_path.parent().unwrap();
        std::fs::write(dir.join("x.secrets"), "real: super-secret\n").unwrap();

        let (project, _r) =
            Project::load_and_resolve(&project_path, None, None, &[], None).unwrap();
        assert_eq!(
            project.apps.get("a").unwrap().env.get("K").unwrap(),
            "super-secret"
        );
    }

    #[test]
    fn secrets_explicit_path_overrides_autodiscovery() {
        let project_path = write_named(
            "y.yaml",
            "name: P\norg: o\nregion: par\napps:\n  a:\n    name: ${secrets.k}-app\n    kind: node\n",
        );
        let dir = project_path.parent().unwrap();
        std::fs::write(dir.join("y.secrets"), "k: from-default\n").unwrap();
        let explicit = dir.join("custom.secrets");
        std::fs::write(&explicit, "k: from-explicit\n").unwrap();

        let (project, _r) =
            Project::load_and_resolve(&project_path, None, None, &[], Some(&explicit)).unwrap();
        assert_eq!(project.apps.get("a").unwrap().name, "from-explicit-app");
    }

    #[test]
    fn variables_file_yaml_loads_flat_pairs() {
        let p = write_tmp("yaml", "foo: bar\ncount: 3\nflag: true\n");
        let pairs = load_variables_file(&p).unwrap();
        assert_eq!(
            pairs,
            vec![
                ("foo".to_string(), "bar".to_string()),
                ("count".to_string(), "3".to_string()),
                ("flag".to_string(), "true".to_string()),
            ]
        );
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn variables_file_json_loads_flat_pairs() {
        let p = write_tmp("json", r#"{"foo":"bar","x":"y"}"#);
        let pairs = load_variables_file(&p).unwrap();
        assert!(pairs.contains(&("foo".to_string(), "bar".to_string())));
        assert!(pairs.contains(&("x".to_string(), "y".to_string())));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn variables_file_rejects_nested() {
        let p = write_tmp("yaml", "outer:\n  nested: value\n");
        let err = load_variables_file(&p).unwrap_err();
        assert!(err.to_string().contains("scalar"));
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn variable_path_overridden_by_explicit_variable() {
        // Simulate how apply/delete merge sources: file vars are pushed
        // first, then --variable, so --variable wins.
        let p = write_tmp("yaml", "foo: from-file\n");
        let mut combined: Vec<(String, String)> = load_variables_file(&p).unwrap();
        combined.push(("foo".to_string(), "from-cli".to_string()));
        // Build a resolver to confirm the last-write-wins behavior.
        let r = crate::interpolate::Resolver::build(
            &IndexMap::new(),
            &combined,
            "o".to_string(),
            "par".to_string(),
        )
        .unwrap();
        assert_eq!(r.resolve_string("${foo}").unwrap(), "from-cli");
        std::fs::remove_file(&p).ok();
    }

    #[test]
    fn secrets_file_accepts_json_content() {
        let project_path = write_named(
            "j.yaml",
            "name: P\norg: o\nregion: par\napps:\n  a:\n    name: ${secrets.apikey}\n    kind: node\n",
        );
        let dir = project_path.parent().unwrap();
        // The file is named `.secrets` but contains JSON. Should still load.
        std::fs::write(dir.join("j.secrets"), r#"{"apikey":"json-secret"}"#).unwrap();
        let (project, _r) =
            Project::load_and_resolve(&project_path, None, None, &[], None).unwrap();
        assert_eq!(project.apps.get("a").unwrap().name, "json-secret");
    }

    #[test]
    fn secrets_file_invalid_in_both_formats_errors() {
        let project_path = write_named(
            "bad.yaml",
            "name: P\norg: o\nregion: par\napps:\n  a:\n    name: x\n    kind: node\n",
        );
        let dir = project_path.parent().unwrap();
        // Non-mapping at the root would also be rejected — but here let's
        // craft something neither parser will accept (unbalanced braces).
        std::fs::write(
            dir.join("bad.secrets"),
            "{ this is: not valid: in :: any format ]",
        )
        .unwrap();
        let err = Project::load_and_resolve(&project_path, None, None, &[], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("YAML") || msg.contains("JSON"));
    }

    #[test]
    fn missing_secret_errors() {
        let project_path = write_named(
            "z.yaml",
            "name: P\norg: o\nregion: par\napps:\n  a:\n    name: ${secrets.nope}\n    kind: node\n",
        );
        let err = Project::load_and_resolve(&project_path, None, None, &[], None).unwrap_err();
        assert!(err.to_string().contains("secrets.nope") || err.to_string().contains("nope"));
    }

    #[test]
    fn per_env_rejects_mixed_form() {
        let mixed = r#"
name: X
org: o
region: par
variables:
  flat_thing: hello
  group:
    nested: thing
apps: {}
"#;
        let p = write_tmp("yaml", mixed);
        let err = Project::load_and_resolve(&p, None, None, &[], None).unwrap_err();
        assert!(err.to_string().contains("either"));
        std::fs::remove_file(&p).ok();
    }
}