zlayer-sdk 0.11.19

ZLayer Plugin Development Kit for 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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
//! `ZLayer` SDK for building WASM plugins in Rust.
//!
//! This crate provides type-safe bindings to `ZLayer` host functions
//! and convenient macros for implementing plugins.
//!
//! # Example
//!
//! ```rust,ignore
//! #![no_std]
//! extern crate alloc;
//!
//! use alloc::string::String;
//! use alloc::vec::Vec;
//! use zlayer_sdk::bindings::{
//!     export_handler,
//!     exports::zlayer::plugin::handler::{
//!         Guest, Capabilities, HandleResult, InitError, PluginInfo, PluginRequest,
//!     },
//!     zlayer::plugin::{
//!         config, logging,
//!         plugin_metadata::Version,
//!         request_types::PluginResponse,
//!     },
//! };
//!
//! struct MyPlugin;
//!
//! impl Guest for MyPlugin {
//!     fn init() -> Result<Capabilities, InitError> {
//!         logging::info("Initializing...");
//!         Ok(Capabilities::CONFIG | Capabilities::LOGGING)
//!     }
//!
//!     fn info() -> PluginInfo {
//!         PluginInfo {
//!             id: String::from("my:plugin"),
//!             name: String::from("My Plugin"),
//!             version: Version { major: 0, minor: 1, patch: 0, pre_release: None },
//!             description: String::from("A custom plugin"),
//!             author: String::from("Author"),
//!             license: None,
//!             homepage: None,
//!             metadata: Vec::new(),
//!         }
//!     }
//!
//!     fn handle(request: PluginRequest) -> HandleResult {
//!         logging::info("Handling request");
//!         HandleResult::Response(PluginResponse {
//!             status: 200,
//!             headers: Vec::new(),
//!             body: b"Hello from ZLayer!".to_vec(),
//!         })
//!     }
//!
//!     fn shutdown() {
//!         logging::info("Shutting down...");
//!     }
//! }
//!
//! // Note: `with_types_in` is required when using the SDK from an external crate
//! export_handler!(MyPlugin with_types_in zlayer_sdk::bindings);
//! ```
//!
//! # Features
//!
//! - **Type-safe bindings** - Generated from WIT definitions
//! - **Host function access** - Config, KV storage, logging, secrets, metrics
//! - **HTTP capabilities** - Make outbound HTTP requests
//! - **`no_std` compatible** - Minimal runtime dependencies
//!
//! # `no_std` Support
//!
//! This crate is `no_std` by default for WASM plugin compilation.
//! Enable the `std` feature for native testing or non-WASM targets.

// Conditional no_std based on feature flag
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

// =============================================================================
// no_std Runtime Support
// =============================================================================

// Use dlmalloc as the global allocator for no_std WASM builds
#[cfg(all(feature = "wasm-alloc", not(feature = "std")))]
#[global_allocator]
static ALLOC: dlmalloc::GlobalDlmalloc = dlmalloc::GlobalDlmalloc;

// Panic handler for no_std WASM targets
// When std is enabled, the standard library provides this
#[cfg(all(not(feature = "std"), target_arch = "wasm32"))]
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    // In WASM, we can use unreachable to trap
    core::arch::wasm32::unreachable()
}

// For non-WASM no_std targets (rare, but handle gracefully)
#[cfg(all(not(feature = "std"), not(target_arch = "wasm32")))]
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {}
}

/// Generated bindings from WIT definitions.
///
/// This module contains all the type-safe bindings generated by `wit-bindgen`
/// from the `ZLayer` WIT interface definitions. It includes:
///
/// - **Imports**: Host-provided interfaces (config, keyvalue, logging, secrets, metrics)
/// - **Exports**: Plugin-exported interfaces (handler, transformer, authenticator, etc.)
/// - **Types**: Common types used across interfaces
///
/// # Usage
///
/// Import the bindings you need:
///
/// ```rust,ignore
/// use zlayer_sdk::bindings::{
///     export_handler,
///     exports::zlayer::plugin::handler::Guest,
///     zlayer::plugin::{config, logging},
/// };
/// ```
pub mod bindings {
    // Allow the generated code to use alloc types
    extern crate alloc;

    wit_bindgen::generate!({
        // Use the minimal world that doesn't require WASI dependencies
        // For full WASI support, use cargo-component which fetches deps automatically
        world: "zlayer-plugin-minimal",
        path: "wit",
        // Export macro for handler registration - made public for SDK users
        export_macro_name: "export_handler",
        pub_export_macro: true,
    });
}

/// Prelude module for convenient imports.
///
/// Import everything you need with a single use statement:
///
/// ```rust,ignore
/// use zlayer_sdk::prelude::*;
/// ```
pub mod prelude {
    // Re-export the main handler trait and types
    pub use crate::bindings::exports::zlayer::plugin::handler::{
        Capabilities, Guest as Handler, HandleResult, InitError, PluginInfo, PluginRequest,
    };
    // These types come from their source interfaces, not the handler export
    pub use crate::bindings::zlayer::plugin::plugin_metadata::Version;
    pub use crate::bindings::zlayer::plugin::request_types::PluginResponse;

    // Re-export common types
    pub use crate::bindings::zlayer::plugin::common::{Error, KeyValue};

    // Re-export host interfaces
    pub use crate::bindings::zlayer::plugin::config;
    pub use crate::bindings::zlayer::plugin::keyvalue;
    pub use crate::bindings::zlayer::plugin::logging;
    pub use crate::bindings::zlayer::plugin::metrics;
    pub use crate::bindings::zlayer::plugin::secrets;

    // Re-export the export macro
    pub use crate::bindings::export_handler;

    // Re-export alloc types for no_std compatibility
    pub use alloc::format;
    pub use alloc::string::String;
    pub use alloc::vec;
    pub use alloc::vec::Vec;
}

/// Testing utilities for `ZLayer` plugins.
///
/// This module provides mock implementations of `ZLayer` host functions
/// for unit testing plugins without running them in the actual runtime.
///
/// Enable with the `testing` feature:
///
/// ```toml
/// [dev-dependencies]
/// zlayer-sdk = { version = "0.1", features = ["testing"] }
/// ```
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::testing::{MockHost, LogLevel};
/// use zlayer_sdk::zlayer_test;
///
/// zlayer_test!(test_my_plugin, |host| {
///     host.set_config("api_key", "test-key")
///         .set_secret("db_password", "secret123");
/// }, |host| {
///     // Test your plugin logic here
///     assert!(host.has_log(LogLevel::Info, "initialized"));
/// });
/// ```
#[cfg(feature = "testing")]
pub mod testing;

/// Helper module for building plugin responses.
///
/// Provides convenience functions for common response patterns.
pub mod response {
    use crate::bindings::zlayer::plugin::request_types::PluginResponse;
    use crate::bindings::zlayer::plugin::common::KeyValue;
    use alloc::string::String;
    use alloc::vec::Vec;

    /// Create a successful JSON response.
    #[must_use]
    pub fn json(body: &[u8]) -> PluginResponse {
        PluginResponse {
            status: 200,
            headers: alloc::vec![KeyValue {
                key: String::from("Content-Type"),
                value: String::from("application/json"),
            }],
            body: body.to_vec(),
        }
    }

    /// Create a successful plain text response.
    #[must_use]
    pub fn text(body: &str) -> PluginResponse {
        PluginResponse {
            status: 200,
            headers: alloc::vec![KeyValue {
                key: String::from("Content-Type"),
                value: String::from("text/plain; charset=utf-8"),
            }],
            body: body.as_bytes().to_vec(),
        }
    }

    /// Create an empty successful response.
    #[must_use]
    pub fn ok() -> PluginResponse {
        PluginResponse {
            status: 200,
            headers: Vec::new(),
            body: Vec::new(),
        }
    }

    /// Create a not found response.
    #[must_use]
    pub fn not_found() -> PluginResponse {
        PluginResponse {
            status: 404,
            headers: alloc::vec![KeyValue {
                key: String::from("Content-Type"),
                value: String::from("text/plain"),
            }],
            body: b"Not Found".to_vec(),
        }
    }

    /// Create a bad request response with a message.
    #[must_use]
    pub fn bad_request(message: &str) -> PluginResponse {
        PluginResponse {
            status: 400,
            headers: alloc::vec![KeyValue {
                key: String::from("Content-Type"),
                value: String::from("text/plain"),
            }],
            body: message.as_bytes().to_vec(),
        }
    }

    /// Create an internal server error response.
    #[must_use]
    pub fn internal_error(message: &str) -> PluginResponse {
        PluginResponse {
            status: 500,
            headers: alloc::vec![KeyValue {
                key: String::from("Content-Type"),
                value: String::from("text/plain"),
            }],
            body: message.as_bytes().to_vec(),
        }
    }

    /// Create a response with custom status, headers, and body.
    #[must_use]
    pub fn custom(status: u16, headers: Vec<KeyValue>, body: Vec<u8>) -> PluginResponse {
        PluginResponse {
            status,
            headers,
            body,
        }
    }
}

/// Helper module for working with plugin metadata.
pub mod metadata {
    use crate::bindings::exports::zlayer::plugin::handler::PluginInfo;
    use crate::bindings::zlayer::plugin::common::KeyValue;
    use crate::bindings::zlayer::plugin::plugin_metadata::Version;
    use alloc::string::String;
    use alloc::vec::Vec;

    /// Builder for creating plugin info.
    pub struct PluginInfoBuilder {
        id: String,
        name: String,
        version: Version,
        description: String,
        author: String,
        license: Option<String>,
        homepage: Option<String>,
        metadata: Vec<KeyValue>,
    }

    impl PluginInfoBuilder {
        /// Create a new builder with required fields.
        #[must_use]
        pub fn new(id: &str, name: &str, author: &str) -> Self {
            Self {
                id: String::from(id),
                name: String::from(name),
                version: Version {
                    major: 0,
                    minor: 1,
                    patch: 0,
                    pre_release: None,
                },
                description: String::new(),
                author: String::from(author),
                license: None,
                homepage: None,
                metadata: Vec::new(),
            }
        }

        /// Set the version.
        #[must_use]
        pub fn version(mut self, major: u32, minor: u32, patch: u32) -> Self {
            self.version = Version {
                major,
                minor,
                patch,
                pre_release: None,
            };
            self
        }

        /// Set the version with pre-release tag.
        #[must_use]
        pub fn version_prerelease(
            mut self,
            major: u32,
            minor: u32,
            patch: u32,
            prerelease: &str,
        ) -> Self {
            self.version = Version {
                major,
                minor,
                patch,
                pre_release: Some(String::from(prerelease)),
            };
            self
        }

        /// Set the description.
        #[must_use]
        pub fn description(mut self, desc: &str) -> Self {
            self.description = String::from(desc);
            self
        }

        /// Set the license.
        #[must_use]
        pub fn license(mut self, license: &str) -> Self {
            self.license = Some(String::from(license));
            self
        }

        /// Set the homepage URL.
        #[must_use]
        pub fn homepage(mut self, url: &str) -> Self {
            self.homepage = Some(String::from(url));
            self
        }

        /// Add a metadata key-value pair.
        #[must_use]
        pub fn meta(mut self, key: &str, value: &str) -> Self {
            self.metadata.push(KeyValue {
                key: String::from(key),
                value: String::from(value),
            });
            self
        }

        /// Build the plugin info.
        #[must_use]
        pub fn build(self) -> PluginInfo {
            PluginInfo {
                id: self.id,
                name: self.name,
                version: self.version,
                description: self.description,
                author: self.author,
                license: self.license,
                homepage: self.homepage,
                metadata: self.metadata,
            }
        }
    }
}

// =============================================================================
// Error Types
// =============================================================================

use alloc::string::String;
use alloc::vec::Vec;

/// Error returned by config operations
#[derive(Debug, Clone)]
pub struct ConfigError {
    /// Error code
    pub code: String,
    /// Error message
    pub message: String,
}

impl ConfigError {
    /// Create a new config error
    #[must_use]
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }

    /// Create a "not found" error
    #[must_use]
    pub fn not_found(key: &str) -> Self {
        Self::new("not_found", alloc::format!("config key '{}' not found", key))
    }
}

impl core::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}

/// Error returned by key-value operations
#[derive(Debug, Clone)]
pub enum KvError {
    /// Key not found
    NotFound,
    /// Value too large
    ValueTooLarge,
    /// Storage quota exceeded
    QuotaExceeded,
    /// Key format invalid
    InvalidKey,
    /// Generic storage error
    Storage(String),
}

impl KvError {
    fn from_wit(err: bindings::zlayer::plugin::keyvalue::KvError) -> Self {
        use bindings::zlayer::plugin::keyvalue::KvError as WitKvError;
        match err {
            WitKvError::NotFound => KvError::NotFound,
            WitKvError::ValueTooLarge => KvError::ValueTooLarge,
            WitKvError::QuotaExceeded => KvError::QuotaExceeded,
            WitKvError::InvalidKey => KvError::InvalidKey,
            WitKvError::Storage(msg) => KvError::Storage(msg),
        }
    }
}

impl core::fmt::Display for KvError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            KvError::NotFound => write!(f, "key not found"),
            KvError::ValueTooLarge => write!(f, "value too large"),
            KvError::QuotaExceeded => write!(f, "storage quota exceeded"),
            KvError::InvalidKey => write!(f, "invalid key format"),
            KvError::Storage(msg) => write!(f, "storage error: {msg}"),
        }
    }
}

/// Error returned by secret operations
#[derive(Debug, Clone)]
pub struct SecretError {
    /// Error code
    pub code: String,
    /// Error message
    pub message: String,
}

impl SecretError {
    /// Create a new secret error
    #[must_use]
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }

    /// Create a "not found" error
    #[must_use]
    pub fn not_found(name: &str) -> Self {
        Self::new("not_found", alloc::format!("secret '{name}' not found"))
    }
}

impl core::fmt::Display for SecretError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}

// =============================================================================
// Config Module - Ergonomic Wrappers
// =============================================================================

/// Configuration access for plugins.
///
/// Provides ergonomic wrappers around the host config interface.
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::config;
///
/// // Get optional config
/// if let Some(value) = config::get("my_key") {
///     log::info(&format!("Got value: {}", value));
/// }
///
/// // Get required config
/// let required = config::get_required("database.host")?;
///
/// // Get typed values
/// let port = config::get_int("database.port").unwrap_or(5432);
/// let enabled = config::get_bool("feature.enabled").unwrap_or(false);
/// ```
pub mod config {
    use super::*;
    use crate::bindings::zlayer::plugin::config as host_config;

    /// Get a configuration value by key.
    ///
    /// Returns `None` if the key doesn't exist.
    #[must_use]
    pub fn get(key: &str) -> Option<String> {
        host_config::get(key)
    }

    /// Get a configuration value, returning an error if not found.
    ///
    /// # Errors
    ///
    /// Returns `ConfigError` if the key is not found.
    pub fn get_required(key: &str) -> Result<String, ConfigError> {
        host_config::get(key).ok_or_else(|| ConfigError::not_found(key))
    }

    /// Get a configuration value as a boolean.
    ///
    /// Recognizes: "true", "false", "1", "0", "yes", "no"
    #[must_use]
    pub fn get_bool(key: &str) -> Option<bool> {
        host_config::get_bool(key)
    }

    /// Get a configuration value as an integer.
    #[must_use]
    pub fn get_int(key: &str) -> Option<i64> {
        host_config::get_int(key)
    }

    /// Get a configuration value as a float.
    #[must_use]
    pub fn get_float(key: &str) -> Option<f64> {
        host_config::get_float(key)
    }

    /// Check if a configuration key exists.
    #[must_use]
    pub fn exists(key: &str) -> bool {
        host_config::exists(key)
    }

    /// Get multiple configuration values at once.
    ///
    /// Returns a list of (key, value) pairs for keys that exist.
    #[must_use]
    pub fn get_many(keys: &[&str]) -> Vec<(String, String)> {
        let keys_vec: Vec<String> = keys.iter().map(|k| String::from(*k)).collect();
        host_config::get_many(&keys_vec)
    }

    /// Get all configuration keys with a given prefix.
    ///
    /// Example: `get_prefix("database.")` returns all `database.*` keys.
    #[must_use]
    pub fn get_prefix(prefix: &str) -> Vec<(String, String)> {
        host_config::get_prefix(prefix)
    }

    /// Get all configuration as a JSON string (for debugging).
    #[must_use]
    pub fn get_all() -> String {
        // Build a simple JSON representation
        let items = host_config::get_prefix("");
        let mut result = String::from("{");
        for (i, (key, value)) in items.iter().enumerate() {
            if i > 0 {
                result.push_str(", ");
            }
            result.push('"');
            result.push_str(key);
            result.push_str("\": \"");
            result.push_str(value);
            result.push('"');
        }
        result.push('}');
        result
    }
}

// =============================================================================
// Key-Value Storage Module
// =============================================================================

/// Key-value storage for plugin state.
///
/// Provides persistent storage that survives across plugin invocations.
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::kv;
///
/// // Store a value
/// kv::set("state", "counter", b"42")?;
///
/// // Retrieve a value
/// if let Some(data) = kv::get("state", "counter")? {
///     let count: i32 = core::str::from_utf8(&data)
///         .ok()
///         .and_then(|s| s.parse().ok())
///         .unwrap_or(0);
/// }
///
/// // String convenience methods
/// kv::set_string("state", "name", "my-value")?;
/// let name = kv::get_string("state", "name")?;
/// ```
pub mod kv {
    use super::*;
    use alloc::string::ToString;
    use crate::bindings::zlayer::plugin::keyvalue as host_kv;

    /// Get a value by key.
    ///
    /// The bucket parameter namespaces keys to avoid collisions.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn get(bucket: &str, key: &str) -> Result<Option<Vec<u8>>, KvError> {
        let full_key = make_key(bucket, key);
        host_kv::get(&full_key).map_err(KvError::from_wit)
    }

    /// Get a value as a UTF-8 string.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn get_string(bucket: &str, key: &str) -> Result<Option<String>, KvError> {
        let full_key = make_key(bucket, key);
        host_kv::get_string(&full_key).map_err(KvError::from_wit)
    }

    /// Set a value.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn set(bucket: &str, key: &str, value: &[u8]) -> Result<(), KvError> {
        let full_key = make_key(bucket, key);
        host_kv::set(&full_key, value).map_err(KvError::from_wit)
    }

    /// Set a string value.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn set_string(bucket: &str, key: &str, value: &str) -> Result<(), KvError> {
        let full_key = make_key(bucket, key);
        host_kv::set_string(&full_key, value).map_err(KvError::from_wit)
    }

    /// Delete a key.
    ///
    /// Returns `Ok(true)` if the key existed, `Ok(false)` otherwise.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn delete(bucket: &str, key: &str) -> Result<bool, KvError> {
        let full_key = make_key(bucket, key);
        host_kv::delete(&full_key).map_err(KvError::from_wit)
    }

    /// List all keys with a given prefix within a bucket.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn keys(bucket: &str, prefix: &str) -> Result<Vec<String>, KvError> {
        let full_prefix = make_key(bucket, prefix);
        let all_keys = host_kv::list_keys(&full_prefix).map_err(KvError::from_wit)?;
        // Strip the bucket prefix from returned keys
        let bucket_prefix = alloc::format!("{bucket}/");
        Ok(all_keys
            .into_iter()
            .map(|k| k.strip_prefix(&bucket_prefix).unwrap_or(&k).to_string())
            .collect())
    }

    /// Check if a key exists.
    #[must_use]
    pub fn exists(bucket: &str, key: &str) -> bool {
        let full_key = make_key(bucket, key);
        host_kv::exists(&full_key)
    }

    /// Set a value with a TTL (time-to-live) in seconds.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn set_with_ttl(
        bucket: &str,
        key: &str,
        value: &[u8],
        ttl_secs: u64,
    ) -> Result<(), KvError> {
        let full_key = make_key(bucket, key);
        let ttl_ns = ttl_secs.saturating_mul(1_000_000_000);
        host_kv::set_with_ttl(&full_key, value, ttl_ns).map_err(KvError::from_wit)
    }

    /// Increment a numeric value atomically.
    ///
    /// Returns the new value after increment.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn increment(bucket: &str, key: &str, delta: i64) -> Result<i64, KvError> {
        let full_key = make_key(bucket, key);
        host_kv::increment(&full_key, delta).map_err(KvError::from_wit)
    }

    /// Compare and swap - set value only if current value matches expected.
    ///
    /// Returns `Ok(true)` if swap succeeded, `Ok(false)` if current value didn't match.
    ///
    /// # Errors
    ///
    /// Returns `KvError` if the operation fails.
    pub fn compare_and_swap(
        bucket: &str,
        key: &str,
        expected: Option<&[u8]>,
        new_value: &[u8],
    ) -> Result<bool, KvError> {
        let full_key = make_key(bucket, key);
        let expected_vec = expected.map(|e| e.to_vec());
        host_kv::compare_and_swap(&full_key, expected_vec.as_deref(), new_value)
            .map_err(KvError::from_wit)
    }

    /// Create a namespaced key from bucket and key.
    fn make_key(bucket: &str, key: &str) -> String {
        alloc::format!("{bucket}/{key}")
    }
}

// =============================================================================
// Logging Module
// =============================================================================

/// Structured logging for plugins.
///
/// All log output is captured by the `ZLayer` host and can be filtered,
/// aggregated, and forwarded to observability systems.
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::log;
///
/// log::info("Plugin started");
/// log::debug("Processing request");
/// log::warn("Rate limit approaching");
/// log::error("Failed to connect to database");
/// ```
pub mod log {
    use crate::bindings::zlayer::plugin::common::KeyValue;
    use crate::bindings::zlayer::plugin::logging as host_log;
    use alloc::string::String;
    use alloc::vec::Vec;

    /// Log level for filtering
    pub use crate::bindings::zlayer::plugin::logging::Level as LogLevel;

    /// Emit a trace-level log message.
    pub fn trace(msg: &str) {
        host_log::trace(msg);
    }

    /// Emit a debug-level log message.
    pub fn debug(msg: &str) {
        host_log::debug(msg);
    }

    /// Emit an info-level log message.
    pub fn info(msg: &str) {
        host_log::info(msg);
    }

    /// Emit a warning-level log message.
    pub fn warn(msg: &str) {
        host_log::warn(msg);
    }

    /// Emit an error-level log message.
    pub fn error(msg: &str) {
        host_log::error(msg);
    }

    /// Emit a log message at the specified level.
    pub fn log(level: LogLevel, msg: &str) {
        host_log::log(level, msg);
    }

    /// Emit a structured log with key-value fields.
    pub fn log_structured(level: LogLevel, msg: &str, fields: &[(String, String)]) {
        let kv_fields: Vec<KeyValue> = fields
            .iter()
            .map(|(k, v)| KeyValue {
                key: k.clone(),
                value: v.clone(),
            })
            .collect();
        host_log::log_structured(level, msg, &kv_fields);
    }

    /// Check if a log level is enabled.
    ///
    /// Use this to avoid expensive log message construction when the level
    /// is filtered out.
    #[must_use]
    pub fn is_enabled(level: LogLevel) -> bool {
        host_log::is_enabled(level)
    }
}

// =============================================================================
// Secrets Module
// =============================================================================

/// Secure secret access for plugins.
///
/// Secrets are configured at deployment time and are read-only to plugins.
/// They are stored securely and never logged.
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::secrets;
///
/// // Get optional secret
/// if let Some(api_key) = secrets::get("API_KEY")? {
///     // Use the API key
/// }
///
/// // Get required secret
/// let db_password = secrets::get_required("DATABASE_PASSWORD")?;
/// ```
pub mod secrets {
    use super::*;
    use crate::bindings::zlayer::plugin::secrets as host_secrets;

    /// Get a secret by name.
    ///
    /// Returns `Ok(None)` if the secret doesn't exist.
    ///
    /// # Errors
    ///
    /// Returns `SecretError` if the operation fails.
    pub fn get(name: &str) -> Result<Option<String>, SecretError> {
        host_secrets::get(name).map_err(|e| SecretError::new(&e.code, &e.message))
    }

    /// Get a required secret, returning an error if not found.
    ///
    /// # Errors
    ///
    /// Returns `SecretError` if the secret is not found.
    pub fn get_required(name: &str) -> Result<String, SecretError> {
        host_secrets::get_required(name).map_err(|e| SecretError::new(&e.code, &e.message))
    }

    /// Check if a secret exists.
    #[must_use]
    pub fn exists(name: &str) -> bool {
        host_secrets::exists(name)
    }

    /// List available secret names (not values).
    ///
    /// Useful for diagnostics without exposing sensitive data.
    #[must_use]
    pub fn list_names() -> Vec<String> {
        host_secrets::list_names()
    }
}

// =============================================================================
// Metrics Module
// =============================================================================

/// Metrics emission for observability.
///
/// Emitted metrics are collected by the `ZLayer` host and can be exported
/// to Prometheus, OpenTelemetry, or other systems.
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::metrics;
///
/// // Increment a counter
/// metrics::counter_inc("requests_total", 1);
///
/// // Set a gauge value
/// metrics::gauge_set("active_connections", 42.0);
///
/// // Record a histogram observation
/// metrics::histogram_observe("request_duration_seconds", 0.125);
/// ```
pub mod metrics {
    use crate::bindings::zlayer::plugin::common::KeyValue;
    use crate::bindings::zlayer::plugin::metrics as host_metrics;
    use alloc::string::String;
    use alloc::vec::Vec;

    /// Increment a counter metric.
    pub fn counter_inc(name: &str, value: u64) {
        host_metrics::counter_inc(name, value);
    }

    /// Increment a counter with labels.
    pub fn counter_inc_labeled(name: &str, value: u64, labels: &[(String, String)]) {
        let kv_labels: Vec<KeyValue> = labels
            .iter()
            .map(|(k, v)| KeyValue {
                key: k.clone(),
                value: v.clone(),
            })
            .collect();
        host_metrics::counter_inc_labeled(name, value, &kv_labels);
    }

    /// Set a gauge metric to a value.
    pub fn gauge_set(name: &str, value: f64) {
        host_metrics::gauge_set(name, value);
    }

    /// Set a gauge with labels.
    pub fn gauge_set_labeled(name: &str, value: f64, labels: &[(String, String)]) {
        let kv_labels: Vec<KeyValue> = labels
            .iter()
            .map(|(k, v)| KeyValue {
                key: k.clone(),
                value: v.clone(),
            })
            .collect();
        host_metrics::gauge_set_labeled(name, value, &kv_labels);
    }

    /// Add to a gauge value (can be negative).
    pub fn gauge_add(name: &str, delta: f64) {
        host_metrics::gauge_add(name, delta);
    }

    /// Record a histogram observation.
    pub fn histogram_observe(name: &str, value: f64) {
        host_metrics::histogram_observe(name, value);
    }

    /// Record a histogram observation with labels.
    pub fn histogram_observe_labeled(name: &str, value: f64, labels: &[(String, String)]) {
        let kv_labels: Vec<KeyValue> = labels
            .iter()
            .map(|(k, v)| KeyValue {
                key: k.clone(),
                value: v.clone(),
            })
            .collect();
        host_metrics::histogram_observe_labeled(name, value, &kv_labels);
    }

    /// Record request duration in nanoseconds.
    pub fn record_duration(name: &str, duration_ns: u64) {
        host_metrics::record_duration(name, duration_ns);
    }

    /// Record request duration with labels.
    pub fn record_duration_labeled(name: &str, duration_ns: u64, labels: &[(String, String)]) {
        let kv_labels: Vec<KeyValue> = labels
            .iter()
            .map(|(k, v)| KeyValue {
                key: k.clone(),
                value: v.clone(),
            })
            .collect();
        host_metrics::record_duration_labeled(name, duration_ns, &kv_labels);
    }
}

// =============================================================================
// Plugin Trait
// =============================================================================

/// Trait for implementing `ZLayer` plugins.
///
/// This trait provides the core interface that all plugins must implement.
/// The `zlayer_plugin!` macro generates the necessary WIT bindings glue code.
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::prelude::*;
/// use zlayer_sdk::{ZLayerPlugin, zlayer_plugin};
///
/// struct MyPlugin;
///
/// impl Default for MyPlugin {
///     fn default() -> Self {
///         Self
///     }
/// }
///
/// impl ZLayerPlugin for MyPlugin {
///     fn info(&self) -> PluginInfo {
///         PluginInfo {
///             id: "my-org:my-plugin".into(),
///             name: "My Plugin".into(),
///             version: Version { major: 1, minor: 0, patch: 0, pre_release: None },
///             description: "A simple plugin".into(),
///             author: "My Organization".into(),
///             license: Some("MIT".into()),
///             homepage: None,
///             metadata: vec![],
///         }
///     }
///
///     fn handle(&self, event_type: &str, payload: &[u8]) -> Result<Vec<u8>, String> {
///         Ok(payload.to_vec())
///     }
/// }
///
/// zlayer_plugin!(MyPlugin);
/// ```
pub trait ZLayerPlugin: Default {
    /// Initialize the plugin.
    ///
    /// Called once when the plugin is loaded. Override to perform
    /// initialization tasks like reading configuration or connecting
    /// to services.
    ///
    /// Return `Ok(())` on success or `Err(message)` to abort loading.
    ///
    /// # Errors
    ///
    /// Returns an error message string if initialization fails.
    fn init(&self) -> Result<(), String> {
        Ok(())
    }

    /// Return plugin metadata.
    ///
    /// This information is used for logging, metrics, and management.
    fn info(&self) -> bindings::exports::zlayer::plugin::handler::PluginInfo;

    /// Handle an incoming event or request.
    ///
    /// # Arguments
    ///
    /// * `event_type` - The type of event (e.g., "GET", "POST", "message", "timer")
    /// * `payload` - The event payload as bytes
    ///
    /// # Returns
    ///
    /// * `Ok(response)` - The response payload as bytes
    /// * `Err(message)` - An error message if handling failed
    ///
    /// # Errors
    ///
    /// Returns an error message string if handling fails.
    fn handle(&self, event_type: &str, payload: &[u8]) -> Result<Vec<u8>, String>;

    /// Graceful shutdown hook.
    ///
    /// Called when the plugin is being unloaded. Override to clean up
    /// resources like database connections or file handles.
    ///
    /// # Errors
    ///
    /// Returns an error message string if shutdown fails.
    fn shutdown(&self) -> Result<(), String> {
        Ok(())
    }

    /// Return the capabilities this plugin requires.
    ///
    /// Override to request additional capabilities like HTTP client access.
    fn capabilities(&self) -> bindings::exports::zlayer::plugin::handler::Capabilities {
        use bindings::exports::zlayer::plugin::handler::Capabilities;
        Capabilities::CONFIG | Capabilities::LOGGING
    }
}

// =============================================================================
// Plugin Registration Macro
// =============================================================================

/// Register a plugin implementation with the `ZLayer` runtime.
///
/// This macro generates the necessary WIT binding exports for your plugin type.
/// Your type must implement the `ZLayerPlugin` trait and `Default`.
///
/// # Example
///
/// ```rust,ignore
/// use zlayer_sdk::prelude::*;
/// use zlayer_sdk::{ZLayerPlugin, zlayer_plugin};
///
/// struct MyPlugin;
/// impl Default for MyPlugin {
///     fn default() -> Self { Self }
/// }
///
/// impl ZLayerPlugin for MyPlugin {
///     fn info(&self) -> PluginInfo {
///         PluginInfo {
///             id: "example:my-plugin".into(),
///             name: "My Plugin".into(),
///             version: Version { major: 1, minor: 0, patch: 0, pre_release: None },
///             description: "Example plugin".into(),
///             author: "Example".into(),
///             license: None,
///             homepage: None,
///             metadata: vec![],
///         }
///     }
///
///     fn handle(&self, event_type: &str, payload: &[u8]) -> Result<Vec<u8>, String> {
///         Ok(payload.to_vec())
///     }
/// }
///
/// zlayer_plugin!(MyPlugin);
/// ```
#[macro_export]
macro_rules! zlayer_plugin {
    ($plugin_type:ty) => {
        struct ZLayerPluginExport;

        impl $crate::bindings::exports::zlayer::plugin::handler::Guest for ZLayerPluginExport {
            fn init() -> Result<
                $crate::bindings::exports::zlayer::plugin::handler::Capabilities,
                $crate::bindings::exports::zlayer::plugin::handler::InitError,
            > {
                let plugin = <$plugin_type as Default>::default();
                match <$plugin_type as $crate::ZLayerPlugin>::init(&plugin) {
                    Ok(()) => Ok(<$plugin_type as $crate::ZLayerPlugin>::capabilities(&plugin)),
                    Err(msg) => Err(
                        $crate::bindings::exports::zlayer::plugin::handler::InitError::Failed(msg),
                    ),
                }
            }

            fn info() -> $crate::bindings::exports::zlayer::plugin::handler::PluginInfo {
                let plugin = <$plugin_type as Default>::default();
                <$plugin_type as $crate::ZLayerPlugin>::info(&plugin)
            }

            fn handle(
                request: $crate::bindings::exports::zlayer::plugin::handler::PluginRequest,
            ) -> $crate::bindings::exports::zlayer::plugin::handler::HandleResult {
                use $crate::bindings::exports::zlayer::plugin::handler::{HandleResult, HttpMethod};
                use $crate::bindings::zlayer::plugin::request_types::PluginResponse;

                let plugin = <$plugin_type as Default>::default();

                let event_type = match request.method {
                    HttpMethod::Get => "GET",
                    HttpMethod::Post => "POST",
                    HttpMethod::Put => "PUT",
                    HttpMethod::Delete => "DELETE",
                    HttpMethod::Patch => "PATCH",
                    HttpMethod::Head => "HEAD",
                    HttpMethod::Options => "OPTIONS",
                    HttpMethod::Connect => "CONNECT",
                    HttpMethod::Trace => "TRACE",
                };

                match <$plugin_type as $crate::ZLayerPlugin>::handle(
                    &plugin,
                    event_type,
                    &request.body,
                ) {
                    Ok(body) => HandleResult::Response(PluginResponse {
                        status: 200,
                        headers: ::alloc::vec::Vec::new(),
                        body,
                    }),
                    Err(msg) => HandleResult::Error(msg),
                }
            }

            fn shutdown() {
                let plugin = <$plugin_type as Default>::default();
                let _ = <$plugin_type as $crate::ZLayerPlugin>::shutdown(&plugin);
            }
        }

        $crate::bindings::export_handler!(ZLayerPluginExport);
    };
}

// =============================================================================
// Additional Helper Functions
// =============================================================================

/// Create a `KeyValue` pair.
#[must_use]
pub fn kv_pair(key: impl Into<String>, value: impl Into<String>) -> bindings::zlayer::plugin::common::KeyValue {
    bindings::zlayer::plugin::common::KeyValue {
        key: key.into(),
        value: value.into(),
    }
}

/// Create a Version struct.
#[must_use]
pub fn version(major: u32, minor: u32, patch: u32) -> bindings::zlayer::plugin::plugin_metadata::Version {
    bindings::zlayer::plugin::plugin_metadata::Version {
        major,
        minor,
        patch,
        pre_release: None,
    }
}

/// Create a Version struct with pre-release tag.
#[must_use]
pub fn version_pre(
    major: u32,
    minor: u32,
    patch: u32,
    pre_release: &str,
) -> bindings::zlayer::plugin::plugin_metadata::Version {
    bindings::zlayer::plugin::plugin_metadata::Version {
        major,
        minor,
        patch,
        pre_release: Some(String::from(pre_release)),
    }
}