neomind-extension-sdk 0.6.3

Unified SDK for developing NeoMind Edge AI Platform extensions with ABI Version 3
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
//! Extension types and helpers for SDK
//!
//! This module provides types that work for both Native and WASM targets.
//! The core IPC boundary types are defined in `ipc_types.rs` for stability.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// Re-export all IPC boundary types for convenience
pub use crate::ipc_types::*;

// ============================================================================
// SDK-Specific Extensions (not in IPC boundary)
// ============================================================================

/// Extension metadata for SDK (SDK-specific fields)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SdkExtensionMetadata {
    /// Unique extension identifier
    pub id: String,
    /// Display name
    pub name: String,
    /// Version string
    pub version: String,
    /// Optional description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Optional author
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// SDK version used to build this extension
    #[serde(default)]
    pub sdk_version: Option<String>,
    /// Extension type
    #[serde(default = "default_extension_type")]
    pub extension_type: String,
}

fn default_extension_type() -> String {
    "native".to_string()
}

impl SdkExtensionMetadata {
    /// Create new metadata
    pub fn new(id: impl Into<String>, name: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            version: version.into(),
            description: None,
            author: None,
            sdk_version: Some(env!("CARGO_PKG_VERSION").to_string()),
            extension_type: "native".to_string(),
        }
    }

    /// Add description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add author
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.author = Some(author.into());
        self
    }

    /// Set extension type
    pub fn with_type(mut self, extension_type: impl Into<String>) -> Self {
        self.extension_type = extension_type.into();
        self
    }
}

// ============================================================================
// Metric Types (SDK-specific wrappers)
// ============================================================================

/// Metric data types (SDK-specific)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum SdkMetricDataType {
    Float,
    Integer,
    Boolean,
    #[default]
    String,
    Binary,
    /// Enum type with a list of allowed options
    Enum {
        options: Vec<String>,
    },
}

impl From<SdkMetricDataType> for MetricDataType {
    fn from(dt: SdkMetricDataType) -> Self {
        match dt {
            SdkMetricDataType::Float => MetricDataType::Float,
            SdkMetricDataType::Integer => MetricDataType::Integer,
            SdkMetricDataType::Boolean => MetricDataType::Boolean,
            SdkMetricDataType::String => MetricDataType::String,
            SdkMetricDataType::Binary => MetricDataType::Binary,
            SdkMetricDataType::Enum { options } => MetricDataType::Enum { options },
        }
    }
}

impl From<MetricDataType> for SdkMetricDataType {
    fn from(dt: MetricDataType) -> Self {
        match dt {
            MetricDataType::Float => SdkMetricDataType::Float,
            MetricDataType::Integer => SdkMetricDataType::Integer,
            MetricDataType::Boolean => SdkMetricDataType::Boolean,
            MetricDataType::String => SdkMetricDataType::String,
            MetricDataType::Binary => SdkMetricDataType::Binary,
            MetricDataType::Enum { options } => SdkMetricDataType::Enum { options },
        }
    }
}

/// Metric definition (SDK-specific)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SdkMetricDefinition {
    /// Metric name
    pub name: String,
    /// Display name
    pub display_name: String,
    /// Data type
    pub data_type: SdkMetricDataType,
    /// Unit of measurement
    #[serde(default)]
    pub unit: String,
    /// Minimum value (for numeric types)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<f64>,
    /// Maximum value (for numeric types)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<f64>,
    /// Is this metric required
    #[serde(default)]
    pub required: bool,
}

impl SdkMetricDefinition {
    /// Create a new metric definition
    pub fn new(
        name: impl Into<String>,
        display_name: impl Into<String>,
        data_type: SdkMetricDataType,
    ) -> Self {
        Self {
            name: name.into(),
            display_name: display_name.into(),
            data_type,
            unit: String::new(),
            min: None,
            max: None,
            required: false,
        }
    }

    /// Add unit
    pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
        self.unit = unit.into();
        self
    }

    /// Add min value
    pub fn with_min(mut self, min: f64) -> Self {
        self.min = Some(min);
        self
    }

    /// Add max value
    pub fn with_max(mut self, max: f64) -> Self {
        self.max = Some(max);
        self
    }

    /// Set as required
    pub fn with_required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }
}

impl From<SdkMetricDefinition> for MetricDescriptor {
    fn from(def: SdkMetricDefinition) -> Self {
        Self {
            name: def.name,
            display_name: def.display_name,
            data_type: def.data_type.into(),
            unit: def.unit,
            min: def.min,
            max: def.max,
            required: def.required,
        }
    }
}

/// Metric value (SDK-specific)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[derive(Default)]
pub enum SdkMetricValue {
    Float(f64),
    Integer(i64),
    Boolean(bool),
    String(String),
    Binary(Vec<u8>),
    #[default]
    Null,
}

impl From<SdkMetricValue> for MetricValue {
    fn from(v: SdkMetricValue) -> Self {
        match v {
            SdkMetricValue::Float(f) => MetricValue::Float(f),
            SdkMetricValue::Integer(i) => MetricValue::Integer(i),
            SdkMetricValue::Boolean(b) => MetricValue::Boolean(b),
            SdkMetricValue::String(s) => MetricValue::String(s),
            SdkMetricValue::Binary(b) => MetricValue::Binary(b),
            SdkMetricValue::Null => MetricValue::Null,
        }
    }
}

impl From<MetricValue> for SdkMetricValue {
    fn from(v: MetricValue) -> Self {
        match v {
            MetricValue::Float(f) => SdkMetricValue::Float(f),
            MetricValue::Integer(i) => SdkMetricValue::Integer(i),
            MetricValue::Boolean(b) => SdkMetricValue::Boolean(b),
            MetricValue::String(s) => SdkMetricValue::String(s),
            MetricValue::Binary(b) => SdkMetricValue::Binary(b),
            MetricValue::Null => SdkMetricValue::Null,
        }
    }
}

impl From<f64> for SdkMetricValue {
    fn from(v: f64) -> Self {
        Self::Float(v)
    }
}

impl From<i64> for SdkMetricValue {
    fn from(v: i64) -> Self {
        Self::Integer(v)
    }
}

impl From<bool> for SdkMetricValue {
    fn from(v: bool) -> Self {
        Self::Boolean(v)
    }
}

impl From<String> for SdkMetricValue {
    fn from(v: String) -> Self {
        Self::String(v)
    }
}

impl From<&str> for SdkMetricValue {
    fn from(v: &str) -> Self {
        Self::String(v.to_string())
    }
}

impl From<Vec<u8>> for SdkMetricValue {
    fn from(v: Vec<u8>) -> Self {
        Self::Binary(v)
    }
}

// ============================================================================
// Extension Metric Value (SDK-specific)
// ============================================================================

/// Extension metric value with name, value and timestamp (SDK-specific)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SdkExtensionMetricValue {
    /// Metric name
    pub name: String,
    /// Metric value
    pub value: SdkMetricValue,
    /// Timestamp in milliseconds
    pub timestamp: i64,
}

impl SdkExtensionMetricValue {
    /// Create a new extension metric value
    pub fn new(name: impl Into<String>, value: SdkMetricValue) -> Self {
        Self {
            name: name.into(),
            value,
            timestamp: {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    crate::ipc_types::current_timestamp_ms()
                }
                #[cfg(target_arch = "wasm32")]
                {
                    // Request timestamp from host via capability invocation
                    crate::wasm::bindings::invoke_capability_raw(
                        "system_timestamp",
                        &serde_json::json!({}),
                    )
                    .ok()
                    .and_then(|v| v.get("timestamp_ms").and_then(|t| t.as_i64()))
                    .unwrap_or(0)
                }
            },
        }
    }

    /// Create with explicit timestamp
    pub fn with_timestamp(name: impl Into<String>, value: SdkMetricValue, timestamp: i64) -> Self {
        Self {
            name: name.into(),
            value,
            timestamp,
        }
    }
}

impl From<SdkExtensionMetricValue> for ExtensionMetricValue {
    fn from(v: SdkExtensionMetricValue) -> Self {
        Self {
            name: v.name,
            value: v.value.into(),
            timestamp: v.timestamp,
        }
    }
}

// ============================================================================
// Command Types (SDK-specific)
// ============================================================================

/// Parameter definition for commands (SDK-specific)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SdkParameterDefinition {
    /// Parameter name
    pub name: String,
    /// Display name
    #[serde(default)]
    pub display_name: String,
    /// Description
    #[serde(default)]
    pub description: String,
    /// Parameter data type
    #[serde(default)]
    pub param_type: SdkMetricDataType,
    /// Is this parameter required
    #[serde(default)]
    pub required: bool,
    /// Default value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_value: Option<SdkMetricValue>,
    /// Minimum value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<f64>,
    /// Maximum value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<f64>,
    /// Options for enum types
    #[serde(default)]
    pub options: Vec<String>,
}

impl SdkParameterDefinition {
    /// Create a new parameter definition
    pub fn new(name: impl Into<String>, param_type: SdkMetricDataType) -> Self {
        Self {
            name: name.into(),
            display_name: String::new(),
            description: String::new(),
            param_type,
            required: true,
            default_value: None,
            min: None,
            max: None,
            options: Vec::new(),
        }
    }

    /// Add display name
    pub fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = display_name.into();
        self
    }

    /// Add description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Set as optional
    pub fn optional(mut self) -> Self {
        self.required = false;
        self
    }

    /// Add default value
    pub fn with_default(mut self, default: SdkMetricValue) -> Self {
        self.default_value = Some(default);
        self.required = false;
        self
    }
}

impl From<SdkParameterDefinition> for ParameterDefinition {
    fn from(p: SdkParameterDefinition) -> Self {
        Self {
            name: p.name,
            display_name: p.display_name,
            description: p.description,
            param_type: p.param_type.into(),
            required: p.required,
            default_value: p.default_value.map(|v| v.into()),
            min: p.min,
            max: p.max,
            options: p.options,
        }
    }
}

/// Command definition (SDK-specific)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SdkCommandDefinition {
    /// Command name
    pub name: String,
    /// Display name
    #[serde(default)]
    pub display_name: String,
    /// Payload template
    #[serde(default)]
    pub payload_template: String,
    /// Description
    #[serde(default)]
    pub description: String,
    /// Parameters
    #[serde(default)]
    pub parameters: Vec<SdkParameterDefinition>,
    /// Fixed values
    #[serde(default)]
    pub fixed_values: std::collections::HashMap<String, serde_json::Value>,
    /// Sample payloads
    #[serde(default)]
    pub samples: Vec<serde_json::Value>,
    /// Parameter groups
    #[serde(default)]
    pub parameter_groups: Vec<SdkParameterGroup>,
}

/// Parameter group for organizing command parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SdkParameterGroup {
    /// Group name
    pub name: String,
    /// Display name
    #[serde(default)]
    pub display_name: String,
    /// Description
    #[serde(default)]
    pub description: String,
    /// Parameters in this group
    #[serde(default)]
    pub parameters: Vec<String>,
}

impl SdkCommandDefinition {
    /// Create a new command definition
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            display_name: String::new(),
            payload_template: String::new(),
            description: String::new(),
            parameters: Vec::new(),
            fixed_values: std::collections::HashMap::new(),
            samples: Vec::new(),
            parameter_groups: Vec::new(),
        }
    }

    /// Add description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Add a parameter
    pub fn param(mut self, param: SdkParameterDefinition) -> Self {
        self.parameters.push(param);
        self
    }
}

impl From<SdkCommandDefinition> for CommandDescriptor {
    fn from(c: SdkCommandDefinition) -> Self {
        Self {
            name: c.name,
            display_name: c.display_name,
            description: c.description,
            payload_template: c.payload_template,
            parameters: c.parameters.into_iter().map(|p| p.into()).collect(),
            fixed_values: c.fixed_values,
            samples: c.samples,
            parameter_groups: c
                .parameter_groups
                .into_iter()
                .map(|g| ParameterGroup {
                    name: g.name,
                    display_name: g.display_name,
                    description: g.description,
                    parameters: g.parameters,
                })
                .collect(),
        }
    }
}

// ============================================================================
// Error Types (SDK-specific)
// ============================================================================

/// Extension error type (SDK-specific)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SdkExtensionError {
    /// Command not found
    CommandNotFound(String),
    /// Invalid arguments
    InvalidArguments(String),
    /// Execution failed
    ExecutionFailed(String),
    /// Timeout
    Timeout(String),
    /// Not found
    NotFound(String),
    /// Invalid format
    InvalidFormat(String),
    /// Load failed
    LoadFailed(String),
    /// Security error
    SecurityError(String),
    /// Not supported
    NotSupported(String),
    /// Configuration error
    ConfigurationError(String),
    /// Internal error
    InternalError(String),
    /// Other error
    Other(String),
}

impl std::fmt::Display for SdkExtensionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CommandNotFound(cmd) => write!(f, "Command not found: {}", cmd),
            Self::InvalidArguments(msg) => write!(f, "Invalid arguments: {}", msg),
            Self::ExecutionFailed(msg) => write!(f, "Execution failed: {}", msg),
            Self::Timeout(msg) => write!(f, "Timeout: {}", msg),
            Self::NotFound(msg) => write!(f, "Not found: {}", msg),
            Self::InvalidFormat(msg) => write!(f, "Invalid format: {}", msg),
            Self::LoadFailed(msg) => write!(f, "Load failed: {}", msg),
            Self::SecurityError(msg) => write!(f, "Security error: {}", msg),
            Self::NotSupported(msg) => write!(f, "Not supported: {}", msg),
            Self::ConfigurationError(msg) => write!(f, "Configuration error: {}", msg),
            Self::InternalError(msg) => write!(f, "Internal error: {}", msg),
            Self::Other(msg) => write!(f, "Error: {}", msg),
        }
    }
}

impl std::error::Error for SdkExtensionError {}

impl From<serde_json::Error> for SdkExtensionError {
    fn from(e: serde_json::Error) -> Self {
        Self::InvalidFormat(e.to_string())
    }
}

impl From<SdkExtensionError> for ExtensionError {
    fn from(e: SdkExtensionError) -> Self {
        match e {
            SdkExtensionError::CommandNotFound(s) => ExtensionError::CommandNotFound(s),
            SdkExtensionError::InvalidArguments(s) => ExtensionError::InvalidArguments(s),
            SdkExtensionError::ExecutionFailed(s) => ExtensionError::ExecutionFailed(s),
            SdkExtensionError::Timeout(s) => ExtensionError::Timeout(s),
            SdkExtensionError::NotFound(s) => ExtensionError::NotFound(s),
            SdkExtensionError::InvalidFormat(s) => ExtensionError::InvalidFormat(s),
            SdkExtensionError::LoadFailed(s) => ExtensionError::LoadFailed(s),
            SdkExtensionError::SecurityError(s) => ExtensionError::SecurityError(s),
            SdkExtensionError::NotSupported(s) => ExtensionError::NotSupported(s),
            SdkExtensionError::ConfigurationError(s) => ExtensionError::ConfigurationError(s),
            SdkExtensionError::InternalError(s) => ExtensionError::InternalError(s),
            SdkExtensionError::Other(s) => ExtensionError::Other(s),
        }
    }
}

/// Result type for SDK extension operations
pub type SdkResult<T> = std::result::Result<T, SdkExtensionError>;

// ============================================================================
// Frontend Component Types
// ============================================================================

/// Frontend component manifest for extensions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrontendManifest {
    /// Extension ID this frontend belongs to
    pub id: String,
    /// Frontend version
    pub version: String,
    /// Path to main JavaScript file
    #[serde(default = "default_entrypoint")]
    pub entrypoint: String,
    /// Path to main CSS file (optional)
    pub style_entrypoint: Option<String>,
    /// List of components provided
    pub components: Vec<FrontendComponent>,
    /// i18n configuration
    pub i18n: Option<I18nConfig>,
    /// Frontend dependencies
    #[serde(default)]
    pub dependencies: HashMap<String, String>,
}

fn default_entrypoint() -> String {
    "index.js".to_string()
}

/// Frontend component definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrontendComponent {
    /// Component identifier
    pub name: String,
    /// Component type
    #[serde(rename = "type")]
    pub component_type: FrontendComponentType,
    /// Human-readable name
    pub display_name: String,
    /// Component description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Icon name or SVG path
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    /// Default size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_size: Option<ComponentSize>,
    /// Minimum size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_size: Option<ComponentSize>,
    /// Maximum size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_size: Option<ComponentSize>,
    /// Configuration schema (JSON Schema)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config_schema: Option<serde_json::Value>,
    /// Supports manual refresh
    #[serde(default = "default_true")]
    pub refreshable: bool,
    /// Default refresh interval in milliseconds (0 = no auto-refresh)
    #[serde(default)]
    pub refresh_interval: u64,
}

fn default_true() -> bool {
    true
}

/// Component type enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FrontendComponentType {
    /// Dashboard card component
    Card,
    /// Widget component
    Widget,
    /// Panel component
    Panel,
    /// Dialog component
    Dialog,
    /// Settings component
    Settings,
}

/// Component size definition
#[derive(Debug, Clone, Serialize, Deserialize, Copy)]
pub struct ComponentSize {
    /// Width in pixels
    pub width: u32,
    /// Height in pixels
    pub height: u32,
}

impl ComponentSize {
    /// Create a new size
    pub fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }
}

/// i18n configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct I18nConfig {
    /// Default language
    #[serde(default = "default_language")]
    pub default_language: String,
    /// Supported languages
    pub supported_languages: Vec<String>,
    /// Path to i18n resource files
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources_path: Option<String>,
}

fn default_language() -> String {
    "en".to_string()
}

// ============================================================================
// Frontend Manifest Builder
// ============================================================================

/// Builder for creating frontend manifests
pub struct FrontendManifestBuilder {
    manifest: FrontendManifest,
}

impl FrontendManifestBuilder {
    /// Create a new builder
    pub fn new(id: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            manifest: FrontendManifest {
                id: id.into(),
                version: version.into(),
                entrypoint: default_entrypoint(),
                style_entrypoint: None,
                components: Vec::new(),
                i18n: None,
                dependencies: HashMap::new(),
            },
        }
    }

    /// Set the entrypoint
    pub fn entrypoint(mut self, path: impl Into<String>) -> Self {
        self.manifest.entrypoint = path.into();
        self
    }

    /// Set the style entrypoint
    pub fn style_entrypoint(mut self, path: impl Into<String>) -> Self {
        self.manifest.style_entrypoint = Some(path.into());
        self
    }

    /// Add a component
    pub fn component(mut self, component: FrontendComponent) -> Self {
        self.manifest.components.push(component);
        self
    }

    /// Add a card component
    pub fn card(mut self, name: impl Into<String>, display_name: impl Into<String>) -> Self {
        self.manifest.components.push(FrontendComponent {
            name: name.into(),
            component_type: FrontendComponentType::Card,
            display_name: display_name.into(),
            description: None,
            icon: None,
            default_size: None,
            min_size: None,
            max_size: None,
            config_schema: None,
            refreshable: true,
            refresh_interval: 0,
        });
        self
    }

    /// Add a widget component
    pub fn widget(mut self, name: impl Into<String>, display_name: impl Into<String>) -> Self {
        self.manifest.components.push(FrontendComponent {
            name: name.into(),
            component_type: FrontendComponentType::Widget,
            display_name: display_name.into(),
            description: None,
            icon: None,
            default_size: None,
            min_size: None,
            max_size: None,
            config_schema: None,
            refreshable: true,
            refresh_interval: 0,
        });
        self
    }

    /// Add a panel component
    pub fn panel(mut self, name: impl Into<String>, display_name: impl Into<String>) -> Self {
        self.manifest.components.push(FrontendComponent {
            name: name.into(),
            component_type: FrontendComponentType::Panel,
            display_name: display_name.into(),
            description: None,
            icon: None,
            default_size: None,
            min_size: None,
            max_size: None,
            config_schema: None,
            refreshable: true,
            refresh_interval: 0,
        });
        self
    }

    /// Set i18n configuration
    pub fn i18n(mut self, config: I18nConfig) -> Self {
        self.manifest.i18n = Some(config);
        self
    }

    /// Add a dependency
    pub fn dependency(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
        self.manifest
            .dependencies
            .insert(name.into(), version.into());
        self
    }

    /// Build the manifest
    pub fn build(self) -> FrontendManifest {
        self.manifest
    }
}

// ============================================================================
// Argument Parsing Helpers
// ============================================================================

/// Helper for parsing command arguments
pub struct ArgParser<'a> {
    args: &'a serde_json::Value,
}

impl<'a> ArgParser<'a> {
    /// Create a new argument parser
    pub fn new(args: &'a serde_json::Value) -> Self {
        Self { args }
    }

    /// Get a string argument
    pub fn get_string(&self, name: &str) -> SdkResult<String> {
        self.args
            .get(name)
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .ok_or_else(|| {
                SdkExtensionError::InvalidArguments(format!(
                    "Missing or invalid string argument: {}",
                    name
                ))
            })
    }

    /// Get an optional string argument
    pub fn get_optional_string(&self, name: &str) -> Option<String> {
        self.args
            .get(name)
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    /// Get an i64 argument
    pub fn get_i64(&self, name: &str) -> SdkResult<i64> {
        self.args.get(name).and_then(|v| v.as_i64()).ok_or_else(|| {
            SdkExtensionError::InvalidArguments(format!(
                "Missing or invalid integer argument: {}",
                name
            ))
        })
    }

    /// Get an optional i64 argument
    pub fn get_optional_i64(&self, name: &str) -> Option<i64> {
        self.args.get(name).and_then(|v| v.as_i64())
    }

    /// Get a f64 argument
    pub fn get_f64(&self, name: &str) -> SdkResult<f64> {
        self.args.get(name).and_then(|v| v.as_f64()).ok_or_else(|| {
            SdkExtensionError::InvalidArguments(format!(
                "Missing or invalid float argument: {}",
                name
            ))
        })
    }

    /// Get an optional f64 argument
    pub fn get_optional_f64(&self, name: &str) -> Option<f64> {
        self.args.get(name).and_then(|v| v.as_f64())
    }

    /// Get a bool argument
    pub fn get_bool(&self, name: &str) -> SdkResult<bool> {
        self.args
            .get(name)
            .and_then(|v| v.as_bool())
            .ok_or_else(|| {
                SdkExtensionError::InvalidArguments(format!(
                    "Missing or invalid boolean argument: {}",
                    name
                ))
            })
    }

    /// Get an optional bool argument
    pub fn get_optional_bool(&self, name: &str) -> Option<bool> {
        self.args.get(name).and_then(|v| v.as_bool())
    }

    /// Get a JSON object argument
    pub fn get_object(&self, name: &str) -> SdkResult<&serde_json::Map<String, serde_json::Value>> {
        self.args
            .get(name)
            .and_then(|v| v.as_object())
            .ok_or_else(|| {
                SdkExtensionError::InvalidArguments(format!(
                    "Missing or invalid object argument: {}",
                    name
                ))
            })
    }

    /// Get a JSON array argument
    pub fn get_array(&self, name: &str) -> SdkResult<&Vec<serde_json::Value>> {
        self.args
            .get(name)
            .and_then(|v| v.as_array())
            .ok_or_else(|| {
                SdkExtensionError::InvalidArguments(format!(
                    "Missing or invalid array argument: {}",
                    name
                ))
            })
    }

    /// Parse the entire args as a specific type
    pub fn parse<T: for<'de> Deserialize<'de>>(&self) -> SdkResult<T> {
        serde_json::from_value(self.args.clone()).map_err(Into::into)
    }
}

// ============================================================================
// Extension Statistics (for WASM target)
// ============================================================================

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

    #[test]
    fn test_metric_data_type_serialization() {
        let types = vec![
            (SdkMetricDataType::Float, r#""float""#),
            (SdkMetricDataType::Integer, r#""integer""#),
            (SdkMetricDataType::Boolean, r#""boolean""#),
            (SdkMetricDataType::String, r#""string""#),
            (SdkMetricDataType::Binary, r#""binary""#),
        ];

        for (dtype, expected) in types {
            let json = serde_json::to_string(&dtype).unwrap();
            assert_eq!(json, expected);

            let deserialized: SdkMetricDataType = serde_json::from_str(expected).unwrap();
            assert_eq!(dtype, deserialized);
        }

        // Test Enum type
        let enum_type = SdkMetricDataType::Enum {
            options: vec!["option1".to_string(), "option2".to_string()],
        };
        let json = serde_json::to_string(&enum_type).unwrap();
        assert!(json.contains("enum"));
        assert!(json.contains("options"));
    }

    #[test]
    fn test_metric_definition_serialization() {
        let metric = SdkMetricDefinition {
            name: "test_metric".to_string(),
            display_name: "Test Metric".to_string(),
            data_type: SdkMetricDataType::Float,
            unit: "°C".to_string(),
            min: Some(0.0),
            max: Some(100.0),
            required: true,
        };

        let json = serde_json::to_string(&metric).unwrap();
        assert!(json.contains("test_metric"));
        assert!(json.contains("float"));

        let deserialized: SdkMetricDefinition = serde_json::from_str(&json).unwrap();
        assert_eq!(metric.name, deserialized.name);
        assert_eq!(metric.unit, deserialized.unit);
    }

    #[test]
    fn test_extension_metadata_serialization() {
        let meta = SdkExtensionMetadata {
            id: "test-ext".to_string(),
            name: "Test Extension".to_string(),
            version: "1.0.0".to_string(),
            description: Some("A test extension".to_string()),
            author: Some("Test Author".to_string()),
            sdk_version: Some("0.5.11".to_string()),
            extension_type: "native".to_string(),
        };

        let json = serde_json::to_string(&meta).unwrap();
        assert!(json.contains("test-ext"));
        assert!(json.contains("1.0.0"));

        let deserialized: SdkExtensionMetadata = serde_json::from_str(&json).unwrap();
        assert_eq!(meta.id, deserialized.id);
        assert_eq!(meta.version, deserialized.version);
    }

    #[test]
    fn test_extension_error_serialization() {
        let error = SdkExtensionError::InvalidArguments("test error".to_string());
        let json = serde_json::to_string(&error).unwrap();
        assert!(json.contains("InvalidArguments"));

        // Test error display
        assert!(error.to_string().contains("test error"));
    }

    #[test]
    fn test_type_conversions() {
        // SdkMetricDataType <-> MetricDataType
        let sdk_dt = SdkMetricDataType::Float;
        let dt: MetricDataType = sdk_dt.clone().into();
        assert!(matches!(dt, MetricDataType::Float));
        let back: SdkMetricDataType = dt.into();
        assert!(matches!(back, SdkMetricDataType::Float));

        // SdkMetricValue <-> MetricValue
        let sdk_v = SdkMetricValue::Integer(42);
        let v: MetricValue = sdk_v.into();
        assert!(matches!(v, MetricValue::Integer(42)));
    }
}