germanic 0.2.3

Schema-validated binary data for AI agents. JSON to .grm compiler with zero-copy FlatBuffers.
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
//! # Practice Schema
//!
//! Schema for healthcare practitioners, doctors and therapists.
//!
//! ## Data Flow
//!
//! ```text
//! WordPress Plugin
//!//!//!   praxis.json
//!//!//!   serde_json::from_str::<PraxisSchema>()
//!//!//!   PraxisSchema (Rust struct)
//!//!       ├── validate() → Ok(())
//!//!//!   to_bytes() → FlatBuffer Bytes
//!//!//!   .grm file (Header + Payload)
//! ```

use crate::GermanicSchema;
use crate::schema::GermanicSerialize;
use flatbuffers::FlatBufferBuilder;
use serde::{Deserialize, Serialize};

// Import of generated FlatBuffer types
use crate::generated::praxis::de::gesundheit::{
    Adresse as FbAdresse, AdresseArgs as FbAdresseArgs, Praxis as FbPraxis,
    PraxisArgs as FbPraxisArgs,
};

// ============================================================================
// ADRESSE
// ============================================================================

/// Address of a practice.
///
/// ## Fields
///
/// | Field       | Type           | Required | Default |
/// |-------------|----------------|----------|---------|
/// | strasse     | String         | ✅       | -       |
/// | hausnummer  | `Option<String>` | ❌       | None    |
/// | plz         | String         | ✅       | -       |
/// | ort         | String         | ✅       | -       |
/// | land        | String         | ❌       | "DE"    |
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, GermanicSchema)]
#[germanic(schema_id = "de.gesundheit.adresse.v1")]
pub struct AdresseSchema {
    /// Street name (without house number)
    #[germanic(required)]
    pub strasse: String,

    /// House number (optional)
    #[serde(default)]
    pub hausnummer: Option<String>,

    /// Postal code
    #[germanic(required)]
    pub plz: String,

    /// City name
    #[germanic(required)]
    pub ort: String,

    /// Country code (ISO 3166-1 alpha-2)
    #[serde(default = "default_land")]
    #[germanic(default = "DE")]
    pub land: String,
}

fn default_land() -> String {
    "DE".to_string()
}

impl GermanicSerialize for AdresseSchema {
    /// Serializes the address to FlatBuffer bytes.
    ///
    /// **Note:** AdresseSchema alone is not a valid root type.
    /// This method is mainly used for tests.
    /// Normally address is serialized as part of PraxisSchema.
    fn to_bytes(&self) -> Vec<u8> {
        let mut builder = FlatBufferBuilder::with_capacity(256);

        // Create strings (leaves first)
        let strasse = builder.create_string(&self.strasse);
        let hausnummer = self.hausnummer.as_ref().map(|h| builder.create_string(h));
        let plz = builder.create_string(&self.plz);
        let ort = builder.create_string(&self.ort);
        let land = builder.create_string(&self.land);

        // Create address table
        let adresse = FbAdresse::create(
            &mut builder,
            &FbAdresseArgs {
                strasse: Some(strasse),
                hausnummer,
                plz: Some(plz),
                ort: Some(ort),
                land: Some(land),
            },
        );

        // Note: Address is not a root type in the FlatBuffer schema,
        // so we use finish_minimal instead of finish
        builder.finish_minimal(adresse);
        builder.finished_data().to_vec()
    }
}

// ============================================================================
// PRAXIS
// ============================================================================

/// Main schema for a healthcare practice.
///
/// ## Fields
///
/// | Field             | Type           | Required | Description                      |
/// |-------------------|----------------|----------|----------------------------------|
/// | name              | String         | ✅       | Name of practitioner             |
/// | bezeichnung       | String         | ✅       | "Heilpraktikerin", "Arzt", etc.  |
/// | adresse           | AdresseSchema  | ✅       | Complete address                 |
/// | praxisname        | `Option<String>` | ❌       | Name of practice                 |
/// | telefon           | `Option<String>` | ❌       | Phone number                     |
/// | ...               | ...            | ...      | additional optional fields       |
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, GermanicSchema)]
#[germanic(schema_id = "de.gesundheit.praxis.v1")]
pub struct PraxisSchema {
    // ────────────────────────────────────────────────────────────────────────
    // REQUIRED FIELDS
    // ────────────────────────────────────────────────────────────────────────
    /// Name of practitioner
    #[germanic(required)]
    pub name: String,

    /// Professional title
    #[germanic(required)]
    pub bezeichnung: String,

    /// Complete practice address
    pub adresse: AdresseSchema,

    // ────────────────────────────────────────────────────────────────────────
    // OPTIONAL FIELDS
    // ────────────────────────────────────────────────────────────────────────
    /// Name of practice
    #[serde(default)]
    pub praxisname: Option<String>,

    /// Phone number
    #[serde(default)]
    pub telefon: Option<String>,

    /// Email address
    #[serde(default)]
    pub email: Option<String>,

    /// Website URL
    #[serde(default)]
    pub website: Option<String>,

    /// Online appointment booking URL
    #[serde(default)]
    pub terminbuchung_url: Option<String>,

    /// Opening hours as free text
    #[serde(default)]
    pub oeffnungszeiten: Option<String>,

    /// Brief self-description
    #[serde(default)]
    pub kurzbeschreibung: Option<String>,

    // ────────────────────────────────────────────────────────────────────────
    // LISTS
    // ────────────────────────────────────────────────────────────────────────
    /// Medical specializations
    #[serde(default)]
    pub schwerpunkte: Vec<String>,

    /// Offered therapy forms
    #[serde(default)]
    pub therapieformen: Vec<String>,

    /// Qualifications and certificates
    #[serde(default)]
    pub qualifikationen: Vec<String>,

    /// Spoken languages
    #[serde(default)]
    pub sprachen: Vec<String>,

    // ────────────────────────────────────────────────────────────────────────
    // BOOLEANS
    // ────────────────────────────────────────────────────────────────────────
    /// Treats private patients?
    #[serde(default)]
    #[germanic(default = "false")]
    pub privatpatienten: bool,

    /// Treats public insurance patients?
    #[serde(default)]
    #[germanic(default = "false")]
    pub kassenpatienten: bool,
}

impl GermanicSerialize for PraxisSchema {
    /// Serializes the practice schema to FlatBuffer bytes.
    ///
    /// ## Algorithm (Inside-Out)
    ///
    /// ```text
    /// 1. Create strings             → Offsets
    /// 2. Create string vectors      → Offsets
    /// 3. Create address             → Offset (needs string offsets)
    /// 4. Create practice            → Offset (needs all others)
    /// 5. finish()                   → Bytes
    /// ```
    fn to_bytes(&self) -> Vec<u8> {
        // Estimate capacity: ~100 bytes base + strings
        let capacity = 256 + self.name.len() + self.bezeichnung.len();
        let mut builder = FlatBufferBuilder::with_capacity(capacity);

        // ════════════════════════════════════════════════════════════════════
        // STEP 1: Create all strings (leaves first)
        // ════════════════════════════════════════════════════════════════════

        // Required strings
        let name = builder.create_string(&self.name);
        let bezeichnung = builder.create_string(&self.bezeichnung);

        // Optional strings (only if present)
        let praxisname = self.praxisname.as_ref().map(|s| builder.create_string(s));
        let telefon = self.telefon.as_ref().map(|s| builder.create_string(s));
        let email = self.email.as_ref().map(|s| builder.create_string(s));
        let website = self.website.as_ref().map(|s| builder.create_string(s));
        let terminbuchung_url = self
            .terminbuchung_url
            .as_ref()
            .map(|s| builder.create_string(s));
        let oeffnungszeiten = self
            .oeffnungszeiten
            .as_ref()
            .map(|s| builder.create_string(s));
        let kurzbeschreibung = self
            .kurzbeschreibung
            .as_ref()
            .map(|s| builder.create_string(s));

        // ════════════════════════════════════════════════════════════════════
        // STEP 2: Create string vectors
        // ════════════════════════════════════════════════════════════════════
        //
        // FlatBuffer expects: Vector<WIPOffset<&str>>
        // We must first create all strings in the vector, then the vector

        let schwerpunkte = if !self.schwerpunkte.is_empty() {
            let offsets: Vec<_> = self
                .schwerpunkte
                .iter()
                .map(|s| builder.create_string(s))
                .collect();
            Some(builder.create_vector(&offsets))
        } else {
            None
        };

        let therapieformen = if !self.therapieformen.is_empty() {
            let offsets: Vec<_> = self
                .therapieformen
                .iter()
                .map(|s| builder.create_string(s))
                .collect();
            Some(builder.create_vector(&offsets))
        } else {
            None
        };

        let qualifikationen = if !self.qualifikationen.is_empty() {
            let offsets: Vec<_> = self
                .qualifikationen
                .iter()
                .map(|s| builder.create_string(s))
                .collect();
            Some(builder.create_vector(&offsets))
        } else {
            None
        };

        let sprachen = if !self.sprachen.is_empty() {
            let offsets: Vec<_> = self
                .sprachen
                .iter()
                .map(|s| builder.create_string(s))
                .collect();
            Some(builder.create_vector(&offsets))
        } else {
            None
        };

        // ════════════════════════════════════════════════════════════════════
        // STEP 3: Create address (Nested Table)
        // ════════════════════════════════════════════════════════════════════

        let adresse = {
            let strasse = builder.create_string(&self.adresse.strasse);
            let hausnummer = self
                .adresse
                .hausnummer
                .as_ref()
                .map(|h| builder.create_string(h));
            let plz = builder.create_string(&self.adresse.plz);
            let ort = builder.create_string(&self.adresse.ort);
            let land = builder.create_string(&self.adresse.land);

            FbAdresse::create(
                &mut builder,
                &FbAdresseArgs {
                    strasse: Some(strasse),
                    hausnummer,
                    plz: Some(plz),
                    ort: Some(ort),
                    land: Some(land),
                },
            )
        };

        // ════════════════════════════════════════════════════════════════════
        // STEP 4: Create practice (Root)
        // ════════════════════════════════════════════════════════════════════

        let praxis = FbPraxis::create(
            &mut builder,
            &FbPraxisArgs {
                // Required
                name: Some(name),
                bezeichnung: Some(bezeichnung),
                adresse: Some(adresse),
                // Optional
                praxisname,
                telefon,
                email,
                website,
                terminbuchung_url,
                oeffnungszeiten,
                kurzbeschreibung,
                // Vektoren
                schwerpunkte,
                therapieformen,
                qualifikationen,
                sprachen,
                // Booleans
                privatpatienten: self.privatpatienten,
                kassenpatienten: self.kassenpatienten,
            },
        );

        // ════════════════════════════════════════════════════════════════════
        // STEP 5: Finalize
        // ════════════════════════════════════════════════════════════════════

        builder.finish(praxis, None);
        builder.finished_data().to_vec()
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{SchemaMetadata, Validate};

    // ────────────────────────────────────────────────────────────────────────
    // EXISTING TESTS
    // ────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_praxis_schema_id() {
        let praxis = PraxisSchema::default();
        assert_eq!(praxis.schema_id(), "de.gesundheit.praxis.v1");
    }

    #[test]
    fn test_adresse_schema_id() {
        let adresse = AdresseSchema::default();
        assert_eq!(adresse.schema_id(), "de.gesundheit.adresse.v1");
    }

    #[test]
    fn test_adresse_default_land() {
        let adresse = AdresseSchema::default();
        assert_eq!(adresse.land, "DE");
    }

    #[test]
    fn test_praxis_default_booleans() {
        let praxis = PraxisSchema::default();
        assert!(!praxis.privatpatienten);
        assert!(!praxis.kassenpatienten);
    }

    #[test]
    fn test_practice_validation_missing() {
        let praxis = PraxisSchema::default();
        let result = praxis.validate();

        assert!(result.is_err());

        if let Err(crate::error::ValidationError::RequiredFieldsMissing(fields)) = result {
            assert!(fields.contains(&"name".to_string()));
            assert!(fields.contains(&"bezeichnung".to_string()));
            assert!(fields.contains(&"adresse.strasse".to_string()));
            assert!(fields.contains(&"adresse.plz".to_string()));
            assert!(fields.contains(&"adresse.ort".to_string()));
        }
    }

    #[test]
    fn test_practice_validation_ok() {
        let praxis = PraxisSchema {
            name: "Dr. Anna Schmidt".to_string(),
            bezeichnung: "Zahnärztin".to_string(),
            adresse: AdresseSchema {
                strasse: "Musterstraße".to_string(),
                hausnummer: Some("42".to_string()),
                plz: "12345".to_string(),
                ort: "Beispielstadt".to_string(),
                land: "DE".to_string(),
            },
            ..Default::default()
        };

        assert!(praxis.validate().is_ok());
    }

    #[test]
    fn test_json_deserialization() {
        let json = r#"{
            "name": "Dr. Müller",
            "bezeichnung": "Arzt",
            "adresse": {
                "strasse": "Hauptstraße",
                "plz": "12345",
                "ort": "Berlin"
            }
        }"#;

        let praxis: PraxisSchema = serde_json::from_str(json).unwrap();

        assert_eq!(praxis.name, "Dr. Müller");
        assert_eq!(praxis.bezeichnung, "Arzt");
        assert_eq!(praxis.adresse.land, "DE"); // Default
        assert!(praxis.validate().is_ok());
    }

    #[test]
    fn test_json_complete() {
        let json = r#"{
            "name": "Dr. Anna Schmidt",
            "bezeichnung": "Zahnärztin",
            "praxisname": "Praxis Schmidt",
            "adresse": {
                "strasse": "Musterstraße",
                "hausnummer": "42",
                "plz": "12345",
                "ort": "Beispielstadt",
                "land": "DE"
            },
            "telefon": "+49 123 9876543",
            "email": "info@praxis-schmidt.example",
            "website": "https://praxis-schmidt.example",
            "schwerpunkte": ["Zahnerhaltung", "Prophylaxe"],
            "therapieformen": ["Wurzelbehandlung", "Bleaching"],
            "qualifikationen": ["Zahnärztin", "Implantologie-Zertifikat"],
            "terminbuchung_url": "https://praxis-schmidt.example/termin",
            "oeffnungszeiten": "Nach Vereinbarung",
            "privatpatienten": true,
            "kassenpatienten": false,
            "sprachen": ["Deutsch"],
            "kurzbeschreibung": "Ganzheitliche Medizin in Beispielstadt"
        }"#;

        let praxis: PraxisSchema = serde_json::from_str(json).unwrap();

        assert_eq!(praxis.name, "Dr. Anna Schmidt");
        assert!(praxis.privatpatienten);
        assert!(!praxis.kassenpatienten);
        assert_eq!(praxis.schwerpunkte.len(), 2);
        assert!(praxis.validate().is_ok());
    }

    // ────────────────────────────────────────────────────────────────────────
    // NEW TESTS: FLATBUFFER SERIALIZATION
    // ────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_practice_serialization_minimal() {
        let praxis = PraxisSchema {
            name: "Test".to_string(),
            bezeichnung: "Arzt".to_string(),
            adresse: AdresseSchema {
                strasse: "Teststr.".to_string(),
                hausnummer: None,
                plz: "12345".to_string(),
                ort: "Berlin".to_string(),
                land: "DE".to_string(),
            },
            ..Default::default()
        };

        let bytes = praxis.to_bytes();

        // FlatBuffer has at least header + data
        assert!(!bytes.is_empty());
        assert!(bytes.len() > 50); // Minimum size for the data
    }

    #[test]
    fn test_practice_serialization_roundtrip() {
        let original = PraxisSchema {
            name: "Dr. Anna Schmidt".to_string(),
            bezeichnung: "Zahnärztin".to_string(),
            adresse: AdresseSchema {
                strasse: "Musterstraße".to_string(),
                hausnummer: Some("42".to_string()),
                plz: "12345".to_string(),
                ort: "Beispielstadt".to_string(),
                land: "DE".to_string(),
            },
            praxisname: Some("Praxis Schmidt".to_string()),
            telefon: Some("+49 123 9876543".to_string()),
            schwerpunkte: vec!["Zahnerhaltung".to_string()],
            privatpatienten: true,
            ..Default::default()
        };

        // Serialize
        let bytes = original.to_bytes();

        // Deserialize (Zero-Copy!)
        let praxis = flatbuffers::root::<FbPraxis>(&bytes).expect("Invalid FlatBuffer");

        // Compare - required fields return &str
        assert_eq!(praxis.name(), "Dr. Anna Schmidt");
        assert_eq!(praxis.bezeichnung(), "Zahnärztin");

        // Optional fields return Option<&str>
        assert_eq!(praxis.praxisname(), Some("Praxis Schmidt"));
        assert_eq!(praxis.telefon(), Some("+49 123 9876543"));
        assert!(praxis.privatpatienten());
        assert!(!praxis.kassenpatienten());

        // Check address - required, returns Address (not Option)
        let adresse = praxis.adresse();
        assert_eq!(adresse.strasse(), "Musterstraße");
        assert_eq!(adresse.hausnummer(), Some("42"));
        assert_eq!(adresse.plz(), "12345");
        assert_eq!(adresse.ort(), "Beispielstadt");
        assert_eq!(adresse.land(), "DE");

        // Check vectors
        let schwerpunkte = praxis.schwerpunkte().expect("Specializations missing");
        assert_eq!(schwerpunkte.len(), 1);
        assert_eq!(schwerpunkte.get(0), "Zahnerhaltung");
    }

    #[test]
    fn test_practice_serialization_all_vectors() {
        let praxis = PraxisSchema {
            name: "Test".to_string(),
            bezeichnung: "Test".to_string(),
            adresse: AdresseSchema {
                strasse: "Test".to_string(),
                hausnummer: None,
                plz: "12345".to_string(),
                ort: "Test".to_string(),
                land: "DE".to_string(),
            },
            schwerpunkte: vec!["A".to_string(), "B".to_string()],
            therapieformen: vec!["X".to_string(), "Y".to_string(), "Z".to_string()],
            qualifikationen: vec!["Q1".to_string()],
            sprachen: vec!["Deutsch".to_string(), "Englisch".to_string()],
            ..Default::default()
        };

        let bytes = praxis.to_bytes();
        let fb = flatbuffers::root::<FbPraxis>(&bytes).unwrap();

        assert_eq!(fb.schwerpunkte().unwrap().len(), 2);
        assert_eq!(fb.therapieformen().unwrap().len(), 3);
        assert_eq!(fb.qualifikationen().unwrap().len(), 1);
        assert_eq!(fb.sprachen().unwrap().len(), 2);
    }

    #[test]
    fn test_address_serialization() {
        let adresse = AdresseSchema {
            strasse: "Hauptstraße".to_string(),
            hausnummer: Some("42".to_string()),
            plz: "12345".to_string(),
            ort: "Teststadt".to_string(),
            land: "DE".to_string(),
        };

        let bytes = adresse.to_bytes();

        // Deserialize address
        let fb = flatbuffers::root::<FbAdresse>(&bytes).expect("Invalid FlatBuffer");

        // required fields: direct &str
        assert_eq!(fb.strasse(), "Hauptstraße");
        assert_eq!(fb.plz(), "12345");
        assert_eq!(fb.ort(), "Teststadt");

        // optional fields: Option<&str>
        assert_eq!(fb.hausnummer(), Some("42"));
        assert_eq!(fb.land(), "DE");
    }
}