reflow_graph 0.2.1

Graph data structures for Reflow — nodes, edges, IIPs, exports, and analysis.
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
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::collections::HashSet;
#[cfg(target_arch = "wasm32")]
use tsify::*;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

#[derive(Clone, Serialize, Deserialize, Debug, Default, PartialEq, Eq)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct GraphNode {
    pub id: String,
    pub component: String,
    /// Flexible metadata bag — carries all extension data including
    /// component specs, deployment state, and user-defined key-value pairs.
    /// Reserved keys (accessed via typed helpers):
    ///   - `"componentSpec"` → `ComponentSpec`
    ///   - `"dynasb.*"` → deployment metadata from DynASBClient
    #[cfg_attr(target_arch = "wasm32", tsify(type = "Map<string, any> | undefined"))]
    pub metadata: Option<HashMap<String, Value>>,
}

impl GraphNode {
    /// Read the component specification from metadata.
    pub fn component_spec(&self) -> Option<ComponentSpec> {
        self.metadata
            .as_ref()
            .and_then(|m| m.get("componentSpec"))
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// Set the component specification in metadata.
    pub fn set_component_spec(&mut self, spec: ComponentSpec) {
        let meta = self.metadata.get_or_insert_with(HashMap::new);
        if let Ok(v) = serde_json::to_value(&spec) {
            meta.insert("componentSpec".to_string(), v);
        }
    }

    /// Derive the script runtime from the component spec.
    /// Returns `None` if no component spec is set or if the spec is not a script.
    pub fn script_runtime(&self) -> Option<&str> {
        match self.component_spec() {
            Some(ComponentSpec::Script { script }) => Some(
                // Leak avoided by matching known runtimes to static strs
                match script.runtime.as_str() {
                    "python" => "python",
                    "nodejs" => "nodejs",
                    "ruby" => "ruby",
                    "lua" => "lua",
                    _ => return None,
                },
            ),
            _ => None,
        }
    }

    /// Get a typed value from metadata by key.
    pub fn get_metadata<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
        self.metadata
            .as_ref()
            .and_then(|m| m.get(key))
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// Set a typed value in metadata by key.
    pub fn set_metadata<T: Serialize>(&mut self, key: &str, value: &T) {
        let meta = self.metadata.get_or_insert_with(HashMap::new);
        if let Ok(v) = serde_json::to_value(value) {
            meta.insert(key.to_string(), v);
        }
    }
}

/// Runtime environment for script actors
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum ScriptRuntime {
    Python,
    JavaScript,
}

/// Component specification — the contract that tells the runtime what kind
/// of component this is and how to deploy it.
///
/// A graph node's `component` field names the actor. `component_spec` tells
/// the runtime *what* the actor is and where its code lives.
///
/// ```json
/// {
///   "id": "transform",
///   "component": "DataTransformer",
///   "componentSpec": {
///     "type": "script",
///     "script": {
///       "runtime": "nodejs",
///       "source": "inline",
///       "code": "module.exports.handler = (event) => ({ out: event.data * 2 })",
///       "handler": "handler",
///       "dependencies": { "lodash": "^4.17.0" }
///     }
///   }
/// }
/// ```
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[derive(Default)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ComponentSpec {
    /// A pre-registered native Rust actor — resolved by component name
    #[default]
    Native,

    /// A script actor — deployed to a runtime (dynASB, embedded, etc.)
    Script { script: ScriptSpec },

    /// A WASM actor — loaded from a .wasm binary
    Wasm {
        /// Path or URL to the .wasm module
        source: String,
        /// Entry point function name
        handler: String,
    },

    /// A subgraph reference — another graph used as a component
    Subgraph {
        /// Graph name or path
        graph: String,
    },
}

/// Script source and runtime specification.
///
/// For Node.js:
/// ```json
/// {
///   "runtime": "nodejs",
///   "source": "inline",
///   "code": "module.exports.handler = (event) => ({ out: event.data })",
///   "handler": "handler",
///   "dependencies": { "lodash": "^4.17.0", "axios": "^1.6.0" }
/// }
/// ```
///
/// For Python:
/// ```json
/// {
///   "runtime": "python",
///   "source": "file",
///   "path": "./actors/transform.py",
///   "handler": "handler",
///   "dependencies": { "numpy": "*", "pandas": ">=2.0" }
/// }
/// ```
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct ScriptSpec {
    /// Runtime: "nodejs", "python", "ruby", "lua"
    pub runtime: String,

    /// Source type: "inline" (code in `code` field) or "file" (path in `path` field)
    #[serde(default = "default_source_type")]
    pub source: ScriptSourceType,

    /// Inline source code (when source = "inline")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,

    /// File path relative to graph file (when source = "file")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,

    /// Entry point / handler function name
    #[serde(default = "default_handler")]
    pub handler: String,

    /// Package dependencies: { "package_name": "version_spec" }
    /// Node.js: npm packages, Python: pip packages, Ruby: gems, Lua: rocks
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    #[cfg_attr(
        target_arch = "wasm32",
        tsify(type = "Map<string, string> | undefined")
    )]
    pub dependencies: HashMap<String, String>,

    /// Timeout in seconds for script execution
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<u32>,

    /// Memory limit in MB
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_mb: Option<u32>,
}

/// How the script source is provided
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub enum ScriptSourceType {
    /// Code is inline in the `code` field
    #[default]
    Inline,
    /// Code is in a file at `path`
    File,
}

fn default_source_type() -> ScriptSourceType {
    ScriptSourceType::Inline
}

fn default_handler() -> String {
    "handler".to_string()
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct GraphEdge {
    pub port_name: String,
    pub port_id: String,
    pub node_id: String,
    pub index: Option<usize>,
    /// Expose this port. If the graph is a subgraph, exposed port allow other graphs or nodes connect to a specific exposed port
    pub expose: bool,
    pub data: Option<Value>,
    #[cfg_attr(target_arch = "wasm32", tsify(type = "Map<string, any> | undefined"))]
    pub metadata: Option<HashMap<String, Value>>,
    pub port_type: PortType,
}

/// Port types supported by the graph
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(tag = "type", content = "value")]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
pub enum PortType {
    #[default]
    #[serde(rename = "any")]
    Any,
    #[serde(rename = "flow")]
    Flow,
    #[serde(rename = "event")]
    Event,
    #[serde(rename = "boolean")]
    Boolean,
    #[serde(rename = "integer")]
    Integer,
    #[serde(rename = "float")]
    Float,
    #[serde(rename = "string")]
    String,
    #[serde(rename = "object")]
    Object(String),
    #[serde(rename = "array")]
    Array(Box<PortType>),
    #[serde(rename = "encoded")]
    Encoded,
    #[serde(rename = "bytes")]
    Bytes,
    #[serde(rename = "stream")]
    Stream,
    #[serde(rename = "option")]
    Option(Box<PortType>),
}

#[cfg(target_arch = "wasm32")]
impl From<PortType> for JsValue {
    fn from(port_type: PortType) -> Self {
        use gloo_utils::format::JsValueSerdeExt;
        JsValue::from_serde(&port_type).unwrap()
    }
}

#[cfg(target_arch = "wasm32")]
impl TryFrom<JsValue> for PortType {
    type Error = serde_json::Error;

    fn try_from(value: JsValue) -> Result<Self, Self::Error> {
        use gloo_utils::format::JsValueSerdeExt;
        value.into_serde()
    }
}

// TypeScript type generation
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(typescript_custom_section))]
#[allow(dead_code)]
const TS_PORT_TYPE_DEF: &str = r#"
export type PortType =
  | { type: "flow" }
  | { type: "event" }
  | { type: "boolean" }
  | { type: "integer" }
  | { type: "float" }
  | { type: "string" }
  | { type: "object", value: string }
  | { type: "array", value: PortType }
  | { type: "bytes" }
  | { type: "stream" }
  | { type: "encoded" }
  | { type: "any" }
  | { type: "option", value: PortType };
"#;

// #[cfg(target_arch = "wasm32")]
// #[wasm_bindgen]
// impl PortType {
//     #[wasm_bindgen(js_name = "Any")]
//     pub fn any() -> Self {
//         Self::Any
//     }

//     #[wasm_bindgen(js_name = "Flow")]
//     pub fn flow() -> Self {
//         Self::Flow
//     }

//     #[wasm_bindgen(js_name = "Event")]
//     pub fn event() -> Self {
//         Self::Event
//     }
//     #[wasm_bindgen(js_name = "Boolean")]
//     pub fn boolean() -> Self {
//         Self::Boolean
//     }
//     #[wasm_bindgen(js_name = "Integer")]
//     pub fn integer() -> Self {
//         Self::Integer
//     }
//     #[wasm_bindgen(js_name = "Float")]
//     pub fn float() -> Self {
//         Self::Float
//     }
//     #[wasm_bindgen(js_name = "String")]
//     pub fn string() -> Self {
//         Self::String
//     }
//     #[wasm_bindgen(js_name = "Object")]
//     pub fn object(value: String) -> Self {
//         Self::Object(value)
//     }
//     #[wasm_bindgen(js_name = "Array")]
//     pub fn array(value: PortType) -> Self {
//         Self::Array(Box::new(value))
//     }
//     #[wasm_bindgen(js_name = "Stream")]
//     pub fn stream() -> Self {
//         Self::Stream
//     }
//     #[wasm_bindgen(js_name = "Encoded")]
//     pub fn encoded() -> Self {
//         Self::Encoded
//     }
//     #[wasm_bindgen(js_name = "Option")]
//     pub fn option(value: PortType) -> Self {
//         Self::Option(Box::new(value))
//     }
//     #[wasm_bindgen(js_name = "isAny")]
//     pub fn is_any(&self) -> bool {
//         matches!(self, Self::Any)
//     }
//     #[wasm_bindgen(js_name = "isFlow")]
//     pub fn is_flow(&self) -> bool {
//         matches!(self, Self::Flow)
//     }
//     #[wasm_bindgen(js_name = "isEvent")]
//     pub fn is_event(&self) -> bool {
//         matches!(self, Self::Event)
//     }
//     #[wasm_bindgen(js_name = "isBoolean")]
//     pub fn is_boolean(&self) -> bool {
//         matches!(self, Self::Boolean)
//     }
//     #[wasm_bindgen(js_name = "isInteger")]
//     pub fn is_integer(&self) -> bool {
//         matches!(self, Self::Integer)
//     }
//     #[wasm_bindgen(js_name = "isFloat")]
//     pub fn is_float(&self) -> bool {
//         matches!(self, Self::Float)
//     }
//     #[wasm_bindgen(js_name = "isString")]
//     pub fn is_string(&self) -> bool {
//         matches!(self, Self::String)
//     }
//     #[wasm_bindgen(js_name = "isObject")]
//     pub fn is_object(&self) -> bool {
//         matches!(self, Self::Object(_))
//     }
//     #[wasm_bindgen(js_name = "isArray")]
//     pub fn is_array(&self) -> bool {
//         matches!(self, Self::Array(_))
//     }
//     #[wasm_bindgen(js_name = "isStream")]
//     pub fn is_stream(&self) -> bool {
//         matches!(self, Self::Stream)
//     }
//     #[wasm_bindgen(js_name = "isEncoded")]
//     pub fn is_encoded(&self) -> bool {
//         matches!(self, Self::Encoded)
//     }
//     #[wasm_bindgen(js_name = "isOption")]
//     pub fn is_option(&self) -> bool {
//         matches!(self, Self::Option(_))
//     }
//     // #[wasm_bindgen(js_name = "isCompatibleWith")]
//     // pub fn is_compatible_with(&self, other: Self) -> bool {
//     //     match (self, other) {
//     //         (_, PortType::Any) | (PortType::Any, _) => true,
//     //         (a, b) if *a == b => true,
//     //         (PortType::Array(a), PortType::Array(b)) => a.is_compatible_with(b.as_ref().clone()),
//     //         (PortType::Option(a), b) => a.is_compatible_with(b.clone()),
//     //         (a, PortType::Option(b)) => a.is_compatible_with(*b),
//     //         // (PortType::Generic(_), _) | (_, PortType::Generic(_)) => true,
//     //         // (PortType::Tuple(a), PortType::Tuple(b)) => {
//     //         //     a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| a.is_compatible_with(b))
//     //         // }
//     //         (PortType::Integer, PortType::Float) => true,
//     //         (PortType::Stream, _) | (_, PortType::Stream) => true,
//     //         (PortType::Float, PortType::Integer) => true,
//     //         (PortType::Encoded, PortType::Encoded) => true,
//     //         _ => false,
//     //     }
//     // }
// }

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct GraphConnection {
    pub from: GraphEdge,
    pub to: GraphEdge,
    #[cfg_attr(target_arch = "wasm32", tsify(type = "Map<string, any> | undefined"))]
    pub metadata: Option<HashMap<String, Value>>,
    pub data: Option<Value>,
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
pub struct GraphIIP {
    pub to: GraphEdge,
    #[cfg_attr(target_arch = "wasm32", tsify(type = "any"))]
    pub data: Value,
    #[cfg_attr(target_arch = "wasm32", tsify(type = "Map<string, any> | undefined"))]
    pub metadata: Option<HashMap<String, Value>>,
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct GraphGroup {
    pub id: String,
    pub nodes: Vec<String>,
    #[cfg_attr(target_arch = "wasm32", tsify(type = "Map<string, any> | undefined"))]
    pub metadata: Option<HashMap<String, Value>>,
}

/// Graph dependency for workspace composition
#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct GraphDependency {
    pub graph_name: String,
    pub namespace: Option<String>,
    pub version_constraint: Option<String>,
    pub required: bool,
    pub description: Option<String>,
}

/// External connection to other graphs in workspace
#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct ExternalConnection {
    pub connection_id: String,
    pub target_graph: String,
    pub target_namespace: Option<String>,
    pub from_process: String,
    pub from_port: String,
    pub to_process: String,
    pub to_port: String,
    pub description: Option<String>,
    #[cfg_attr(target_arch = "wasm32", tsify(type = "Map<string, any> | undefined"))]
    pub metadata: Option<HashMap<String, Value>>,
}

/// Interface definition for workspace graph interfaces
#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct InterfaceDefinition {
    pub interface_id: String,
    pub process_name: String,
    pub port_name: String,
    pub data_type: Option<String>,
    pub description: Option<String>,
    pub required: bool,
    #[cfg_attr(target_arch = "wasm32", tsify(type = "Map<string, any> | undefined"))]
    pub metadata: Option<HashMap<String, Value>>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct GraphExport {
    pub case_sensitive: bool,
    #[cfg_attr(
        target_arch = "wasm32",
        tsify(type = "Map<string, any>"),
        serde(default = "default_properties")
    )]
    pub properties: HashMap<String, Value>,
    #[serde(default = "default_port")]
    pub inports: HashMap<String, GraphEdge>,
    #[serde(default = "default_port")]
    pub outports: HashMap<String, GraphEdge>,
    #[serde(default = "default_groups")]
    pub groups: Vec<GraphGroup>,
    #[serde(default = "default_processes")]
    pub processes: HashMap<String, GraphNode>,
    #[serde(default = "default_connections")]
    pub connections: Vec<GraphConnection>,

    // New workspace fields (Optional for backward compatibility)
    #[serde(
        default = "default_graph_dependencies",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub graph_dependencies: Vec<GraphDependency>,

    #[serde(
        default = "default_external_connections",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub external_connections: Vec<ExternalConnection>,

    #[serde(
        default = "default_provided_interfaces",
        skip_serializing_if = "HashMap::is_empty"
    )]
    pub provided_interfaces: HashMap<String, InterfaceDefinition>,

    #[serde(
        default = "default_required_interfaces",
        skip_serializing_if = "HashMap::is_empty"
    )]
    pub required_interfaces: HashMap<String, InterfaceDefinition>,
}

pub fn default_properties() -> HashMap<String, Value> {
    HashMap::from_iter([("name".to_string(), json!("My Graph"))])
}

pub fn default_processes() -> HashMap<String, GraphNode> {
    HashMap::new()
}

pub fn default_port() -> HashMap<String, GraphEdge> {
    HashMap::new()
}

pub fn default_groups() -> Vec<GraphGroup> {
    Vec::new()
}

pub fn default_connections() -> Vec<GraphConnection> {
    Vec::new()
}

pub fn default_graph_dependencies() -> Vec<GraphDependency> {
    Vec::new()
}

pub fn default_external_connections() -> Vec<ExternalConnection> {
    Vec::new()
}

pub fn default_provided_interfaces() -> HashMap<String, InterfaceDefinition> {
    HashMap::new()
}

pub fn default_required_interfaces() -> HashMap<String, InterfaceDefinition> {
    HashMap::new()
}

type EventValue = Value;

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(namespace))]
#[serde(tag = "_type")]
pub enum GraphEvents {
    AddNode(EventValue),
    RemoveNode(EventValue),
    RenameNode(EventValue),
    ChangeNode(EventValue),
    AddConnection(EventValue),
    RemoveConnection(EventValue),
    ChangeConnection(EventValue),
    AddInitial(EventValue),
    RemoveInitial(EventValue),
    ChangeProperties(EventValue),
    AddGroup(EventValue),
    RemoveGroup(EventValue),
    RenameGroup(EventValue),
    ChangeGroup(EventValue),
    AddInport(EventValue),
    RemoveInport(EventValue),
    RenameInport(EventValue),
    ChangeInport(EventValue),
    AddOutport(EventValue),
    RemoveOutport(EventValue),
    RenameOutport(EventValue),
    ChangeOutport(EventValue),
    StartTransaction(EventValue),
    EndTransaction(EventValue),
    Transaction(EventValue),
    #[default]
    None,
}

#[derive(Debug, Clone)]
pub enum GraphError {
    NodeNotFound(String),
    DuplicateNode(String),
    InvalidConnection { from: String, to: String },
    CycleDetected,
    InvalidOperation(String),
}

impl std::fmt::Display for GraphError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GraphError::NodeNotFound(id) => write!(f, "Node not found: {}", id),
            GraphError::DuplicateNode(id) => write!(f, "Node already exists: {}", id),
            GraphError::InvalidConnection { from, to } => {
                write!(f, "Invalid connection from {} to {}", from, to)
            }
            GraphError::CycleDetected => write!(f, "Cycle detected in graph"),
            GraphError::InvalidOperation(msg) => write!(f, "Invalid operation: {}", msg),
        }
    }
}

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

/// Second tier: Workspace-enhanced graph export with discovery metadata
#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceGraphExport {
    /// The core graph definition (first tier)
    #[serde(flatten)]
    pub graph: GraphExport,

    /// Workspace discovery metadata
    pub workspace_metadata: WorkspaceMetadata,
}

/// Metadata added during workspace discovery
#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceMetadata {
    /// Discovered namespace based on file structure
    pub discovered_namespace: String,

    /// Original file path relative to workspace root
    pub source_path: String,

    /// File format detected
    pub source_format: WorkspaceFileFormat,

    /// Discovery timestamp
    pub discovered_at: String,

    /// File size in bytes
    pub file_size: u64,

    /// Last modified time of source file
    pub last_modified: Option<String>,

    /// Resolved dependencies after analysis
    pub resolved_dependencies: Vec<ResolvedDependency>,

    /// Auto-discovered connections to other graphs
    pub auto_connections: Vec<AutoDiscoveredConnection>,

    /// Interface compatibility analysis
    pub interface_analysis: InterfaceAnalysis,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
pub enum WorkspaceFileFormat {
    Json,
    Yaml,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct ResolvedDependency {
    /// The dependency graph name
    pub target_graph: String,

    /// Target graph's namespace
    pub target_namespace: String,

    /// Whether dependency was resolved successfully
    pub resolved: bool,

    /// Version constraint if specified
    pub version_constraint: Option<String>,

    /// Resolution status
    pub resolution_status: DependencyResolutionStatus,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
pub enum DependencyResolutionStatus {
    Resolved,
    NotFound,
    VersionMismatch,
    CircularDependency,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct AutoDiscoveredConnection {
    /// Unique identifier for this connection
    pub connection_id: String,

    /// Source graph name
    pub from_graph: String,

    /// Source graph namespace
    pub from_namespace: String,

    /// Source interface name
    pub from_interface: String,

    /// Target graph name
    pub to_graph: String,

    /// Target graph namespace
    pub to_namespace: String,

    /// Target interface name
    pub to_interface: String,

    /// Confidence score (0.0 to 1.0)
    pub confidence: f64,

    /// How this connection was discovered
    pub discovery_method: DiscoveryMethod,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
pub enum DiscoveryMethod {
    ExplicitDeclaration,
    InterfaceMatching,
    DataTypeCompatibility,
    NamingConvention,
    DependencyAnalysis,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
#[derive(Default)]
pub struct InterfaceAnalysis {
    /// Number of provided interfaces
    pub provided_count: usize,

    /// Number of required interfaces
    pub required_count: usize,

    /// Compatibility scores with other graphs
    pub compatibility_scores: HashMap<String, f64>,

    /// Interface type mismatches found
    pub type_mismatches: Vec<InterfaceTypeMismatch>,

    /// Unused provided interfaces
    pub unused_provided: Vec<String>,

    /// Unsatisfied required interfaces
    pub unsatisfied_required: Vec<String>,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
#[serde(rename_all = "camelCase")]
pub struct InterfaceTypeMismatch {
    pub provided_interface: String,
    pub provided_type: Option<String>,
    pub required_interface: String,
    pub required_type: Option<String>,
    pub target_graph: String,
    pub severity: MismatchSeverity,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify))]
#[cfg_attr(target_arch = "wasm32", tsify(into_wasm_abi))]
#[cfg_attr(target_arch = "wasm32", tsify(from_wasm_abi))]
pub enum MismatchSeverity {
    Warning,
    Error,
    Critical,
}

impl WorkspaceGraphExport {
    /// Create a WorkspaceGraphExport from a base GraphExport
    pub fn from_graph_export(graph: GraphExport, workspace_metadata: WorkspaceMetadata) -> Self {
        WorkspaceGraphExport {
            graph,
            workspace_metadata,
        }
    }

    /// Extract the base GraphExport
    pub fn into_graph_export(self) -> GraphExport {
        self.graph
    }

    /// Get a reference to the base GraphExport
    pub fn graph_export(&self) -> &GraphExport {
        &self.graph
    }

    /// Get a mutable reference to the base GraphExport
    pub fn graph_export_mut(&mut self) -> &mut GraphExport {
        &mut self.graph
    }

    /// Get the graph name
    pub fn graph_name(&self) -> Option<&str> {
        self.graph.properties.get("name").and_then(|v| v.as_str())
    }

    /// Get the discovered namespace
    pub fn namespace(&self) -> &str {
        &self.workspace_metadata.discovered_namespace
    }

    /// Check if this graph has unresolved dependencies
    pub fn has_unresolved_dependencies(&self) -> bool {
        self.workspace_metadata
            .resolved_dependencies
            .iter()
            .any(|dep| !dep.resolved)
    }

    /// Get all auto-discovered connections with confidence above threshold
    pub fn get_confident_auto_connections(&self, threshold: f64) -> Vec<&AutoDiscoveredConnection> {
        self.workspace_metadata
            .auto_connections
            .iter()
            .filter(|conn| conn.confidence >= threshold)
            .collect()
    }

    /// Check interface compatibility with another graph
    pub fn is_compatible_with(&self, other_graph_name: &str) -> Option<f64> {
        self.workspace_metadata
            .interface_analysis
            .compatibility_scores
            .get(other_graph_name)
            .copied()
    }
}

impl Default for WorkspaceMetadata {
    fn default() -> Self {
        WorkspaceMetadata {
            discovered_namespace: "default".to_string(),
            source_path: "unknown".to_string(),
            source_format: WorkspaceFileFormat::Json,
            discovered_at: chrono::Utc::now().to_rfc3339(),
            file_size: 0,
            last_modified: None,
            resolved_dependencies: Vec::new(),
            auto_connections: Vec::new(),
            interface_analysis: InterfaceAnalysis::default(),
        }
    }
}

#[derive(Debug, Default)]
pub struct FlowValidation {
    pub cycles: Vec<Vec<String>>,
    pub orphaned_nodes: Vec<String>,
    pub port_mismatches: Vec<PortMismatch>,
}

#[derive(Debug)]
pub struct DataFlowPath {
    pub nodes: Vec<String>,
    pub transforms: Vec<DataTransform>,
}

#[derive(Debug)]
pub struct DataTransform {
    pub node: String,
    pub operation: String,
    pub input_type: String,
    pub output_type: String,
}

#[derive(Debug, Clone)]
pub struct ExecutionPath {
    pub nodes: Vec<String>,
    pub estimated_time: f32,
    pub resource_requirements: HashMap<String, f32>,
}

#[derive(Debug, Default)]
pub struct ParallelismAnalysis {
    pub parallel_branches: Vec<Subgraph>,
    pub pipeline_stages: Vec<PipelineStage>,
    pub max_parallelism: usize,
}

#[derive(Debug)]
pub enum Bottleneck {
    HighDegree(String),
    SequentialChain(Vec<String>),
}

#[derive(Debug, Default)]
pub struct Subgraph {
    pub nodes: Vec<String>,
    pub internal_connections: Vec<GraphConnection>,
    pub entry_points: Vec<String>,
    pub exit_points: Vec<String>,
}

#[derive(Debug)]
pub struct PipelineStage {
    pub level: usize,
    pub nodes: Vec<String>,
}

/// Analysis results for a subgraph
#[derive(Debug, Clone)]
pub struct SubgraphAnalysis {
    pub node_count: usize,
    pub connection_count: usize,
    pub entry_points: Vec<String>,
    pub exit_points: Vec<String>,
    pub is_cyclic: bool,
    pub max_depth: usize,
    pub branching_factor: f64,
}

/// Cycle analysis result
#[derive(Debug)]
pub struct CycleAnalysis {
    pub total_cycles: usize,
    pub cycle_lengths: Vec<usize>,
    pub nodes_in_cycles: HashSet<String>,
    pub longest_cycle: Option<Vec<String>>,
    pub shortest_cycle: Option<Vec<String>>,
}

/// Detailed analysis of orphaned nodes
#[derive(Debug)]
pub struct OrphanedNodeAnalysis {
    pub total_orphaned: usize,
    pub completely_isolated: Vec<String>,
    pub unreachable: Vec<String>,
    pub disconnected_groups: Vec<Vec<String>>,
}

#[derive(Debug, Clone)]
pub struct PortMismatch {
    pub from_node: String,
    pub from_port: String,
    pub from_type: PortType,
    pub to_node: String,
    pub to_port: String,
    pub to_type: PortType,
    pub reason: String,
}

impl std::fmt::Display for PortMismatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Port type mismatch: {}:{} ({:?}) -> {}:{} ({:?}): {}",
            self.from_node,
            self.from_port,
            self.from_type,
            self.to_node,
            self.to_port,
            self.to_type,
            self.reason
        )
    }
}

#[derive(Clone, Debug)]
pub struct NodePosition {
    pub x: f32,
    pub y: f32,
}

#[derive(Clone, Debug)]
pub struct NodeDimensions {
    pub width: f32,
    pub height: f32,
    pub anchor: AnchorPoint,
}

#[derive(Clone, Debug)]
pub struct AnchorPoint {
    pub x: f32, // Relative to node's left edge (0.0 to 1.0)
    pub y: f32, // Relative to node's top edge (0.0 to 1.0)
}

/// Optimization suggestions for graph execution
#[derive(Clone)]
pub enum OptimizationSuggestion {
    ParallelizableChain {
        nodes: Vec<String>,
    },
    RedundantNode {
        node: String,
        reason: String,
    },
    ResourceBottleneck {
        resource: String,
        severity: f64,
    },
    DataTypeOptimization {
        from: String,
        to: String,
        suggestion: String,
    },
}

/// Enhanced analysis result including performance predictions
#[derive(Default)]
pub struct EnhancedGraphAnalysis {
    pub parallelism: ParallelismAnalysis,
    pub estimated_execution_time: f64,
    pub resource_requirements: HashMap<String, f64>,
    pub optimization_suggestions: Vec<OptimizationSuggestion>,
    pub performance_bottlenecks: Vec<Bottleneck>,
}