syncable-cli 0.37.1

A Rust-based CLI that analyzes code repositories and generates Infrastructure as Code configurations
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
//! Service endpoint discovery and env var matching for inter-service linking
//!
//! When deploying service A that calls service B, this module discovers
//! already-deployed services, shows their public URLs, and offers to inject
//! them as environment variables.

use crate::platform::api::types::{CloudRunnerNetwork, DeployedService, DeploymentSecretInput};
use crate::wizard::render::wizard_render_config;
use colored::Colorize;
use inquire::{Confirm, InquireError, MultiSelect, Text};

/// A deployed service with a reachable URL (public or private network).
#[derive(Debug, Clone)]
pub struct AvailableServiceEndpoint {
    pub service_name: String,
    /// The URL to use for connecting — either public URL or private IP.
    pub url: String,
    /// Whether this endpoint is a private network address (no public URL).
    pub is_private: bool,
    /// Cloud provider this service runs on (e.g. "hetzner", "gcp", "azure").
    pub cloud_provider: Option<String>,
    pub status: String,
}

/// Confidence level for an env-var-to-service match.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum MatchConfidence {
    Low,
    Medium,
    High,
}

/// A suggested mapping: env var -> deployed service URL.
#[derive(Debug, Clone)]
pub struct EndpointSuggestion {
    pub env_var_name: String,
    pub service: AvailableServiceEndpoint,
    pub confidence: MatchConfidence,
    pub reason: String,
}

// ---------------------------------------------------------------------------
// Suffixes that indicate a URL-like env var
// ---------------------------------------------------------------------------

const URL_SUFFIXES: &[&str] = &[
    "_URL",
    "_SERVICE_URL",
    "_ENDPOINT",
    "_HOST",
    "_BASE",
    "_BASE_URL",
    "_API_URL",
    "_URI",
];

// ---------------------------------------------------------------------------
// Core functions
// ---------------------------------------------------------------------------

/// Filter deployments down to services that have a reachable URL (public or
/// private) and are not in a known-bad state.
///
/// The `list_deployments` API may return multiple records per service (one per
/// deploy attempt). We deduplicate by `service_name`, keeping the most recent
/// record (the API returns most-recent-first).
///
/// A service is included if it has a `public_url` OR a `private_ip` (for
/// internal services deployed on a private network without public access).
pub fn get_available_endpoints(deployments: &[DeployedService]) -> Vec<AvailableServiceEndpoint> {
    const EXCLUDED_STATUSES: &[&str] = &[
        "failed",
        "cancelled",
        "canceled",
        "pending",
        "processing",
        "building",
        "deploying",
        "generating",
        "deleting",
        "deleted",
    ];

    let mut seen_services = std::collections::HashSet::new();

    deployments
        .iter()
        .filter_map(|d| {
            // Deduplicate: keep only the first (most recent) record per service
            if !seen_services.insert(d.service_name.clone()) {
                return None;
            }

            let status_lower = d.status.to_lowercase();
            if EXCLUDED_STATUSES.iter().any(|&s| status_lower == s) {
                log::debug!(
                    "Skipping service '{}' (status: {}): excluded status",
                    d.service_name,
                    d.status
                );
                return None;
            }

            // Prefer public URL; fall back to private IP
            let public_url = d.public_url.as_deref().unwrap_or("").trim();
            let private_ip = d.private_ip.as_deref().unwrap_or("").trim();

            if !public_url.is_empty() {
                log::debug!(
                    "Available endpoint: '{}' -> {} (public, status: {})",
                    d.service_name,
                    public_url,
                    d.status
                );
                Some(AvailableServiceEndpoint {
                    service_name: d.service_name.clone(),
                    url: public_url.to_string(),
                    is_private: false,
                    cloud_provider: d.cloud_provider.clone(),
                    status: d.status.clone(),
                })
            } else if !private_ip.is_empty() {
                // Build a usable URL from the private IP.
                // Services on Hetzner private networks are reachable by IP from
                // other services on the same network.
                let url = format!("http://{}", private_ip);
                log::debug!(
                    "Available endpoint: '{}' -> {} (private, status: {})",
                    d.service_name,
                    url,
                    d.status
                );
                Some(AvailableServiceEndpoint {
                    service_name: d.service_name.clone(),
                    url,
                    is_private: true,
                    cloud_provider: d.cloud_provider.clone(),
                    status: d.status.clone(),
                })
            } else {
                log::debug!(
                    "Skipping service '{}' (status: {}): no public_url or private_ip",
                    d.service_name,
                    d.status
                );
                None
            }
        })
        .collect()
}

/// Filter endpoints so that private-network endpoints only appear when they
/// share the same cloud provider as the service being deployed.
///
/// Public endpoints are always kept regardless of provider — they're reachable
/// from anywhere. Private endpoints are only reachable within the same provider
/// network.
pub fn filter_endpoints_for_provider(
    endpoints: Vec<AvailableServiceEndpoint>,
    target_provider: &str,
) -> Vec<AvailableServiceEndpoint> {
    let target = target_provider.to_lowercase();
    endpoints
        .into_iter()
        .filter(|ep| {
            if !ep.is_private {
                // Public URLs are reachable from any provider
                return true;
            }
            // Private IPs are only useful on the same provider network
            ep.cloud_provider
                .as_ref()
                .map(|p| p.to_lowercase() == target)
                .unwrap_or(false)
        })
        .collect()
}

/// Check whether an env var name looks like it holds a URL.
pub fn is_url_env_var(name: &str) -> bool {
    let upper = name.to_uppercase();
    URL_SUFFIXES.iter().any(|suffix| upper.ends_with(suffix))
}

/// Strip the URL-like suffix from an env var name to extract a service hint.
///
/// `SENTIMENT_SERVICE_URL` -> `"sentiment"`
/// `API_BASE` -> `"api"`
/// `NODE_ENV` -> `None`
pub fn extract_service_hint(env_var_name: &str) -> Option<String> {
    let upper = env_var_name.to_uppercase();

    // Try suffixes longest-first so _SERVICE_URL is tried before _URL
    let mut suffixes: Vec<&&str> = URL_SUFFIXES.iter().collect();
    suffixes.sort_by_key(|b| std::cmp::Reverse(b.len()));

    for suffix in suffixes {
        if upper.ends_with(suffix) {
            let prefix = &upper[..upper.len() - suffix.len()];
            if prefix.is_empty() {
                return None;
            }
            return Some(prefix.to_lowercase());
        }
    }
    None
}

/// Normalize a name for matching: lowercase, strip `-` and `_`.
fn normalize(s: &str) -> String {
    s.to_lowercase().replace(['-', '_'], "")
}

/// Split a name into tokens on `_` and `-`.
fn tokenize(s: &str) -> Vec<String> {
    s.to_lowercase()
        .split(['_', '-'])
        .filter(|t| !t.is_empty())
        .map(String::from)
        .collect()
}

/// Match a service hint against a service name.
///
/// Returns `None` if there is no meaningful overlap.
pub fn match_hint_to_service(hint: &str, service_name: &str) -> Option<MatchConfidence> {
    let nh = normalize(hint);
    let ns = normalize(service_name);

    if nh.is_empty() || ns.is_empty() {
        return None;
    }

    // Exact match or hint is prefix of service (normalized)
    if nh == ns || ns.starts_with(&nh) {
        return Some(MatchConfidence::High);
    }

    // One contains the other (normalized, no separators)
    if ns.contains(&nh) || nh.contains(&ns) {
        return Some(MatchConfidence::Medium);
    }

    // Check if either normalized form is a prefix of the other
    // (catches "contacts" ~ "contactintelligence" via shared stem)
    if nh.starts_with(&ns) || ns.starts_with(&nh) {
        return Some(MatchConfidence::Medium);
    }

    // Token overlap: exact or prefix match between tokens
    let hint_tokens = tokenize(hint);
    let svc_tokens = tokenize(service_name);
    let overlap = hint_tokens
        .iter()
        .filter(|ht| {
            svc_tokens
                .iter()
                .any(|st| st == *ht || st.starts_with(ht.as_str()) || ht.starts_with(st.as_str()))
        })
        .count();

    if overlap == 0 {
        return None;
    }

    let max_tokens = hint_tokens.len().max(svc_tokens.len());
    if overlap * 2 >= max_tokens {
        Some(MatchConfidence::Medium)
    } else {
        Some(MatchConfidence::Low)
    }
}

/// For each URL-like env var, find the best matching deployed service.
///
/// Returns suggestions sorted by confidence (highest first).
pub fn match_env_vars_to_services(
    env_var_names: &[String],
    endpoints: &[AvailableServiceEndpoint],
) -> Vec<EndpointSuggestion> {
    let mut suggestions = Vec::new();

    for var_name in env_var_names {
        if !is_url_env_var(var_name) {
            continue;
        }
        let hint = match extract_service_hint(var_name) {
            Some(h) => h,
            None => continue,
        };

        // Find best match
        let mut best: Option<(MatchConfidence, &AvailableServiceEndpoint)> = None;
        for ep in endpoints {
            if let Some(conf) = match_hint_to_service(&hint, &ep.service_name) {
                if best.as_ref().is_none_or(|(bc, _)| conf > *bc) {
                    best = Some((conf, ep));
                }
            }
        }

        if let Some((confidence, ep)) = best {
            suggestions.push(EndpointSuggestion {
                env_var_name: var_name.clone(),
                service: ep.clone(),
                confidence,
                reason: format!(
                    "Env var '{}' (hint '{}') matches service '{}' ({:?})",
                    var_name, hint, ep.service_name, confidence
                ),
            });
        }
    }

    suggestions.sort_by(|a, b| b.confidence.cmp(&a.confidence));
    suggestions
}

/// Generate a default env var name for a service.
///
/// `"sentiment-analysis"` -> `"SENTIMENT_ANALYSIS_URL"`
pub fn suggest_env_var_name(service_name: &str) -> String {
    let base = service_name.to_uppercase().replace('-', "_");
    format!("{}_URL", base)
}

// ---------------------------------------------------------------------------
// Wizard UI
// ---------------------------------------------------------------------------

/// Interactive prompt to link deployed service URLs as env vars.
///
/// Shows available endpoints, lets the user select which to link, and
/// prompts for each env var name. Returns `DeploymentSecretInput` entries
/// with `is_secret: false` (URLs are not secrets).
pub fn collect_service_endpoint_env_vars(
    endpoints: &[AvailableServiceEndpoint],
) -> Vec<DeploymentSecretInput> {
    if endpoints.is_empty() {
        return Vec::new();
    }

    println!();
    println!(
        "{}",
        "─── Deployed Service Endpoints ────────────────────".dimmed()
    );
    println!(
        "  Found {} running service(s) with reachable URLs:",
        endpoints.len().to_string().cyan()
    );
    for ep in endpoints {
        let access_label = if ep.is_private {
            " (private network)"
        } else {
            ""
        };
        println!(
            "    {} {:<30} {}{}",
            "".green(),
            ep.service_name.cyan(),
            ep.url.dimmed(),
            access_label.yellow()
        );
    }
    println!();

    // Ask if user wants to link any
    let wants_link = match Confirm::new("Link any deployed service URLs as env vars?")
        .with_default(true)
        .with_help_message("Inject deployed service URLs as environment variables")
        .prompt()
    {
        Ok(v) => v,
        Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
            return Vec::new();
        }
        Err(_) => return Vec::new(),
    };

    if !wants_link {
        return Vec::new();
    }

    // Build labels for multi-select
    let labels: Vec<String> = endpoints
        .iter()
        .map(|ep| {
            let suffix = if ep.is_private { " [private]" } else { "" };
            format!("{} ({}){}", ep.service_name, ep.url, suffix)
        })
        .collect();

    let selected = match MultiSelect::new("Select services to link:", labels.clone())
        .with_render_config(wizard_render_config())
        .with_help_message("Space to toggle, Enter to confirm")
        .prompt()
    {
        Ok(s) if !s.is_empty() => s,
        Ok(_) => return Vec::new(),
        Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
            return Vec::new();
        }
        Err(_) => return Vec::new(),
    };

    // Map selected labels back to endpoints
    let mut result = Vec::new();
    for sel_label in &selected {
        let idx = match labels.iter().position(|l| l == sel_label) {
            Some(i) => i,
            None => continue,
        };
        let ep = &endpoints[idx];
        let default_name = suggest_env_var_name(&ep.service_name);

        let var_name = match Text::new(&format!("Env var name for '{}':", ep.service_name))
            .with_default(&default_name)
            .with_help_message("Environment variable name to hold this service URL")
            .prompt()
        {
            Ok(name) => name.trim().to_uppercase(),
            Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
                break;
            }
            Err(_) => break,
        };

        if var_name.is_empty() {
            continue;
        }

        let private_note = if ep.is_private {
            " (private network)"
        } else {
            ""
        };
        println!(
            "  {} {} = {}{}",
            "".green(),
            var_name.cyan(),
            ep.url.dimmed(),
            private_note.yellow()
        );

        result.push(DeploymentSecretInput {
            key: var_name,
            value: ep.url.clone(),
            is_secret: false,
        });
    }

    result
}

// ---------------------------------------------------------------------------
// Network endpoint discovery
// ---------------------------------------------------------------------------

/// A network resource with its connection-relevant details.
///
/// Extracted from `CloudRunnerNetwork` records, filtered for the target
/// provider and environment. Contains key-value pairs of useful connection
/// info (VPC_ID, DEFAULT_DOMAIN, etc.) that can be injected as env vars.
#[derive(Debug, Clone)]
pub struct NetworkEndpointInfo {
    pub network_id: String,
    pub cloud_provider: String,
    pub region: String,
    pub status: String,
    pub environment_id: Option<String>,
    /// Key-value pairs of useful connection info for this network
    /// e.g., ("NETWORK_VPC_ID", "12345"), ("NETWORK_DEFAULT_DOMAIN", "my-app.azurecontainerapps.io")
    pub connection_details: Vec<(String, String)>,
}

/// Extract useful connection details from cloud runner networks.
///
/// Returns only networks that are "ready" and on the target provider.
/// Optionally filters by environment ID (shared/default networks with no
/// environment_id are always included).
pub fn extract_network_endpoints(
    networks: &[CloudRunnerNetwork],
    target_provider: &str,
    target_environment_id: Option<&str>,
) -> Vec<NetworkEndpointInfo> {
    networks
        .iter()
        .filter(|n| {
            n.status == "ready"
                && n.cloud_provider.eq_ignore_ascii_case(target_provider)
                && (target_environment_id.is_none()
                    || n.environment_id.as_deref() == target_environment_id
                    || n.environment_id.is_none()) // shared/default networks
        })
        .map(|n| {
            let mut details = Vec::new();

            // Provider-generic connection details
            if let Some(ref vpc_id) = n.vpc_id {
                details.push(("NETWORK_VPC_ID".to_string(), vpc_id.clone()));
            }
            if let Some(ref vpc_name) = n.vpc_name {
                details.push(("NETWORK_VPC_NAME".to_string(), vpc_name.clone()));
            }
            if let Some(ref subnet_id) = n.subnet_id {
                details.push(("NETWORK_SUBNET_ID".to_string(), subnet_id.clone()));
            }
            // Azure-specific
            if let Some(ref cae_name) = n.container_app_environment_name {
                details.push(("AZURE_CONTAINER_APP_ENV_NAME".to_string(), cae_name.clone()));
            }
            if let Some(ref domain) = n.default_domain {
                details.push(("NETWORK_DEFAULT_DOMAIN".to_string(), domain.clone()));
            }
            if let Some(ref rg) = n.resource_group_name {
                details.push(("AZURE_RESOURCE_GROUP".to_string(), rg.clone()));
            }
            // GCP-specific
            if let Some(ref connector_name) = n.vpc_connector_name {
                details.push(("GCP_VPC_CONNECTOR".to_string(), connector_name.clone()));
            }

            NetworkEndpointInfo {
                network_id: n.id.clone(),
                cloud_provider: n.cloud_provider.clone(),
                region: n.region.clone(),
                status: n.status.clone(),
                environment_id: n.environment_id.clone(),
                connection_details: details,
            }
        })
        .collect()
}

/// Interactive prompt to offer network connection details as env vars.
///
/// Shows discovered network info and lets the user select which to inject.
/// Returns `DeploymentSecretInput` entries with `is_secret: false` (network
/// identifiers are infrastructure metadata, not secrets).
pub fn collect_network_endpoint_env_vars(
    network_endpoints: &[NetworkEndpointInfo],
) -> Vec<DeploymentSecretInput> {
    if network_endpoints.is_empty() {
        return Vec::new();
    }

    // Flatten all connection details across networks
    let all_details: Vec<(&NetworkEndpointInfo, &str, &str)> = network_endpoints
        .iter()
        .flat_map(|ne| {
            ne.connection_details
                .iter()
                .map(move |(k, v)| (ne, k.as_str(), v.as_str()))
        })
        .collect();

    if all_details.is_empty() {
        return Vec::new();
    }

    println!();
    println!(
        "{}",
        "─── Private Network Resources ────────────────────".dimmed()
    );
    for ne in network_endpoints {
        println!(
            "  {} {} network in {} ({})",
            "".green(),
            ne.cloud_provider.cyan(),
            ne.region,
            ne.status,
        );
        for (k, v) in &ne.connection_details {
            println!("    {} = {}", k.dimmed(), v);
        }
    }
    println!();

    let wants_inject = match Confirm::new("Inject any network details as env vars?")
        .with_default(false)
        .with_help_message("Add network identifiers like VPC_ID, DEFAULT_DOMAIN as env vars")
        .prompt()
    {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };

    if !wants_inject {
        return Vec::new();
    }

    let labels: Vec<String> = all_details
        .iter()
        .map(|(ne, k, v)| format!("{} = {} [{}]", k, v, ne.cloud_provider))
        .collect();

    let selected = match MultiSelect::new("Select network details to inject:", labels.clone())
        .with_render_config(wizard_render_config())
        .with_help_message("Space to toggle, Enter to confirm")
        .prompt()
    {
        Ok(s) if !s.is_empty() => s,
        _ => return Vec::new(),
    };

    selected
        .iter()
        .filter_map(|label| {
            let idx = labels.iter().position(|l| l == label)?;
            let (_, key, value) = &all_details[idx];
            Some(DeploymentSecretInput {
                key: key.to_string(),
                value: value.to_string(),
                is_secret: false,
            })
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_extract_service_hint() {
        assert_eq!(
            extract_service_hint("SENTIMENT_SERVICE_URL"),
            Some("sentiment".to_string())
        );
        assert_eq!(extract_service_hint("API_BASE"), Some("api".to_string()));
        assert_eq!(extract_service_hint("NODE_ENV"), None);
        assert_eq!(
            extract_service_hint("CONTACTS_API_URL"),
            Some("contacts".to_string())
        );
        assert_eq!(
            extract_service_hint("BACKEND_ENDPOINT"),
            Some("backend".to_string())
        );
    }

    #[test]
    fn test_match_hint_exact() {
        assert_eq!(
            match_hint_to_service("sentiment", "sentiment"),
            Some(MatchConfidence::High)
        );
    }

    #[test]
    fn test_match_hint_prefix() {
        assert_eq!(
            match_hint_to_service("sentiment", "sentiment-analysis"),
            Some(MatchConfidence::High)
        );
    }

    #[test]
    fn test_match_hint_containment() {
        assert_eq!(
            match_hint_to_service("contacts", "contact-intelligence"),
            Some(MatchConfidence::Medium)
        );
    }

    #[test]
    fn test_no_match() {
        assert_eq!(
            match_hint_to_service("database", "sentiment-analysis"),
            None
        );
    }

    #[test]
    fn test_is_url_env_var() {
        assert!(is_url_env_var("DATABASE_URL"));
        assert!(is_url_env_var("BACKEND_SERVICE_URL"));
        assert!(is_url_env_var("API_ENDPOINT"));
        assert!(is_url_env_var("SERVICE_HOST"));
        assert!(is_url_env_var("API_BASE"));
        assert!(is_url_env_var("APP_BASE_URL"));
        assert!(is_url_env_var("BACKEND_API_URL"));
        assert!(is_url_env_var("SERVICE_URI"));
        assert!(!is_url_env_var("NODE_ENV"));
        assert!(!is_url_env_var("PORT"));
        assert!(!is_url_env_var("DEBUG"));
    }

    #[test]
    fn test_suggest_env_var_name() {
        assert_eq!(
            suggest_env_var_name("sentiment-analysis"),
            "SENTIMENT_ANALYSIS_URL"
        );
        assert_eq!(suggest_env_var_name("backend"), "BACKEND_URL");
        assert_eq!(
            suggest_env_var_name("contact-intelligence"),
            "CONTACT_INTELLIGENCE_URL"
        );
    }

    #[test]
    fn test_match_env_vars_to_services() {
        let endpoints = vec![
            AvailableServiceEndpoint {
                service_name: "sentiment-analysis".to_string(),
                url: "https://sentiment-abc.syncable.dev".to_string(),
                is_private: false,
                cloud_provider: Some("hetzner".to_string()),
                status: "running".to_string(),
            },
            AvailableServiceEndpoint {
                service_name: "contact-intelligence".to_string(),
                url: "https://contact-def.syncable.dev".to_string(),
                is_private: false,
                cloud_provider: Some("hetzner".to_string()),
                status: "running".to_string(),
            },
        ];

        let env_vars = vec![
            "SENTIMENT_SERVICE_URL".to_string(),
            "CONTACTS_API_URL".to_string(),
            "NODE_ENV".to_string(),     // not a URL var
            "DATABASE_URL".to_string(), // no matching service
        ];

        let suggestions = match_env_vars_to_services(&env_vars, &endpoints);

        // SENTIMENT_SERVICE_URL should match sentiment-analysis
        let sent = suggestions
            .iter()
            .find(|s| s.env_var_name == "SENTIMENT_SERVICE_URL");
        assert!(sent.is_some());
        assert_eq!(sent.unwrap().service.service_name, "sentiment-analysis");
        assert_eq!(sent.unwrap().confidence, MatchConfidence::High);

        // CONTACTS_API_URL should match contact-intelligence
        let cont = suggestions
            .iter()
            .find(|s| s.env_var_name == "CONTACTS_API_URL");
        assert!(cont.is_some());
        assert_eq!(cont.unwrap().service.service_name, "contact-intelligence");

        // NODE_ENV should not be in suggestions (not a URL var)
        assert!(suggestions.iter().all(|s| s.env_var_name != "NODE_ENV"));
    }

    #[test]
    fn test_get_available_endpoints() {
        use crate::platform::api::types::DeployedService;
        use chrono::Utc;

        let deployments = vec![
            DeployedService {
                id: "1".to_string(),
                project_id: "p1".to_string(),
                service_name: "running-svc".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "running".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: Some("https://running.example.com".to_string()),
                private_ip: None,
                cloud_provider: None,
                created_at: Utc::now(),
            },
            DeployedService {
                id: "2".to_string(),
                project_id: "p1".to_string(),
                service_name: "no-url-svc".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "running".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: None,
                private_ip: None,
                cloud_provider: None,
                created_at: Utc::now(),
            },
            DeployedService {
                id: "3".to_string(),
                project_id: "p1".to_string(),
                service_name: "failed-svc".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "failed".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: Some("https://failed.example.com".to_string()),
                private_ip: None,
                cloud_provider: None,
                created_at: Utc::now(),
            },
            DeployedService {
                id: "4".to_string(),
                project_id: "p1".to_string(),
                service_name: "healthy-svc".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "healthy".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: Some("https://healthy.example.com".to_string()),
                private_ip: None,
                cloud_provider: None,
                created_at: Utc::now(),
            },
        ];

        let endpoints = get_available_endpoints(&deployments);
        assert_eq!(endpoints.len(), 2);
        assert_eq!(endpoints[0].service_name, "running-svc");
        assert_eq!(endpoints[1].service_name, "healthy-svc");
    }

    #[test]
    fn test_get_available_endpoints_includes_private_ip() {
        use crate::platform::api::types::DeployedService;
        use chrono::Utc;

        let deployments = vec![
            DeployedService {
                id: "1".to_string(),
                project_id: "p1".to_string(),
                service_name: "public-svc".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "healthy".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: Some("https://public.example.com".to_string()),
                private_ip: Some("10.0.0.2".to_string()),
                cloud_provider: Some("hetzner".to_string()),
                created_at: Utc::now(),
            },
            DeployedService {
                id: "2".to_string(),
                project_id: "p1".to_string(),
                service_name: "internal-svc".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "healthy".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: None,
                private_ip: Some("10.0.0.3".to_string()),
                cloud_provider: Some("hetzner".to_string()),
                created_at: Utc::now(),
            },
            DeployedService {
                id: "3".to_string(),
                project_id: "p1".to_string(),
                service_name: "ghost-svc".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "healthy".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: None,
                private_ip: None,
                cloud_provider: None,
                created_at: Utc::now(),
            },
        ];

        let endpoints = get_available_endpoints(&deployments);
        assert_eq!(endpoints.len(), 2);

        // Public service uses public URL, not private IP
        assert_eq!(endpoints[0].service_name, "public-svc");
        assert_eq!(endpoints[0].url, "https://public.example.com");
        assert!(!endpoints[0].is_private);

        // Internal service uses private IP
        assert_eq!(endpoints[1].service_name, "internal-svc");
        assert_eq!(endpoints[1].url, "http://10.0.0.3");
        assert!(endpoints[1].is_private);
    }

    #[test]
    fn test_get_available_endpoints_deduplicates() {
        use crate::platform::api::types::DeployedService;
        use chrono::Utc;

        // Simulate API returning two records for same service (most recent first)
        let deployments = vec![
            DeployedService {
                id: "2".to_string(),
                project_id: "p1".to_string(),
                service_name: "backend".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "running".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: Some("https://backend.example.com".to_string()),
                private_ip: None,
                cloud_provider: None,
                created_at: Utc::now(),
            },
            DeployedService {
                id: "1".to_string(),
                project_id: "p1".to_string(),
                service_name: "backend".to_string(),
                repository_full_name: "org/repo".to_string(),
                status: "failed".to_string(),
                backstage_task_id: None,
                commit_sha: None,
                public_url: Some("https://backend-old.example.com".to_string()),
                private_ip: None,
                cloud_provider: None,
                created_at: Utc::now(),
            },
        ];

        let endpoints = get_available_endpoints(&deployments);
        assert_eq!(endpoints.len(), 1);
        assert_eq!(endpoints[0].url, "https://backend.example.com");
    }

    #[test]
    fn test_get_available_endpoints_accepts_unknown_statuses() {
        use crate::platform::api::types::DeployedService;
        use chrono::Utc;

        // A service with an unexpected status but a public URL should be included
        let deployments = vec![DeployedService {
            id: "1".to_string(),
            project_id: "p1".to_string(),
            service_name: "api-svc".to_string(),
            repository_full_name: "org/repo".to_string(),
            status: "succeeded".to_string(),
            backstage_task_id: None,
            commit_sha: None,
            public_url: Some("https://api.example.com".to_string()),
            private_ip: None,
            cloud_provider: None,
            created_at: Utc::now(),
        }];

        let endpoints = get_available_endpoints(&deployments);
        assert_eq!(endpoints.len(), 1);
        assert_eq!(endpoints[0].service_name, "api-svc");
    }

    #[test]
    fn test_filter_endpoints_for_provider() {
        let endpoints = vec![
            // Public endpoint on Azure — should always be kept
            AvailableServiceEndpoint {
                service_name: "azure-api".to_string(),
                url: "https://azure-api.example.com".to_string(),
                is_private: false,
                cloud_provider: Some("azure".to_string()),
                status: "healthy".to_string(),
            },
            // Private endpoint on Hetzner — should be kept when deploying to Hetzner
            AvailableServiceEndpoint {
                service_name: "hetzner-worker".to_string(),
                url: "http://10.0.0.5".to_string(),
                is_private: true,
                cloud_provider: Some("hetzner".to_string()),
                status: "healthy".to_string(),
            },
            // Private endpoint on Azure — should NOT be kept when deploying to Hetzner
            AvailableServiceEndpoint {
                service_name: "azure-internal".to_string(),
                url: "http://10.1.0.5".to_string(),
                is_private: true,
                cloud_provider: Some("azure".to_string()),
                status: "healthy".to_string(),
            },
        ];

        // Deploying to Hetzner: keep public endpoints + Hetzner private only
        let filtered = filter_endpoints_for_provider(endpoints.clone(), "hetzner");
        assert_eq!(filtered.len(), 2);
        assert_eq!(filtered[0].service_name, "azure-api"); // public, always kept
        assert_eq!(filtered[1].service_name, "hetzner-worker"); // same provider

        // Deploying to Azure: keep public endpoints + Azure private only
        let filtered = filter_endpoints_for_provider(endpoints, "azure");
        assert_eq!(filtered.len(), 2);
        assert_eq!(filtered[0].service_name, "azure-api"); // public
        assert_eq!(filtered[1].service_name, "azure-internal"); // same provider
    }

    // =========================================================================
    // Network endpoint tests
    // =========================================================================

    fn make_network(
        id: &str,
        provider: &str,
        region: &str,
        status: &str,
        env_id: Option<&str>,
    ) -> CloudRunnerNetwork {
        CloudRunnerNetwork {
            id: id.to_string(),
            project_id: "proj-1".to_string(),
            organization_id: "org-1".to_string(),
            environment_id: env_id.map(String::from),
            cloud_provider: provider.to_string(),
            region: region.to_string(),
            vpc_id: None,
            vpc_name: None,
            subnet_id: None,
            vpc_connector_id: None,
            vpc_connector_name: None,
            resource_group_name: None,
            container_app_environment_id: None,
            container_app_environment_name: None,
            default_domain: None,
            status: status.to_string(),
            error_message: None,
        }
    }

    #[test]
    fn test_extract_network_endpoints_filters_by_provider_and_status() {
        let networks = vec![
            {
                let mut n = make_network("n1", "hetzner", "nbg1", "ready", Some("env-1"));
                n.vpc_id = Some("vpc-123".to_string());
                n.subnet_id = Some("subnet-456".to_string());
                n
            },
            // Different provider — should be excluded
            {
                let mut n = make_network("n2", "gcp", "us-central1", "ready", Some("env-1"));
                n.vpc_connector_name = Some("my-connector".to_string());
                n
            },
            // Same provider but not ready — should be excluded
            {
                let mut n = make_network("n3", "hetzner", "fsn1", "provisioning", Some("env-1"));
                n.vpc_id = Some("vpc-789".to_string());
                n
            },
        ];

        let endpoints = extract_network_endpoints(&networks, "hetzner", Some("env-1"));
        assert_eq!(endpoints.len(), 1);
        assert_eq!(endpoints[0].network_id, "n1");
        assert_eq!(endpoints[0].cloud_provider, "hetzner");
        assert_eq!(endpoints[0].connection_details.len(), 2);
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "NETWORK_VPC_ID" && v == "vpc-123")
        );
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "NETWORK_SUBNET_ID" && v == "subnet-456")
        );
    }

    #[test]
    fn test_extract_network_endpoints_azure() {
        let networks = vec![{
            let mut n = make_network("n1", "azure", "eastus", "ready", Some("env-1"));
            n.container_app_environment_name = Some("my-cae".to_string());
            n.default_domain = Some("my-app.azurecontainerapps.io".to_string());
            n.resource_group_name = Some("rg-prod".to_string());
            n
        }];

        let endpoints = extract_network_endpoints(&networks, "azure", Some("env-1"));
        assert_eq!(endpoints.len(), 1);
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "AZURE_CONTAINER_APP_ENV_NAME" && v == "my-cae")
        );
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "NETWORK_DEFAULT_DOMAIN" && v == "my-app.azurecontainerapps.io")
        );
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "AZURE_RESOURCE_GROUP" && v == "rg-prod")
        );
    }

    #[test]
    fn test_extract_network_endpoints_hetzner() {
        let networks = vec![{
            let mut n = make_network("n1", "hetzner", "nbg1", "ready", None);
            n.vpc_id = Some("hetz-vpc-1".to_string());
            n.subnet_id = Some("hetz-sub-1".to_string());
            n
        }];

        let endpoints = extract_network_endpoints(&networks, "hetzner", Some("env-1"));
        // Shared network (no environment_id) should be included
        assert_eq!(endpoints.len(), 1);
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "NETWORK_VPC_ID" && v == "hetz-vpc-1")
        );
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "NETWORK_SUBNET_ID" && v == "hetz-sub-1")
        );
    }

    #[test]
    fn test_extract_network_endpoints_gcp() {
        let networks = vec![{
            let mut n = make_network("n1", "gcp", "us-central1", "ready", Some("env-1"));
            n.vpc_connector_name =
                Some("projects/my-proj/locations/us-central1/connectors/vpc-conn".to_string());
            n
        }];

        let endpoints = extract_network_endpoints(&networks, "gcp", Some("env-1"));
        assert_eq!(endpoints.len(), 1);
        assert!(
            endpoints[0]
                .connection_details
                .iter()
                .any(|(k, v)| k == "GCP_VPC_CONNECTOR"
                    && v == "projects/my-proj/locations/us-central1/connectors/vpc-conn")
        );
    }

    #[test]
    fn test_extract_network_endpoints_filters_non_ready() {
        let networks = vec![
            {
                let mut n = make_network("n1", "hetzner", "nbg1", "error", Some("env-1"));
                n.vpc_id = Some("vpc-err".to_string());
                n
            },
            {
                let mut n = make_network("n2", "hetzner", "nbg1", "provisioning", Some("env-1"));
                n.vpc_id = Some("vpc-prov".to_string());
                n
            },
        ];

        let endpoints = extract_network_endpoints(&networks, "hetzner", Some("env-1"));
        assert!(endpoints.is_empty());
    }
}