product-os-openapi 0.0.6

Product OS : OpenAPI provides a set of structs for defining the structure of an OpenAPI / Swagger specification. This crate is no_std compatible and requires the 'openapi' feature for serialization/deserialization support. Intended to be used with Product OS : Connector.
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
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! # Product OS OpenAPI
//!
//! A `no_std` compatible library for working with OpenAPI/Swagger specifications.
//!
//! This crate provides strongly-typed data structures for both OpenAPI v2 (Swagger) and
//! OpenAPI v3.x specifications, with full serialization and deserialization support via `serde`.
//!
//! ## Features
//!
//! - **Dual Version Support**: Works with both Swagger 2.0 and OpenAPI 3.x specifications
//! - **no_std Compatible**: Can be used in embedded and constrained environments
//! - **Type Safety**: Strongly typed structs with proper validation through the type system
//! - **Serde Integration**: Full JSON serialization/deserialization support
//!
//! ## Cargo Features
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `std` | Yes | Standard library support via `no-std-compat/std` |
//! | `openapi` | Yes | Serde serialization/deserialization for OpenAPI structs |
//!
//! ## Usage Examples
//!
//! ### Parsing OpenAPI v3 Specification
//!
//! ```rust
//! use product_os_openapi::{ProductOSOpenAPI, Info};
//! use serde_json;
//!
//! let json = r#"{
//!     "openapi": "3.0.0",
//!     "info": {
//!         "title": "My API",
//!         "version": "1.0.0"
//!     }
//! }"#;
//!
//! let spec: ProductOSOpenAPI = serde_json::from_str(json)
//!     .expect("Failed to parse OpenAPI spec");
//!
//! assert_eq!(spec.info.title, "My API");
//! ```
//!
//! ### Parsing Swagger v2 Specification
//!
//! ```rust
//! use product_os_openapi::ProductOSOpenAPI;
//! use serde_json;
//!
//! let json = r#"{
//!     "swagger": "2.0",
//!     "info": {
//!         "title": "My API",
//!         "version": "1.0.0"
//!     },
//!     "host": "api.example.com",
//!     "basePath": "/v1"
//! }"#;
//!
//! let spec: ProductOSOpenAPI = serde_json::from_str(json)
//!     .expect("Failed to parse Swagger spec");
//!
//! assert_eq!(spec.swagger, Some("2.0".to_owned()));
//! ```
//!
//! ### Creating Specifications Programmatically
//!
//! ```rust
//! use product_os_openapi::{ProductOSOpenAPI, Info};
//! use serde_json;
//!
//! let spec = ProductOSOpenAPI {
//!     openapi: Some("3.0.0".to_owned()),
//!     info: Info {
//!         title: "My API".to_owned(),
//!         version: "1.0.0".to_owned(),
//!         description: Some("A test API".to_owned()),
//!         summary: None,
//!         terms_of_service: None,
//!         contact: None,
//!         license: None,
//!     },
//!     json_schema_dialect: None,
//!     servers: None,
//!     paths: None,
//!     webhooks: None,
//!     components: None,
//!     definitions: None,
//!     security: None,
//!     tags: None,
//!     external_docs: None,
//!     swagger: None,
//!     host: None,
//!     base_path: None,
//!     schemes: None,
//!     consumes: None,
//!     produces: None,
//! };
//!
//! let json = serde_json::to_string_pretty(&spec).unwrap();
//! ```
//!
//! ## OpenAPI v2 vs v3
//!
//! This crate supports both versions by including fields from both specifications in the
//! main [`ProductOSOpenAPI`] struct:
//!
//! - **OpenAPI v3** uses: `openapi`, `servers`, `components`, `webhooks`, `json_schema_dialect`
//! - **Swagger v2** uses: `swagger`, `host`, `base_path`, `schemes`, `consumes`, `produces`, `definitions`
//! - **Both versions** share: `info`, `paths`, `security`, `tags`, `external_docs`
//!
//! When deserializing, the appropriate fields will be populated based on the specification version.

#![no_std]
extern crate no_std_compat as std;
extern crate alloc;

use std::prelude::v1::*;

use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Serialize};

/// Type alias for callback definitions.
///
/// Callbacks are complex nested structures mapping callback names to expressions
/// to runtime expressions to Path Items.
pub type Callbacks = BTreeMap<String, BTreeMap<String, BTreeMap<String, PathItem>>>;


/// Root structure for OpenAPI/Swagger specifications.
///
/// This struct supports both OpenAPI v3.x and Swagger v2.0 specifications by including
/// fields from both versions. When parsing a specification, the appropriate fields will
/// be populated based on the version.
///
/// # OpenAPI v3.x Fields
///
/// - `openapi` - Version string (required for v3)
/// - `servers` - Server connectivity information
/// - `components` - Reusable components
/// - `webhooks` - Incoming webhook definitions
/// - `json_schema_dialect` - JSON Schema dialect URI
///
/// # Swagger v2.0 Fields
///
/// - `swagger` - Version string (required for v2, must be "2.0")
/// - `host` - Host serving the API
/// - `base_path` - Base path for all API paths
/// - `schemes` - Transfer protocols (http, https, ws, wss)
/// - `consumes` - MIME types the API can consume
/// - `produces` - MIME types the API can produce
/// - `definitions` - Data type definitions (v2 equivalent of components.schemas)
///
/// # Shared Fields (Both Versions)
///
/// - `info` - API metadata (required)
/// - `paths` - Available API paths and operations
/// - `security` - Security requirements
/// - `tags` - Tag definitions for grouping operations
/// - `external_docs` - External documentation
///
/// # Examples
///
/// ```rust
/// use product_os_openapi::{ProductOSOpenAPI, Info};
/// use serde_json;
///
/// // OpenAPI v3 example
/// let v3_json = r#"{
///     "openapi": "3.0.0",
///     "info": {
///         "title": "My API",
///         "version": "1.0.0"
///     }
/// }"#;
///
/// let v3_spec: ProductOSOpenAPI = serde_json::from_str(v3_json).unwrap();
/// assert_eq!(v3_spec.openapi, Some("3.0.0".to_owned()));
///
/// // Swagger v2 example
/// let v2_json = r#"{
///     "swagger": "2.0",
///     "info": {
///         "title": "My API",
///         "version": "1.0.0"
///     }
/// }"#;
///
/// let v2_spec: ProductOSOpenAPI = serde_json::from_str(v2_json).unwrap();
/// assert_eq!(v2_spec.swagger, Some("2.0".to_owned()));
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProductOSOpenAPI {
    /// The OpenAPI Specification version (e.g., "3.0.0", "3.1.0"). Required for OpenAPI v3.
    pub openapi: Option<String>,
    
    /// Metadata about the API. This field is required in both OpenAPI v3 and Swagger v2.
    pub info: Info,
    
    /// The default JSON Schema dialect for Schema Objects. Must be a URI.
    /// Only applicable to OpenAPI v3.1+.
    pub json_schema_dialect: Option<String>,
    
    /// An array of Server objects providing connectivity information.
    /// If not provided or empty, the default is a server with url "/".
    /// Only applicable to OpenAPI v3.
    pub servers: Option<Vec<Server>>,
    
    /// The available paths and operations for the API.
    /// Maps path strings (e.g., "/users/{id}") to PathItem objects.
    pub paths: Option<BTreeMap<String, PathItem>>,
    
    /// Incoming webhooks that may be received as part of this API.
    /// Only applicable to OpenAPI v3.1+.
    pub webhooks: Option<BTreeMap<String, PathItem>>,
    
    /// Reusable components including schemas, responses, parameters, etc.
    /// Only applicable to OpenAPI v3.
    pub components: Option<Components>,
    
    /// Data type definitions. This is the Swagger v2 equivalent of `components.schemas`.
    /// Only applicable to Swagger v2.
    pub definitions: Option<BTreeMap<String, Schema>>,
    
    /// Global security requirements. Individual operations can override this.
    /// Each entry represents alternative security requirements (logical OR).
    pub security: Option<Vec<BTreeMap<String, Vec<String>>>>,
    
    /// A list of tags for grouping operations with additional metadata.
    pub tags: Option<Vec<Tag>>,
    
    /// Additional external documentation for the API.
    pub external_docs: Option<ExternalDocs>,

    /// The Swagger Specification version. Must be "2.0" for Swagger v2.
    /// Only applicable to Swagger v2.
    pub swagger: Option<String>,
    
    /// The host (name or IP) serving the API. May include a port.
    /// Only applicable to Swagger v2.
    pub host: Option<String>,
    
    /// The base path on which the API is served, relative to the host.
    /// Must start with a leading slash "/".
    /// Only applicable to Swagger v2.
    pub base_path: Option<String>,
    
    /// Transfer protocols supported by the API (e.g., "http", "https", "ws", "wss").
    /// Only applicable to Swagger v2.
    pub schemes: Option<Vec<String>>,
    
    /// MIME types the API can consume globally.
    /// Can be overridden on specific operations.
    /// Only applicable to Swagger v2.
    pub consumes: Option<Vec<String>>,
    
    /// MIME types the API can produce globally.
    /// Can be overridden on specific operations.
    /// Only applicable to Swagger v2.
    pub produces: Option<Vec<String>>,
}

/// Metadata about the API.
///
/// The Info object provides essential information about the API including its title,
/// version, description, and contact/license information.
///
/// # Required Fields
///
/// - `title` - The title of the API
/// - `version` - The version of the API (distinct from the OpenAPI version)
///
/// # Example
///
/// ```rust
/// use product_os_openapi::{Info, Contact, License};
///
/// let info = Info {
///     title: "My API".to_owned(),
///     version: "1.0.0".to_owned(),
///     summary: Some("A brief summary".to_owned()),
///     description: Some("A detailed description".to_owned()),
///     terms_of_service: Some("https://example.com/terms".to_owned()),
///     contact: Some(Contact {
///         name: Some("API Support".to_owned()),
///         url: Some("https://example.com".to_owned()),
///         email: "support@example.com".to_owned(),
///     }),
///     license: Some(License {
///         name: "Apache 2.0".to_owned(),
///         identifier: Some("Apache-2.0".to_owned()),
///         url: Some("https://www.apache.org/licenses/LICENSE-2.0".to_owned()),
///     }),
/// };
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Info {
    /// The title of the API. This field is required.
    pub title: String,
    
    /// A short summary of the API. (OpenAPI v3.1+)
    pub summary: Option<String>,
    
    /// A description of the API. CommonMark syntax may be used for rich text.
    pub description: Option<String>,
    
    /// A URL to the Terms of Service for the API. Must be a valid URL.
    pub terms_of_service: Option<String>,
    
    /// Contact information for the exposed API.
    pub contact: Option<Contact>,
    
    /// License information for the exposed API.
    pub license: Option<License>,
    
    /// The version of the API. This field is required.
    /// Note: This is distinct from the OpenAPI Specification version.
    pub version: String,
}

/// Contact information for the API.
///
/// Provides contact details for the API maintainers or support team.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Contact {
    /// The identifying name of the contact person/organization.
    pub name: Option<String>,
    
    /// The URL pointing to the contact information. Must be a valid URL.
    pub url: Option<String>,
    
    /// The email address of the contact person/organization.
    pub email: String
}

/// License information for the API.
///
/// Specifies the license under which the API is made available.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct License {
    /// The license name used for the API. This field is required.
    pub name: String,
    
    /// An SPDX license identifier (e.g., "MIT", "Apache-2.0"). (OpenAPI v3.1+)
    pub identifier: Option<String>,
    
    /// A URL to the license. Must be a valid URL.
    pub url: Option<String>
}

/// Server connectivity information.
///
/// Represents a server that provides connectivity to the target API.
/// The URL may contain variables enclosed in curly braces which are substituted
/// using values from the `variables` map.
///
/// # Example
///
/// ```rust
/// use product_os_openapi::{Server, ServerVariable};
/// use std::collections::BTreeMap;
///
/// let mut variables = BTreeMap::new();
/// variables.insert("environment".to_owned(), ServerVariable {
///     default: "production".to_owned(),
///     enumeration: Some(vec!["production".to_owned(), "staging".to_owned()]),
///     description: Some("Environment name".to_owned()),
/// });
///
/// let server = Server {
///     url: "https://{environment}.example.com".to_owned(),
///     description: Some("Main API server".to_owned()),
///     variables: Some(variables),
/// };
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Server {
    /// The URL to the target host. May contain variables in curly braces.
    pub url: String,
    
    /// An optional description of the host. CommonMark syntax may be used.
    pub description: Option<String>,
    
    /// A map of variable name to its value substitution information.
    pub variables: Option<BTreeMap<String, ServerVariable>>
}

/// Variable substitution information for a Server URL.
///
/// Used to provide information about variables that can be substituted
/// in a Server URL template.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerVariable {
    /// An optional enumeration of allowed values for this variable.
    #[serde(rename = "enum")]
    pub enumeration: Option<Vec<String>>,
    
    /// The default value for substitution. This field is required.
    pub default: String,
    
    /// An optional description of the variable. CommonMark syntax may be used.
    pub description: Option<String>
}

/// Reusable components for an OpenAPI specification.
///
/// This struct holds various reusable objects that can be referenced throughout
/// the specification, reducing duplication and improving maintainability.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Components {
    /// Reusable Schema objects (data models).
    pub schemas: Option<BTreeMap<String, Schema>>,
    
    /// Reusable Response objects.
    pub responses: Option<BTreeMap<String, Response>>,
    
    /// Reusable Parameter objects.
    pub parameters: Option<BTreeMap<String, Parameter>>,
    
    /// Reusable Example objects.
    pub examples: Option<BTreeMap<String, Example>>,
    
    /// Reusable Request Body objects.
    pub request_bodies: Option<BTreeMap<String, RequestBody>>,
    
    /// Reusable Header objects.
    pub headers: Option<BTreeMap<String, Header>>,
    
    /// Reusable Security Scheme objects.
    pub security_schemes: Option<BTreeMap<String, SecurityScheme>>,
    
    /// Reusable Link objects.
    pub links: Option<BTreeMap<String, Link>>,
    
    /// Reusable Callback objects.
    pub callbacks: Option<Callbacks>,
    
    /// Reusable Path Item objects.
    pub path_items: Option<BTreeMap<String, PathItem>>,
}

/// Describes a single API path and its operations.
///
/// A Path Item may contain operation objects for HTTP methods (GET, PUT, POST, etc.),
/// or it may be a reference to another Path Item definition.
///
/// # Example
///
/// ```rust
/// use product_os_openapi::{PathItem, Operation};
/// use std::collections::BTreeMap;
///
/// let path_item = PathItem {
///     reference: None,
///     summary: Some("User operations".to_owned()),
///     description: Some("Operations for managing users".to_owned()),
///     get: Some(Operation {
///         summary: Some("Get user".to_owned()),
///         operation_id: Some("getUser".to_owned()),
///         tags: Some(vec!["users".to_owned()]),
///         description: None,
///         external_docs: None,
///         parameters: None,
///         request_body: None,
///         responses: None,
///         callbacks: None,
///         deprecated: None,
///         security: None,
///         servers: None,
///     }),
///     put: None,
///     post: None,
///     delete: None,
///     options: None,
///     head: None,
///     patch: None,
///     trace: None,
///     servers: None,
///     parameters: None,
/// };
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PathItem {
    /// Reference to another Path Item. When present, other fields are overridden.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// A short summary of the path item.
    pub summary: Option<String>,
    
    /// A detailed description of the path item. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Definition of a GET operation on this path.
    pub get: Option<Operation>,
    
    /// Definition of a PUT operation on this path.
    pub put: Option<Operation>,
    
    /// Definition of a POST operation on this path.
    pub post: Option<Operation>,
    
    /// Definition of a DELETE operation on this path.
    pub delete: Option<Operation>,
    
    /// Definition of an OPTIONS operation on this path.
    pub options: Option<Operation>,
    
    /// Definition of a HEAD operation on this path.
    pub head: Option<Operation>,
    
    /// Definition of a PATCH operation on this path.
    pub patch: Option<Operation>,
    
    /// Definition of a TRACE operation on this path.
    pub trace: Option<Operation>,

    /// Alternative servers for operations in this path.
    pub servers: Option<Vec<Server>>,
    
    /// Parameters applicable to all operations in this path.
    /// Can be overridden at the operation level.
    pub parameters: Option<Vec<Parameter>>
}


/// JSON Schema data types supported by OpenAPI.
///
/// Represents the basic data types that can be used in schema definitions.
///
/// # Serialization
///
/// This enum serializes to lowercase strings matching the JSON Schema specification.
///
/// # Example
///
/// ```rust
/// use product_os_openapi::SchemaType;
///
/// assert_eq!(SchemaType::String.to_string(), "string");
/// assert_eq!(SchemaType::Integer.to_string(), "integer");
/// assert_eq!(SchemaType::Array.to_string(), "array");
/// ```
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SchemaType {
    /// JSON object type
    Object,
    /// Numeric type with decimals
    Number,
    /// Numeric type without decimals
    Integer,
    /// String type
    String,
    /// Boolean type (true/false)
    Boolean,
    /// Array type
    Array
}

impl fmt::Display for SchemaType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SchemaType::Object => write!(f, "object"),
            SchemaType::Number => write!(f, "number"),
            SchemaType::Integer => write!(f, "integer"),
            SchemaType::String => write!(f, "string"),
            SchemaType::Boolean => write!(f, "boolean"),
            SchemaType::Array => write!(f, "array")
        }
    }
}


/// Parameter or schema location within an API operation.
///
/// Specifies where a parameter or schema property can be located in an HTTP request.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SchemaLocation {
    /// In the URL path (e.g., `/users/{id}`)
    Path,
    /// In the request body
    Body,
    /// In the URL query string (e.g., `?limit=10`)
    Query,
    /// In an HTTP cookie
    Cookie
}


/// JSON Schema definition for data models.
///
/// Defines the structure and constraints of data types used in the API.
/// Can represent primitive types, objects, arrays, or references to other schemas.
///
/// # Example
///
/// ```rust
/// use product_os_openapi::{Schema, SchemaType, SchemaProperty};
/// use std::collections::BTreeMap;
///
/// let mut properties = BTreeMap::new();
/// properties.insert("id".to_owned(), SchemaProperty {
///     reference: None,
///     description: Some("User ID".to_owned()),
///     all_of: None,
///     kind: Some(SchemaType::Integer),
///     minimum: Some(1),
///     items: None,
///     min_items: None,
///     unique_items: None,
///     min_length: None,
///     required: None,
/// });
///
/// let schema = Schema {
///     reference: None,
///     title: Some("User".to_owned()),
///     description: Some("User model".to_owned()),
///     all_of: None,
///     kind: Some(SchemaType::Object),
///     format: None,
///     properties: Some(properties),
///     minimum: None,
///     maximum: None,
///     items: None,
///     min_items: None,
///     max_items: None,
///     unique_items: None,
///     min_length: None,
///     max_length: None,
///     required: Some(vec!["id".to_owned()]),
///     discriminator: None,
///     xml: None,
///     external_docs: None,
///     example: None,
/// };
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Schema {
    /// Reference to another schema definition. When present, most other fields are ignored.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,

    /// A title for the schema.
    pub title: Option<String>,
    
    /// A description of the schema. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Composition of schemas using allOf (all schemas must match).
    pub all_of: Option<Vec<Box<Schema>>>,

    /// The data type of the schema.
    #[serde(rename = "type")]
    pub kind: Option<SchemaType>,
    
    /// Additional format information (e.g., "email", "date-time", "uuid").
    pub format: Option<String>,
    
    /// Properties of an object schema. Maps property names to their schemas.
    pub properties: Option<BTreeMap<String, SchemaProperty>>,
    
    /// Minimum value for numeric types.
    pub minimum: Option<u64>,
    
    /// Maximum value for numeric types.
    pub maximum: Option<u64>,
    
    /// Schema for items in an array.
    pub items: Option<Box<Schema>>,
    
    /// Minimum number of items in an array.
    pub min_items: Option<u64>,
    
    /// Maximum number of items in an array.
    pub max_items: Option<u64>,
    
    /// Whether array items must be unique.
    pub unique_items: Option<bool>,
    
    /// Minimum length for string types.
    pub min_length: Option<u64>,
    
    /// Maximum length for string types.
    pub max_length: Option<u64>,
    
    /// List of required property names for object types.
    pub required: Option<Vec<String>>,

    /// Discriminator for polymorphism support.
    pub discriminator: Option<Discriminator>,
    
    /// XML metadata for XML serialization.
    pub xml: Option<XML>,
    
    /// Additional external documentation for this schema.
    pub external_docs: Option<ExternalDocs>,
    
    /// Example value for this schema.
    pub example: Option<serde_json::Value>,
}


/// Property definition within a Schema.
///
/// Similar to Schema but simplified for use as object properties.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SchemaProperty {
    /// Reference to another schema definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,

    /// Description of the property. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Composition of schemas using allOf.
    pub all_of: Option<Vec<Box<SchemaProperty>>>,

    /// The data type of the property.
    #[serde(rename = "type")]
    pub kind: Option<SchemaType>,
    
    /// Minimum value for numeric types.
    pub minimum: Option<u64>,
    
    /// Schema for items if this property is an array.
    pub items: Option<Box<Schema>>,
    
    /// Minimum number of items if this property is an array.
    pub min_items: Option<u64>,
    
    /// Whether array items must be unique.
    pub unique_items: Option<bool>,
    
    /// Minimum length for string types.
    pub min_length: Option<u64>,
    
    /// List of required nested property names.
    pub required: Option<Vec<String>>,
}



/// Discriminator for polymorphism support.
///
/// Used to differentiate between schemas in inheritance/polymorphism scenarios.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Discriminator {
    /// The name of the property that holds the discriminator value. This field is required.
    pub property_name: String,
    
    /// Mapping between payload values and schema names or references.
    pub mapping: Option<BTreeMap<String, String>>
}

/// XML serialization metadata.
///
/// Provides information for XML representation of schema properties.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct XML {
    /// Replaces the name of the element/attribute.
    pub name: Option<String>,
    
    /// The URI of the namespace definition. Must be an absolute URI.
    pub namespace: Option<String>,
    
    /// The prefix to be used for the name.
    pub prefix: Option<String>,
    
    /// Whether the property translates to an XML attribute (default: false).
    pub attribute: Option<bool>,
    
    /// Whether arrays are wrapped in an element (default: false).
    pub wrapped: Option<bool>,
}


/// A single API operation on a path.
///
/// Describes a single operation (HTTP method) available on a path, including
/// parameters, request body, responses, and security requirements.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Operation {
    /// Tags for logical grouping of operations.
    pub tags: Option<Vec<String>>,
    
    /// A short summary of the operation.
    pub summary: Option<String>,
    
    /// A detailed description of the operation. CommonMark syntax may be used.
    pub description: Option<String>,
    
    /// Additional external documentation for this operation.
    pub external_docs: Option<ExternalDocs>,
    
    /// Unique identifier for the operation. Should follow naming conventions.
    pub operation_id: Option<String>,
    
    /// Parameters applicable for this operation.
    pub parameters: Option<Vec<Parameter>>,
    
    /// The request body for this operation.
    pub request_body: Option<RequestBody>,
    
    /// Possible responses from this operation, keyed by HTTP status code or "default".
    pub responses: Option<BTreeMap<String, Response>>,
    
    /// Callbacks that may be initiated by the API provider.
    pub callbacks: Option<BTreeMap<String, BTreeMap<String, PathItem>>>,
    
    /// Whether this operation is deprecated (default: false).
    pub deprecated: Option<bool>,
    
    /// Security requirements for this operation. Overrides global security.
    pub security: Option<Vec<BTreeMap<String, Vec<String>>>>,
    
    /// Alternative server for this operation.
    pub servers: Option<Server>,
}


/// Response from an API operation.
///
/// Describes a single response from an operation, including headers, content, and links.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Response {
    /// Reference to a response definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary of the response.
    pub summary: Option<String>,
    
    /// Description of the response. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Response headers, keyed by header name.
    pub headers: Option<BTreeMap<String, Header>>,
    
    /// Response content, keyed by media type (e.g., "application/json").
    pub content: Option<BTreeMap<String, MediaType>>,
    
    /// Links to operations that can be followed from this response.
    pub links: Option<BTreeMap<String, Link>>,
    
    /// Schema for the response (Swagger v2 only).
    pub schema: Option<Schema>,
}

/// Operation parameter.
///
/// Describes a single operation parameter that can be located in the path, query, header, or cookie.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Parameter {
    /// Reference to a parameter definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary of the parameter.
    pub summary: Option<String>,
    
    /// Description of the parameter. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Name of the parameter. Required unless this is a reference.
    pub name: Option<String>,
    
    /// Location of the parameter: "query", "header", "path", or "cookie".
    #[serde(rename = "in")]
    pub location: Option<String>,
    
    /// Whether the parameter is mandatory. Path parameters must be required.
    pub required: Option<bool>,
    
    /// Whether the parameter is deprecated (default: false).
    pub deprecated: Option<bool>,
    
    /// Whether empty-valued parameters are allowed (default: false).
    pub allow_empty_value: Option<bool>,

    /// Serialization style for the parameter value.
    pub style: Option<String>,
    
    /// Whether to generate separate parameters for array/object values.
    pub explode: Option<bool>,
    
    /// Whether to allow reserved characters without percent-encoding.
    pub allow_reserved: Option<bool>,
    
    /// Schema defining the parameter type.
    pub schema: Option<Schema>,
    
    /// Example value for the parameter.
    pub example: Option<serde_json::Value>,
    
    /// Multiple examples for the parameter.
    pub examples: Option<BTreeMap<String, Example>>,
    
    /// Content representation for complex parameters.
    pub content: Option<BTreeMap<String, MediaType>>,
}


/// Example value for a parameter, request body, or response.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Example {
    /// Reference to an example definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary of the example.
    pub summary: Option<String>,
    
    /// Long description of the example. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Embedded literal example value.
    pub value: Option<serde_json::Value>,
    
    /// URI pointing to an external example.
    pub external_value: Option<String>
}


/// Request body for an operation.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestBody {
    /// Reference to a request body definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary of the request body.
    pub summary: Option<String>,
    
    /// Description of the request body. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Content of the request body, keyed by media type. This field is required.
    pub content: BTreeMap<String, MediaType>,
    
    /// Whether the request body is required (default: false).
    pub required: Option<bool>,
}

/// HTTP header definition.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Header {
    /// Reference to a header definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary of the header.
    pub summary: Option<String>,
    
    /// Description of the header. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Whether the header is required (default: false).
    pub required: Option<bool>,
    
    /// Whether the header is deprecated (default: false).
    pub deprecated: Option<bool>,
    
    /// Whether empty values are allowed (default: false).
    pub allow_empty_value: Option<bool>,
    
    /// Serialization style for the header value.
    pub style: Option<String>,

    /// Whether to generate separate parameters for array/object values.
    pub explode: Option<bool>,
    
    /// Whether to allow reserved characters.
    pub allow_reserved: Option<bool>,
    
    /// Schema defining the header type.
    pub schema: Option<Schema>,
    
    /// Example value for the header.
    pub example: Option<serde_json::Value>,
    
    /// Multiple examples for the header.
    pub examples: Option<BTreeMap<String, Example>>,
    
    /// Content representation for the header.
    pub content: Option<BTreeMap<String, MediaType>>,
}

/// Media type and schema for request/response content.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaType {
    /// Schema defining the content structure.
    pub schema: Option<Schema>,
    
    /// Example of the media type content.
    pub example: Option<serde_json::Value>,
    
    /// Multiple examples of the media type content.
    pub examples: Option<BTreeMap<String, Example>>,
    
    /// Encoding information for specific properties (multipart/form-data, application/x-www-form-urlencoded).
    pub encoding: Option<BTreeMap<String, Encoding>>,
}

/// Property encoding information for multipart and form-urlencoded request bodies.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Encoding {
    /// Content-Type for encoding a specific property.
    pub content_type: Option<String>,
    
    /// Additional headers for the property.
    pub headers: Option<BTreeMap<String, Header>>,
    
    /// Serialization style for the property value.
    pub style: Option<String>,
    
    /// Whether to generate separate parameters for array/object values.
    pub explode: Option<bool>,
    
    /// Whether to allow reserved characters.
    pub allow_reserved: Option<bool>
}

/// Security scheme definition.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SecurityScheme {
    /// Reference to a security scheme definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary of the security scheme.
    pub summary: Option<String>,
    
    /// Description of the security scheme. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Type of security scheme: "apiKey", "http", "mutualTLS", "oauth2", or "openIdConnect". Required.
    #[serde(rename = "type")]
    pub kind: String,
    
    /// Name of the API key header, query, or cookie parameter (for apiKey type).
    pub api_key: Option<String>,

    /// Location of the API key: "query", "header", or "cookie" (for apiKey type).
    #[serde(rename = "in")]
    pub location: Option<String>,
    
    /// HTTP authorization scheme name (for http type). Required for http type.
    pub scheme: String,
    
    /// Hint for bearer token format, e.g., "JWT" (for http bearer type).
    pub bearer_format: Option<String>,
    
    /// OAuth2 flow configurations (for oauth2 type). Required for oauth2 type.
    pub flows: Option<OAuthFlows>,
    
    /// OpenID Connect URL for OAuth2 configuration discovery (for openIdConnect type). Required for openIdConnect type.
    pub open_id_connect_url: Option<String>,
}

/// OAuth2 flow configurations.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthFlows {
    /// OAuth2 implicit flow configuration.
    pub implicit: Option<OAuthFlow>,
    
    /// OAuth2 resource owner password flow configuration.
    pub password: Option<OAuthFlow>,
    
    /// OAuth2 client credentials flow configuration.
    pub client_credentials: Option<OAuthFlow>,
    
    /// OAuth2 authorization code flow configuration.
    pub authorization_code: Option<OAuthFlow>,
}

/// Single OAuth2 flow configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthFlow {
    /// Authorization URL (required for implicit and authorizationCode flows).
    pub authorization_url: String,
    
    /// Token URL (required for password, clientCredentials, and authorizationCode flows).
    pub token_url: String,
    
    /// Refresh token URL.
    pub refresh_url: Option<String>,
    
    /// Available scopes. Maps scope names to descriptions. Required.
    pub scopes: BTreeMap<String, String>
}

/// Link to an operation that can be followed from a response.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Link {
    /// Reference to a link definition.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary of the link.
    pub summary: Option<String>,
    
    /// Description of the link. CommonMark syntax may be used.
    pub description: Option<String>,

    /// Relative or absolute URI reference to an operation.
    pub operation_ref: Option<String>,
    
    /// Name of an existing operation (mutually exclusive with operation_ref).
    pub operation_id: Option<String>,
    
    /// Parameters to pass to the linked operation.
    pub parameters: Option<BTreeMap<String, serde_json::Value>>,
    
    /// Request body to use when calling the linked operation.
    pub request_body: Option<serde_json::Value>,
    
    /// Server to use for the linked operation.
    pub server: Option<Server>,
}

/// Tag for grouping operations.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Tag {
    /// Name of the tag. Required.
    pub name: String,
    
    /// Description of the tag. CommonMark syntax may be used.
    pub description: Option<String>,
    
    /// Additional external documentation for the tag.
    pub external_docs: Option<ExternalDocs>,
}


/// External documentation reference.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalDocs {
    /// URL to the external documentation. Required.
    pub url: String,
    
    /// Description of the external documentation. CommonMark syntax may be used.
    pub description: Option<String>
}

/// Reference to a reusable component.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Reference {
    /// The reference identifier URI. Required.
    #[serde(rename = "$ref")]
    pub reference: Option<String>,
    
    /// Short summary overriding the referenced component's summary.
    pub summary: Option<String>,
    
    /// Description overriding the referenced component's description. CommonMark syntax may be used.
    pub description: Option<String>
}

// Implementation methods for convenience and validation
impl ProductOSOpenAPI {
    /// Checks if this is an OpenAPI v3.x specification.
    ///
    /// Returns `true` if the `openapi` field is present, indicating this is an OpenAPI v3 spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// use product_os_openapi::{ProductOSOpenAPI, Info};
    ///
    /// let spec = ProductOSOpenAPI {
    ///     openapi: Some("3.0.0".to_owned()),
    ///     info: Info {
    ///         title: "Test".to_owned(),
    ///         version: "1.0.0".to_owned(),
    ///         summary: None,
    ///         description: None,
    ///         terms_of_service: None,
    ///         contact: None,
    ///         license: None,
    ///     },
    ///     json_schema_dialect: None,
    ///     servers: None,
    ///     paths: None,
    ///     webhooks: None,
    ///     components: None,
    ///     definitions: None,
    ///     security: None,
    ///     tags: None,
    ///     external_docs: None,
    ///     swagger: None,
    ///     host: None,
    ///     base_path: None,
    ///     schemes: None,
    ///     consumes: None,
    ///     produces: None,
    ///};
    ///
    /// assert!(spec.is_openapi_v3());
    /// ```
    pub fn is_openapi_v3(&self) -> bool {
        self.openapi.is_some()
    }

    /// Checks if this is a Swagger v2.0 specification.
    ///
    /// Returns `true` if the `swagger` field is present, indicating this is a Swagger v2 spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// use product_os_openapi::{ProductOSOpenAPI, Info};
    ///
    /// let spec = ProductOSOpenAPI {
    ///     swagger: Some("2.0".to_owned()),
    ///     info: Info {
    ///         title: "Test".to_owned(),
    ///         version: "1.0.0".to_owned(),
    ///         summary: None,
    ///         description: None,
    ///         terms_of_service: None,
    ///         contact: None,
    ///         license: None,
    ///     },
    ///     openapi: None,
    ///     json_schema_dialect: None,
    ///     servers: None,
    ///     paths: None,
    ///     webhooks: None,
    ///     components: None,
    ///     definitions: None,
    ///     security: None,
    ///     tags: None,
    ///     external_docs: None,
    ///     host: None,
    ///     base_path: None,
    ///     schemes: None,
    ///     consumes: None,
    ///     produces: None,
    /// };
    ///
    /// assert!(spec.is_swagger_v2());
    /// ```
    pub fn is_swagger_v2(&self) -> bool {
        self.swagger.is_some()
    }

    /// Gets the specification version string.
    ///
    /// Returns the OpenAPI version (e.g., "3.0.0") or Swagger version (e.g., "2.0").
    ///
    /// # Example
    ///
    /// ```rust
    /// use product_os_openapi::{ProductOSOpenAPI, Info};
    ///
    /// let spec = ProductOSOpenAPI {
    ///     openapi: Some("3.1.0".to_owned()),
    ///     info: Info {
    ///         title: "Test".to_owned(),
    ///         version: "1.0.0".to_owned(),
    ///         summary: None,
    ///         description: None,
    ///         terms_of_service: None,
    ///         contact: None,
    ///         license: None,
    ///     },
    ///     json_schema_dialect: None,
    ///     servers: None,
    ///     paths: None,
    ///     webhooks: None,
    ///     components: None,
    ///     definitions: None,
    ///     security: None,
    ///     tags: None,
    ///     external_docs: None,
    ///     swagger: None,
    ///     host: None,
    ///     base_path: None,
    ///     schemes: None,
    ///     consumes: None,
    ///     produces: None,
    /// };
    ///
    /// assert_eq!(spec.version(), Some("3.1.0"));
    /// ```
    pub fn version(&self) -> Option<&str> {
        self.openapi.as_deref().or(self.swagger.as_deref())
    }
}