adk-deploy 0.8.0

Deployment manifest, bundling, and control-plane client for ADK-Rust
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
use std::{collections::HashMap, fs, path::Path};

use serde::{Deserialize, Serialize};

use crate::{DeployError, DeployResult};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DeploymentManifest {
    pub agent: AgentConfig,
    #[serde(default)]
    pub build: BuildConfig,
    #[serde(default)]
    pub scaling: ScalingPolicy,
    #[serde(default)]
    pub health: HealthCheckConfig,
    #[serde(default)]
    pub strategy: DeploymentStrategyConfig,
    #[serde(default)]
    pub services: Vec<ServiceBinding>,
    #[serde(default)]
    pub secrets: Vec<SecretRef>,
    #[serde(default)]
    pub env: HashMap<String, EnvVarSpec>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub telemetry: Option<TelemetryConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<AgentAuthConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guardrails: Option<GuardrailConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realtime: Option<RealtimeConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub a2a: Option<A2aConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graph: Option<GraphConfig>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub plugins: Vec<PluginRef>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skills: Option<SkillConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interaction: Option<InteractionConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceInfo>,
}

impl DeploymentManifest {
    /// Load a deployment manifest from disk and validate it.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use adk_deploy::DeploymentManifest;
    /// use std::path::Path;
    ///
    /// let manifest = DeploymentManifest::from_path(Path::new("adk-deploy.toml")).unwrap();
    /// assert!(!manifest.agent.binary.is_empty());
    /// ```
    pub fn from_path(path: &Path) -> DeployResult<Self> {
        if !path.exists() {
            return Err(DeployError::ManifestNotFound { path: path.to_path_buf() });
        }
        let raw = fs::read_to_string(path)?;
        let manifest = toml::from_str::<DeploymentManifest>(&raw)
            .map_err(|error| DeployError::ManifestParse { message: error.to_string() })?;
        manifest.validate()?;
        Ok(manifest)
    }

    /// Serialize the manifest to TOML.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use adk_deploy::{AgentConfig, DeploymentManifest};
    ///
    /// let manifest = DeploymentManifest {
    ///     agent: AgentConfig::new("demo", "demo"),
    ///     ..DeploymentManifest::default()
    /// };
    /// let toml = manifest.to_toml_string().unwrap();
    /// assert!(toml.contains("[agent]"));
    /// ```
    pub fn to_toml_string(&self) -> DeployResult<String> {
        self.validate()?;
        toml::to_string_pretty(self)
            .map_err(|error| DeployError::ManifestParse { message: error.to_string() })
    }

    /// Validate manifest semantics before build or push.
    pub fn validate(&self) -> DeployResult<()> {
        use std::collections::BTreeSet;

        if self.agent.name.trim().is_empty() {
            return Err(DeployError::InvalidManifest {
                message: "agent.name must not be empty".to_string(),
            });
        }
        if self.agent.binary.trim().is_empty() {
            return Err(DeployError::InvalidManifest {
                message: "agent.binary must not be empty".to_string(),
            });
        }
        if self.scaling.min_instances > self.scaling.max_instances {
            return Err(DeployError::InvalidManifest {
                message:
                    "scaling.min_instances must be less than or equal to scaling.max_instances"
                        .to_string(),
            });
        }
        if self.strategy.kind == DeploymentStrategyKind::Canary {
            let traffic = self.strategy.traffic_percent.unwrap_or(10);
            if traffic == 0 || traffic > 100 {
                return Err(DeployError::InvalidManifest {
                    message:
                        "strategy.traffic_percent must be between 1 and 100 for canary deployments"
                            .to_string(),
                });
            }
        }
        let mut binding_names = BTreeSet::new();
        for binding in &self.services {
            if !binding_names.insert(binding.name.clone()) {
                return Err(DeployError::InvalidManifest {
                    message: format!("service binding names must be unique: '{}'", binding.name),
                });
            }
            if binding.mode == BindingMode::External
                && binding.connection_url.is_none()
                && binding.secret_ref.is_none()
            {
                return Err(DeployError::InvalidManifest {
                    message: format!(
                        "external service binding '{}' requires connection_url or secret_ref",
                        binding.name
                    ),
                });
            }
        }
        let declared_secrets: BTreeSet<&str> =
            self.secrets.iter().map(|secret| secret.key.as_str()).collect();
        for (key, value) in &self.env {
            if let EnvVarSpec::SecretRef { secret_ref } = value
                && !declared_secrets.contains(secret_ref.as_str())
            {
                return Err(DeployError::InvalidManifest {
                    message: format!("env '{key}' references undeclared secret '{secret_ref}'"),
                });
            }
        }
        if let Some(auth) = &self.auth {
            auth.validate()?;
        }
        if let Some(guardrails) = &self.guardrails {
            guardrails.validate()?;
        }
        if let Some(realtime) = &self.realtime {
            realtime.validate()?;
        }
        if let Some(graph) = &self.graph {
            graph.validate(&self.services)?;
        }
        let mut plugin_names = BTreeSet::new();
        for plugin in &self.plugins {
            if plugin.name.trim().is_empty() {
                return Err(DeployError::InvalidManifest {
                    message: "plugin.name must not be empty".to_string(),
                });
            }
            if !plugin_names.insert(plugin.name.clone()) {
                return Err(DeployError::InvalidManifest {
                    message: format!("plugin names must be unique: '{}'", plugin.name),
                });
            }
        }
        if let Some(skills) = &self.skills
            && skills.directory.trim().is_empty()
        {
            return Err(DeployError::InvalidManifest {
                message: "skills.directory must not be empty".to_string(),
            });
        }
        if let Some(interaction) = &self.interaction {
            interaction.validate()?;
        }
        Ok(())
    }
}

impl Default for DeploymentManifest {
    fn default() -> Self {
        Self {
            agent: AgentConfig::new("example-agent", "example-agent"),
            build: BuildConfig::default(),
            scaling: ScalingPolicy::default(),
            health: HealthCheckConfig::default(),
            strategy: DeploymentStrategyConfig::default(),
            services: Vec::new(),
            secrets: Vec::new(),
            env: HashMap::new(),
            telemetry: None,
            auth: None,
            guardrails: None,
            realtime: None,
            a2a: None,
            graph: None,
            plugins: Vec::new(),
            skills: None,
            interaction: None,
            source: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AgentConfig {
    pub name: String,
    pub binary: String,
    #[serde(default = "default_version")]
    pub version: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub toolchain: Option<String>,
}

impl AgentConfig {
    pub fn new(name: impl Into<String>, binary: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            binary: binary.into(),
            version: default_version(),
            description: None,
            toolchain: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct BuildConfig {
    #[serde(default = "default_profile")]
    pub profile: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    #[serde(default)]
    pub features: Vec<String>,
    #[serde(default)]
    pub system_deps: Vec<String>,
    #[serde(default)]
    pub assets: Vec<String>,
}

impl Default for BuildConfig {
    fn default() -> Self {
        Self {
            profile: default_profile(),
            target: None,
            features: Vec::new(),
            system_deps: Vec::new(),
            assets: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ScalingPolicy {
    #[serde(default = "default_min_instances")]
    pub min_instances: u32,
    #[serde(default = "default_max_instances")]
    pub max_instances: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_latency_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_cpu_percent: Option<u8>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_concurrent_requests: Option<u32>,
}

impl Default for ScalingPolicy {
    fn default() -> Self {
        Self {
            min_instances: default_min_instances(),
            max_instances: default_max_instances(),
            target_latency_ms: Some(500),
            target_cpu_percent: Some(70),
            target_concurrent_requests: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct HealthCheckConfig {
    #[serde(default = "default_health_path")]
    pub path: String,
    #[serde(default = "default_health_interval")]
    pub interval_secs: u64,
    #[serde(default = "default_health_timeout")]
    pub timeout_secs: u64,
    #[serde(default = "default_failure_threshold")]
    pub failure_threshold: u32,
}

impl Default for HealthCheckConfig {
    fn default() -> Self {
        Self {
            path: default_health_path(),
            interval_secs: default_health_interval(),
            timeout_secs: default_health_timeout(),
            failure_threshold: default_failure_threshold(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DeploymentStrategyConfig {
    #[serde(rename = "type")]
    pub kind: DeploymentStrategyKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub traffic_percent: Option<u8>,
}

impl Default for DeploymentStrategyConfig {
    fn default() -> Self {
        Self { kind: DeploymentStrategyKind::Rolling, traffic_percent: None }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum DeploymentStrategyKind {
    Rolling,
    BlueGreen,
    Canary,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ServiceBinding {
    pub name: String,
    pub kind: ServiceKind,
    #[serde(default)]
    pub mode: BindingMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub connection_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secret_ref: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ServiceKind {
    InMemory,
    Postgres,
    Redis,
    Sqlite,
    MongoDb,
    Neo4j,
    Firestore,
    Pgvector,
    RedisMemory,
    MongoMemory,
    Neo4jMemory,
    ArtifactStorage,
    McpServer,
    CheckpointPostgres,
    CheckpointRedis,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
pub enum BindingMode {
    #[default]
    Managed,
    External,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SecretRef {
    pub key: String,
    #[serde(default = "default_required")]
    pub required: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum EnvVarSpec {
    Plain(String),
    SecretRef { secret_ref: String },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SourceInfo {
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_name: Option<String>,
}

/// Declares how operators can interact with a deployed agent in the control plane.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct InteractionConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manual: Option<ManualInteractionConfig>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub triggers: Vec<TriggerInteractionConfig>,
}

impl InteractionConfig {
    fn validate(&self) -> DeployResult<()> {
        if let Some(manual) = &self.manual {
            manual.validate()?;
        }
        for trigger in &self.triggers {
            trigger.validate()?;
        }
        Ok(())
    }
}

/// Defines the default operator input experience for chat or manual-run agents.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ManualInteractionConfig {
    #[serde(default = "default_manual_input_label")]
    pub input_label: String,
    #[serde(default = "default_manual_prompt")]
    pub default_prompt: String,
}

impl ManualInteractionConfig {
    fn validate(&self) -> DeployResult<()> {
        if self.input_label.trim().is_empty() {
            return Err(DeployError::InvalidManifest {
                message: "interaction.manual.input_label must not be empty".to_string(),
            });
        }
        if self.default_prompt.trim().is_empty() {
            return Err(DeployError::InvalidManifest {
                message: "interaction.manual.default_prompt must not be empty".to_string(),
            });
        }
        Ok(())
    }
}

impl Default for ManualInteractionConfig {
    fn default() -> Self {
        Self { input_label: default_manual_input_label(), default_prompt: default_manual_prompt() }
    }
}

/// Describes a non-chat trigger so the console can show how the deployed agent is activated.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct TriggerInteractionConfig {
    pub id: String,
    pub name: String,
    pub kind: TriggerKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_prompt: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cron: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub event_source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub event_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<String>,
}

impl TriggerInteractionConfig {
    fn validate(&self) -> DeployResult<()> {
        if self.id.trim().is_empty() {
            return Err(DeployError::InvalidManifest {
                message: "interaction.triggers[].id must not be empty".to_string(),
            });
        }
        if self.name.trim().is_empty() {
            return Err(DeployError::InvalidManifest {
                message: "interaction.triggers[].name must not be empty".to_string(),
            });
        }
        match self.kind {
            TriggerKind::Webhook => {
                if self.path.as_deref().map(str::trim).is_none_or(str::is_empty) {
                    return Err(DeployError::InvalidManifest {
                        message: "interaction.triggers[].path is required for webhook triggers"
                            .to_string(),
                    });
                }
                if self.method.as_deref().map(str::trim).is_none_or(str::is_empty) {
                    return Err(DeployError::InvalidManifest {
                        message: "interaction.triggers[].method is required for webhook triggers"
                            .to_string(),
                    });
                }
            }
            TriggerKind::Schedule => {
                if self.cron.as_deref().map(str::trim).is_none_or(str::is_empty) {
                    return Err(DeployError::InvalidManifest {
                        message: "interaction.triggers[].cron is required for schedule triggers"
                            .to_string(),
                    });
                }
                if self.timezone.as_deref().map(str::trim).is_none_or(str::is_empty) {
                    return Err(DeployError::InvalidManifest {
                        message:
                            "interaction.triggers[].timezone is required for schedule triggers"
                                .to_string(),
                    });
                }
            }
            TriggerKind::Event => {
                if self.event_source.as_deref().map(str::trim).is_none_or(str::is_empty) {
                    return Err(DeployError::InvalidManifest {
                        message:
                            "interaction.triggers[].event_source is required for event triggers"
                                .to_string(),
                    });
                }
                if self.event_type.as_deref().map(str::trim).is_none_or(str::is_empty) {
                    return Err(DeployError::InvalidManifest {
                        message: "interaction.triggers[].event_type is required for event triggers"
                            .to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

/// Identifies the operator-visible trigger type for a deployment.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum TriggerKind {
    Webhook,
    Schedule,
    Event,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct TelemetryConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub otlp_endpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_name: Option<String>,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub resource_attributes: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AgentAuthConfig {
    pub mode: AuthModeSpec,
    #[serde(default)]
    pub required_scopes: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub issuer: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audience: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jwks_uri: Option<String>,
}

impl AgentAuthConfig {
    fn validate(&self) -> DeployResult<()> {
        if self.mode == AuthModeSpec::Disabled && !self.required_scopes.is_empty() {
            return Err(DeployError::InvalidManifest {
                message: "auth.required_scopes requires auth.mode != disabled".to_string(),
            });
        }
        if self.mode == AuthModeSpec::Oidc
            && (self.issuer.is_none() || self.audience.is_none() || self.jwks_uri.is_none())
        {
            return Err(DeployError::InvalidManifest {
                message: "auth.mode = oidc requires auth.issuer, auth.audience, and auth.jwks_uri"
                    .to_string(),
            });
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum AuthModeSpec {
    Disabled,
    Bearer,
    Oidc,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GuardrailConfig {
    #[serde(default)]
    pub pii_redaction: bool,
    #[serde(default)]
    pub content_filters: Vec<String>,
}

impl GuardrailConfig {
    fn validate(&self) -> DeployResult<()> {
        if !self.pii_redaction && self.content_filters.is_empty() {
            return Err(DeployError::InvalidManifest {
                message:
                    "guardrails must enable pii_redaction or declare at least one content_filter"
                        .to_string(),
            });
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RealtimeConfig {
    #[serde(default)]
    pub features: Vec<String>,
    #[serde(default)]
    pub sticky_sessions: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drain_timeout_secs: Option<u64>,
}

impl RealtimeConfig {
    fn validate(&self) -> DeployResult<()> {
        const ALLOWED: &[&str] = &["openai", "gemini", "vertex-live", "livekit", "openai-webrtc"];
        for feature in &self.features {
            if !ALLOWED.iter().any(|candidate| candidate == feature) {
                return Err(DeployError::InvalidManifest {
                    message: format!(
                        "unsupported realtime feature '{feature}'. valid values: {}",
                        ALLOWED.join(", ")
                    ),
                });
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct A2aConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub advertise_url: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GraphConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checkpoint_binding: Option<String>,
    #[serde(default)]
    pub hitl_enabled: bool,
}

impl GraphConfig {
    fn validate(&self, services: &[ServiceBinding]) -> DeployResult<()> {
        if let Some(binding_name) = &self.checkpoint_binding {
            let binding = services
                .iter()
                .find(|binding| binding.name == *binding_name)
                .ok_or_else(|| DeployError::InvalidManifest {
                    message: format!(
                        "graph.checkpoint_binding references unknown service binding '{binding_name}'"
                    ),
                })?;
            if !matches!(
                binding.kind,
                ServiceKind::CheckpointPostgres | ServiceKind::CheckpointRedis
            ) {
                return Err(DeployError::InvalidManifest {
                    message: format!(
                        "graph.checkpoint_binding '{}' must reference checkpoint-postgres or checkpoint-redis",
                        binding_name
                    ),
                });
            }
        } else if self.hitl_enabled {
            return Err(DeployError::InvalidManifest {
                message:
                    "graph.hitl_enabled requires graph.checkpoint_binding for resumable workflows"
                        .to_string(),
            });
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PluginRef {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SkillConfig {
    pub directory: String,
    #[serde(default)]
    pub hot_reload: bool,
}

fn default_version() -> String {
    "0.1.0".to_string()
}

fn default_profile() -> String {
    "release".to_string()
}

fn default_min_instances() -> u32 {
    1
}

fn default_max_instances() -> u32 {
    10
}

fn default_health_path() -> String {
    "/api/health".to_string()
}

fn default_health_interval() -> u64 {
    10
}

fn default_health_timeout() -> u64 {
    5
}

fn default_failure_threshold() -> u32 {
    3
}

fn default_required() -> bool {
    true
}

fn default_manual_input_label() -> String {
    "Enter your message".to_string()
}

fn default_manual_prompt() -> String {
    "What can you help me build with ADK-Rust today?".to_string()
}

#[cfg(test)]
mod tests {
    use super::{
        AgentAuthConfig, AuthModeSpec, DeploymentManifest, EnvVarSpec, GraphConfig,
        InteractionConfig, ManualInteractionConfig, RealtimeConfig, ServiceBinding, ServiceKind,
        TriggerInteractionConfig, TriggerKind,
    };

    #[test]
    fn rejects_undeclared_secret_refs_in_env() {
        let mut manifest = DeploymentManifest::default();
        manifest.env.insert(
            "OPENAI_API_KEY".to_string(),
            EnvVarSpec::SecretRef { secret_ref: "missing".to_string() },
        );

        let error = manifest.validate().unwrap_err();
        assert!(error.to_string().contains("undeclared secret"));
    }

    #[test]
    fn rejects_invalid_realtime_feature() {
        let manifest = DeploymentManifest {
            realtime: Some(RealtimeConfig {
                features: vec!["unsupported".to_string()],
                sticky_sessions: true,
                drain_timeout_secs: Some(30),
            }),
            ..Default::default()
        };

        let error = manifest.validate().unwrap_err();
        assert!(error.to_string().contains("unsupported realtime feature"));
    }

    #[test]
    fn requires_graph_checkpoint_binding_for_hitl() {
        let manifest = DeploymentManifest {
            graph: Some(GraphConfig { checkpoint_binding: None, hitl_enabled: true }),
            ..Default::default()
        };

        let error = manifest.validate().unwrap_err();
        assert!(error.to_string().contains("graph.hitl_enabled"));
    }

    #[test]
    fn requires_oidc_fields_when_auth_mode_is_oidc() {
        let manifest = DeploymentManifest {
            auth: Some(AgentAuthConfig {
                mode: AuthModeSpec::Oidc,
                required_scopes: vec!["deploy:read".to_string()],
                issuer: None,
                audience: Some("adk-cli".to_string()),
                jwks_uri: None,
            }),
            ..Default::default()
        };

        let error = manifest.validate().unwrap_err();
        assert!(error.to_string().contains("auth.mode = oidc"));
    }

    #[test]
    fn accepts_supported_graph_checkpoint_binding() {
        let mut manifest = DeploymentManifest::default();
        manifest.services.push(ServiceBinding {
            name: "graph-checkpoint".to_string(),
            kind: ServiceKind::CheckpointPostgres,
            mode: super::BindingMode::Managed,
            connection_url: None,
            secret_ref: None,
        });
        manifest.graph = Some(GraphConfig {
            checkpoint_binding: Some("graph-checkpoint".to_string()),
            hitl_enabled: true,
        });

        manifest.validate().unwrap();
    }

    #[test]
    fn rejects_invalid_webhook_interaction_trigger() {
        let manifest = DeploymentManifest {
            interaction: Some(InteractionConfig {
                manual: Some(ManualInteractionConfig::default()),
                triggers: vec![TriggerInteractionConfig {
                    id: "trigger_1".to_string(),
                    name: "Incoming webhook".to_string(),
                    kind: TriggerKind::Webhook,
                    description: None,
                    path: None,
                    method: Some("POST".to_string()),
                    auth: None,
                    default_prompt: None,
                    cron: None,
                    timezone: None,
                    event_source: None,
                    event_type: None,
                    filter: None,
                }],
            }),
            ..Default::default()
        };

        let error = manifest.validate().unwrap_err();
        assert!(error.to_string().contains("path is required"));
    }
}