oca-file 2.0.0

Rust implementation of OCAFile
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
use crate::ocafile::{Pair, Rule, error::InstructionError, instructions::helpers};
use indexmap::IndexMap;
use log::{debug, info};
use oca_ast::ast::{
    CaptureContent, Command, CommandType, NestedAttrType, NestedValue, ObjectKind, OverlayContent,
    RefValue,
};
use overlay_file::{OverlayDef, overlay_registry::OverlayRegistry};
use said::SelfAddressingIdentifier;

pub struct AddInstruction {}

pub fn resolve_overlay_def<'a>(
    registry: &'a dyn OverlayRegistry,
    name: &str,
) -> Result<&'a OverlayDef, InstructionError> {
    match registry.get_overlay(name) {
        Ok(overlay_def) => Ok(overlay_def),
        Err(e) => Err(InstructionError::UnknownOverlay(format!(
            "Overlay '{}' not found in registry: {}",
            name, e
        ))),
    }
}

pub fn parse_overlay_body(
    pair: Pair,
    overlay_def: OverlayDef,
) -> Result<IndexMap<String, NestedValue>, InstructionError> {
    let mut lines: Vec<(usize, Pair)> = Vec::new();

    // First pass: collect all lines with their indentation levels
    for line in pair.into_inner() {
        if line.as_rule() != Rule::overlay_line {
            continue;
        }

        let mut indent_level = 0;
        let mut content = None;

        for item in line.into_inner() {
            match item.as_rule() {
                Rule::indent => {
                    indent_level = item.as_str().len();
                }
                Rule::kv_pair | Rule::block_header => {
                    content = Some(item);
                }
                _ => {}
            }
        }

        if let Some(content) = content {
            lines.push((indent_level, content));
        }
    }

    // Second pass: group lines into blocks based on indentation
    parse_lines_with_indentation(&lines, 0, overlay_def)
}

fn parse_lines_with_indentation(
    lines: &[(usize, Pair)],
    start_idx: usize,
    overlay_def: OverlayDef,
) -> Result<IndexMap<String, NestedValue>, InstructionError> {
    let mut map = IndexMap::new();
    let mut i = start_idx;

    if lines.is_empty() {
        return Ok(map);
    }

    let base_indent = lines[start_idx].0;

    while i < lines.len() {
        let (indent, ref content) = lines[i];

        // If we've dedented, we're done with this block
        if indent < base_indent {
            break;
        }

        // Skip lines that are more indented (they belong to a sub-block)
        if indent > base_indent {
            i += 1;
            continue;
        }

        debug!("Content: {:?}", content);
        match content.as_rule() {
            Rule::kv_pair => {
                let (key, value) = parse_kv_pair(content.clone())?;
                map.insert(key, value);
                i += 1;
            }
            Rule::block_header => {
                let block_key = extract_block_key(content)?;

                // Find all lines that belong to this block (more indented)
                let block_start = i + 1;
                let mut block_end = block_start;

                if block_start < lines.len() {
                    let expected_indent = lines[block_start].0;

                    while block_end < lines.len() && lines[block_end].0 >= expected_indent {
                        block_end += 1;
                    }

                    // Recursively parse the block content
                    let nested_content =
                        parse_lines_with_indentation(lines, block_start, overlay_def.clone())?;

                    map.insert(block_key, NestedValue::Object(nested_content));
                }

                i = block_end;
            }
            _ => {
                i += 1;
            }
        }
    }

    Ok(map)
}

fn parse_kv_pair(pair: Pair) -> Result<(String, NestedValue), InstructionError> {
    let mut inner = pair.into_inner();

    debug!("Inner content: {:?}", inner);
    let key = inner
        .find(|p| p.as_rule() == Rule::attr_key)
        .ok_or_else(|| InstructionError::Parser("Missing key in kv_pair".to_string()))?
        .as_str()
        .to_string()
        .as_str()
        .trim_matches('"')
        .to_string();

    let value_pair = inner
        .find(|p| p.as_rule() == Rule::key_value)
        .ok_or_else(|| InstructionError::Parser("Missing value in kv_pair".to_string()))?;

    let value = parse_key_value(value_pair)?;

    Ok((key, value))
}

fn extract_block_key(pair: &Pair) -> Result<String, InstructionError> {
    pair.clone()
        .into_inner()
        .find(|p| p.as_rule() == Rule::attr_key)
        .map(|p| p.as_str().trim_matches('"').to_string())
        .ok_or_else(|| InstructionError::Parser("Missing key in block_header".to_string()))
}

fn parse_key_value(pair: Pair) -> Result<NestedValue, InstructionError> {
    let inner = pair
        .into_inner()
        .next()
        .ok_or_else(|| InstructionError::Parser("Empty key_value".to_string()))?;

    match inner.as_rule() {
        Rule::string => {
            let s = inner
                .into_inner()
                .next()
                .ok_or_else(|| InstructionError::Parser("Invalid string".to_string()))?
                .as_str()
                .to_string();
            // Clean the string value by removing surrounding quotes
            let cleaned = s.trim_matches('"').to_string();
            Ok(NestedValue::Value(cleaned))
        }
        Rule::array => {
            let values = inner
                .into_inner()
                .map(|v| parse_key_value(v))
                .collect::<Result<Vec<_>, _>>()?;
            Ok(NestedValue::Array(values))
        }
        Rule::said => {
            let said = inner
                .as_str()
                .parse::<SelfAddressingIdentifier>()
                .map_err(|e| InstructionError::Parser(format!("Invalid SAID: {}", e)))?;
            Ok(NestedValue::Reference(RefValue::Said(said)))
        }
        Rule::alias => Ok(NestedValue::Reference(RefValue::Name(
            inner.as_str().to_string(),
        ))),
        _ => {
            // Fallback for plain text - also clean quotes if present
            let s = inner.as_str().trim_matches('"').to_string();
            Ok(NestedValue::Value(s))
        }
    }
}

impl AddInstruction {
    pub(crate) fn from_record(
        record: Pair,
        _index: usize,
        registry: &dyn OverlayRegistry,
    ) -> Result<Command, InstructionError> {
        let mut object_kind = None;
        let kind = CommandType::Add;
        let mut content = OverlayContent {
            properties: None,
            overlay_def: OverlayDef::default(),
        };

        debug!("Parsing add instruction from the record: {:?}", record);
        for object in record.into_inner() {
            match object.as_rule() {
                Rule::overlay => {
                    debug!("Parsing overlay block: {:?}", object);

                    for overlay in object.into_inner() {
                        match overlay.as_rule() {
                            Rule::overlay_header => {
                                for header in overlay.into_inner() {
                                    match header.as_rule() {
                                        Rule::overlay_name => {
                                            debug!("Parsing overlay name: {:?}", header);
                                            let name = header.as_str();
                                            match resolve_overlay_def(registry, name) {
                                                Ok(od) => {
                                                    content.overlay_def = od.clone();
                                                }
                                                Err(e) => {
                                                    return Err(InstructionError::UnknownOverlay(
                                                        e.to_string(),
                                                    ));
                                                }
                                            }
                                        }
                                        _ => {
                                            return Err(InstructionError::UnexpectedToken(
                                                format!(
                                                    "Overlay: unexpected token {:?}",
                                                    header.as_rule()
                                                ),
                                            ));
                                        }
                                    }
                                }
                            }
                            Rule::overlay_body => {
                                debug!("Parsing overlay body: {:?}", overlay);
                                content.properties =
                                    Some(parse_overlay_body(overlay, content.overlay_def.clone())?);
                            }
                            _ => {
                                return Err(InstructionError::UnexpectedToken(format!(
                                    "Overlay: unexpected token {:?}",
                                    overlay.as_rule()
                                )));
                            }
                        }
                    }
                    object_kind = Some(ObjectKind::Overlay(content.clone()));
                }
                Rule::capture_base => {
                    let mut attributes: IndexMap<String, NestedAttrType> = IndexMap::new();
                    for attr_pairs in object.into_inner() {
                        match attr_pairs.as_rule() {
                            Rule::attr_pairs => {
                                debug!("Attribute pairs: {:?}", attr_pairs);
                                for attr in attr_pairs.into_inner() {
                                    debug!("Parsing attribute pair {:?}", attr);
                                    let (key, value) = helpers::extract_attribute(attr)?;
                                    info!("Parsed attribute: {:?} = {:?}", key, value);

                                    attributes.insert(key, value);
                                }
                            }
                            _ => {
                                return Err(InstructionError::UnexpectedToken(format!(
                                    "Invalid attributes in ATTRIBUTE instruction {:?}",
                                    attr_pairs.as_rule()
                                )));
                            }
                        }
                    }
                    debug!("Attributes: {:?}", attributes);
                    object_kind = Some(ObjectKind::CaptureBase(CaptureContent {
                        attributes: Some(attributes),
                    }));
                }
                Rule::comment => continue,
                _ => {
                    return Err(InstructionError::UnexpectedToken(format!(
                        "Overlay: unexpected token {:?}",
                        object.as_rule()
                    )));
                }
            };
        }

        Ok(Command {
            kind,
            object_kind: object_kind.unwrap(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ocafile::OCAfileParser;
    use overlay_file::overlay_registry::OverlayLocalRegistry;
    use pest::Parser;

    #[test]
    fn test_add_attribute_instruction() {
        // test vector with example instruction and boolean if they should be valid or not
        let instructions = vec![
            ("ADD ATTRIBUTE documentNumber = [refn:dokument]", true),
            ("ADD ATTRIBUTE documentNumber=[[[refn:dokument]]]", true),
            (
                "ADD ATTRIBUTE documentNumber=[ refs:ENyO7FUBx7oILUYt8FwmLaDVmvOZGETXWHICultMSEpW ]",
                true,
            ),
            (
                "ADD ATTRIBUTE documentNumber=[refn:klient, refs:ENyO7FUBx7oILUYt8FwmLaDVmvOZGETXWHICultMSEpW]",
                false,
            ),
            (
                "ADD ATTRIBUTE documentNumber=snieg documentType=refs:ENyO7FUBx7oILUYt8FwmLaDVmvOZGETXWHICultMSEpW",
                false,
            ),
            (
                "ADD ATTRIBUTE documentNumber=refn:snieg documentType=refs:ENyO7FUBx7oILUYt8FwmLaDVmvOZGETXWHICultMSEpW",
                true,
            ),
            (
                "ADD ATTRIBUTE documentNumber=Text documentType=Numeric",
                true,
            ),
            (
                "ADD ATTRIBUTE documentNumber=Text documentType=Numeric name=Text list=[Numeric]",
                true,
            ),
            ("ADD ATTRIBUTE name=Text", false),
            ("ADD ATTR name=Text", false),
            ("ADD attribute name=Text", true),
            ("add attribute name=Text", true),
            ("add attribute name=Random", false),
        ];
        let _ = env_logger::builder().is_test(true).try_init();

        // loop over instructions to check if the are meeting the requirements
        for (instruction, is_valid) in instructions {
            debug!("Instruction: {:?}", instruction);
            let parsed_instruction = OCAfileParser::parse(Rule::add, instruction);
            debug!("Parsed instruction: {:?}", parsed_instruction);

            match parsed_instruction {
                Ok(mut parsed_instruction) => {
                    let instruction = parsed_instruction.next();
                    assert!(instruction.is_some());
                    match instruction {
                        Some(instruction) => {
                            let registry =
                                OverlayLocalRegistry::from_dir("../overlay-file/core_overlays")
                                    .unwrap();
                            let instruction =
                                AddInstruction::from_record(instruction, 0, &registry).unwrap();

                            assert_eq!(instruction.kind, CommandType::Add);
                            match instruction.object_kind {
                                ObjectKind::CaptureBase(content) => {
                                    if content.attributes.is_some() {
                                        assert!(!content.attributes.unwrap().is_empty());
                                    }
                                }
                                _ => {
                                    assert!(!is_valid, "Instruction is not valid");
                                }
                            }
                        }
                        None => {
                            assert!(!is_valid, "Instruction is not valid");
                        }
                    }
                }
                Err(e) => {
                    println!("Error: {:?}", e);
                    assert!(!is_valid, "Instruction should be invalid");
                }
            }
        }
    }

    #[test]
    fn test_add_non_existing_overlay() {
        let _ = env_logger::builder().is_test(true).try_init();

        let instructions = vec![
            "ADD OVERLAY NONEXISTENT\n  language=\"en\"",
            "ADD OVERLAY UNKNOWN_OVERLAY\n  name=\"test\"",
            "ADD OVERLAY InvalidOverlay\n  description=\"test\"",
        ];

        for instruction in instructions {
            debug!(
                "Testing non-existing overlay instruction: {:?}",
                instruction
            );
            let parsed_instruction = OCAfileParser::parse(Rule::add, instruction);
            debug!("Parsed instruction: {:?}", parsed_instruction);

            match parsed_instruction {
                Ok(mut parsed_instruction) => {
                    let instruction = parsed_instruction.next();
                    assert!(instruction.is_some());

                    if let Some(instruction) = instruction {
                        let registry =
                            OverlayLocalRegistry::from_dir("../overlay-file/core_overlays")
                                .unwrap();
                        let result = AddInstruction::from_record(instruction, 0, &registry);

                        assert!(result.is_err(), "Expected error for non-existing overlay");

                        match result.unwrap_err() {
                            InstructionError::UnknownOverlay(msg) => {
                                debug!("Correctly caught UnknownOverlay error: {}", msg);
                                assert!(
                                    msg.contains("not found"),
                                    "Expected 'not found' in error message, got: {}",
                                    msg
                                );
                            }
                            other => {
                                panic!("Unexpected error type: {:?}", other);
                            }
                        }
                    }
                }
                Err(e) => {
                    panic!(
                        "Parsing should succeed, but overlay resolution should fail. Got parse error: {:?}",
                        e
                    );
                }
            }
        }
    }

    #[test]
    fn test_add_overlay_instructions() {
        let instructions = vec![
            (
                "ADD OVERLAY LABEL\n  language=\"pl\"\n  attributes\n gender=\"Opcja\"",
                true,
            ),
            (
                "ADD OVERLAY ENTRY_CODE\n  attribute_entry_codes\n    gender=[\"o1\",\"o2\"]",
                true,
            ),
            (
                "ADD OVERLAY ENTRY\n  attribute_entries\n    gender=\"refs:ECfBoOwdcHhQfNtWA5qTKOo9egoxHKXxby6R8Jujpk-o\"",
                true,
            ),
            (
                "ADD OVERLAY FORMAT\n attribute_formats\n    name = \"^\\d+$\"",
                true,
            ),
            (
                "ADD OVERLAY CHARACTER_ENCODING\n attribute_character_encodings\n    name=\"utf-16le\"",
                true,
            ),
            (
                "ADD OVERLAY META\n name=\"test\"\n description=\"desc\"",
                true,
            ),
            (
                "ADD OVERLAY SENSITIVE\n  attributes=[\"gender\", \"name\"]",
                true,
            ),
            ("ADD OVERLAY CODE\n gender=[\"o1\",\"o2\", \"o3\"]", false),
            (
                "ADD OVERLAY SENSITIVE\n  attributes=[\"gender\" \"name\"]",
                false,
            ),
        ];

        let _ = env_logger::builder().is_test(true).try_init();

        for (instruction, is_valid) in instructions {
            let parsed_instruction = OCAfileParser::parse(Rule::add, instruction);

            match parsed_instruction {
                Ok(mut parsed_instruction) => {
                    let instruction = parsed_instruction.next();
                    assert!(instruction.is_some());
                    match instruction {
                        Some(instruction) => {
                            let registry =
                                OverlayLocalRegistry::from_dir("../overlay-file/core_overlays")
                                    .unwrap();
                            let result = AddInstruction::from_record(instruction, 0, &registry);

                            if is_valid {
                                let instruction = result.unwrap();
                                debug!("Parsed instruction: {:?}", instruction);

                                assert_eq!(instruction.kind, CommandType::Add);
                                match instruction.object_kind {
                                    ObjectKind::Overlay(content) => {
                                        let full_name =
                                            content.overlay_def.get_full_name().to_lowercase();
                                        assert!(
                                            !full_name.is_empty(),
                                            "Overlay name should not be empty"
                                        );
                                        assert_eq!(
                                            content.overlay_def.version, "2.0.0",
                                            "Overlay version should be 2.0.0"
                                        );
                                        let properties = content
                                            .properties
                                            .expect("Overlay properties should be present");
                                        debug!("Properties: {:?}", properties);
                                        match full_name.as_str() {
                                            "label/2.0.0" => {
                                                assert!(
                                                    properties.contains_key("language"),
                                                    "Label overlay should include language"
                                                );
                                                assert!(
                                                    properties.contains_key("attributes"),
                                                    "Label overlay should include attributes"
                                                );
                                            }
                                            "entry_code/2.0.0" => {
                                                assert!(
                                                    properties
                                                        .contains_key("attribute_entry_codes"),
                                                    "Entry Code overlay should include attribute_entry_codes"
                                                );
                                            }
                                            "format/2.0.0" => {
                                                assert!(
                                                    properties.contains_key("attribute_formats"),
                                                    "Format overlay should include attribute_formats"
                                                );
                                            }
                                            "character_encoding/2.0.0" => {
                                                assert!(
                                                    properties.contains_key(
                                                        "attribute_character_encodings"
                                                    ),
                                                    "Character Encoding overlay should include attribute_character_encodings"
                                                );
                                            }
                                            "meta/2.0.0" => {
                                                assert!(
                                                    properties.contains_key("description"),
                                                    "Meta overlay should include description"
                                                );
                                            }
                                            "sensitive/2.0.0" => {
                                                let attrs = properties.get("attributes").expect(
                                                    "Sensitive overlay should include attributes",
                                                );
                                                match attrs {
                                                    NestedValue::Array(values) => {
                                                        assert_eq!(values.len(), 2);
                                                    }
                                                    _ => panic!(
                                                        "Sensitive overlay attributes should be array"
                                                    ),
                                                }
                                            }
                                            _ => {}
                                        }
                                    }
                                    ObjectKind::CaptureBase(_) => todo!(),
                                    ObjectKind::OCABundle(_) => todo!(),
                                }
                            } else {
                                assert!(result.is_err());
                                match result.unwrap_err() {
                                    InstructionError::UnknownOverlay(_) => {}
                                    other => {
                                        panic!("Expected UnknownOverlay error, got {:?}", other)
                                    }
                                }
                            }
                        }
                        None => {
                            assert!(!is_valid, "Instruction is not valid");
                        }
                    }
                }
                Err(e) => {
                    assert!(!is_valid, "Instruction should be invalid");
                    println!("Error: {:?}", e);
                }
            }
        }
    }

    #[test]
    fn test_add_overlay_with_multiple_nested_blocks() {
        let instructions = vec![(
            r#"ADD OVERLAY META
  language="en"
  name="Test Schema"
  description="A test schema with multiple nested blocks"
  credential_help_text
    field1="Help for field 1"
    field2="Help for field 2"
  credential_support_text
    field1="Support info for field 1"
    field2="Support info for field 2"
  credential_hint_text
    field1
        label="Support info for field 1"
        title="HINT"
    field2
        label="Support info for field 2"
        title="HINT"
"#,
            true,
        )];

        let _ = env_logger::builder().is_test(true).try_init();

        for (instruction, is_valid) in instructions {
            debug!(
                "Testing multiple nested blocks instruction: {:?}",
                instruction
            );
            let parsed_instruction = OCAfileParser::parse(Rule::add, instruction);
            debug!("Parsed instruction: {:?}", parsed_instruction);

            match parsed_instruction {
                Ok(mut parsed_instruction) => {
                    let instruction = parsed_instruction.next();
                    assert!(instruction.is_some(), "Instruction should be parsed");

                    match instruction {
                        Some(instruction) => {
                            let registry =
                                OverlayLocalRegistry::from_dir("../overlay-file/core_overlays")
                                    .unwrap();
                            let result = AddInstruction::from_record(instruction, 0, &registry);

                            match result {
                                Ok(command) => {
                                    assert_eq!(command.kind, CommandType::Add);
                                    match command.object_kind {
                                        ObjectKind::Overlay(content) => {
                                            assert!(is_valid, "Instruction should be valid");

                                            // Verify properties exist
                                            assert!(
                                                content.properties.is_some(),
                                                "Properties should be present"
                                            );

                                            let properties = content.properties.unwrap();
                                            debug!("Parsed properties: {:?}", properties);

                                            // Count nested blocks (objects)
                                            let nested_block_count = properties
                                                .values()
                                                .filter(|v| matches!(v, NestedValue::Object(_)))
                                                .count();

                                            assert!(
                                                nested_block_count >= 2,
                                                "Should have at least 2 nested blocks, found {}",
                                                nested_block_count
                                            );

                                            // Verify each nested block has content
                                            for (key, value) in properties.iter() {
                                                if let NestedValue::Object(nested_map) = value {
                                                    assert!(
                                                        !nested_map.is_empty(),
                                                        "Nested block '{}' should not be empty",
                                                        key
                                                    );
                                                    debug!(
                                                        "Nested block '{}' contains {} items",
                                                        key,
                                                        nested_map.len()
                                                    );
                                                }
                                            }

                                            println!(
                                                "Successfully parsed overlay with {} nested blocks",
                                                nested_block_count
                                            );
                                        }
                                        ObjectKind::CaptureBase(_) => {
                                            panic!("Expected Overlay, got CaptureBase");
                                        }
                                        ObjectKind::OCABundle(_) => {
                                            panic!("Expected Overlay, got OCABundle");
                                        }
                                    }
                                }
                                Err(e) => {
                                    if is_valid {
                                        panic!("Expected valid instruction but got error: {:?}", e);
                                    } else {
                                        debug!(
                                            "Correctly caught error for invalid instruction: {:?}",
                                            e
                                        );
                                    }
                                }
                            }
                        }
                        None => {
                            assert!(!is_valid, "Instruction should be invalid");
                        }
                    }
                }
                Err(e) => {
                    if is_valid {
                        panic!("Parsing should succeed but got error: {:?}", e);
                    } else {
                        debug!("Correctly failed to parse invalid instruction: {:?}", e);
                    }
                }
            }
        }
    }

    #[test]
    fn test_add_overlay_entry_with_quoted_refs() {
        let _ = env_logger::builder().is_test(true).try_init();
        let instruction = r#"ADD OVERLAY ENTRY
  language="fr"
  attribute_entries
    issuingState=refs:ECfBoOwdcHhQfNtWA5qTKOo9egoxHKXxby6R8Jujpk-o
    issuingStateCode='refs:EnmO60xL2IsIv-_AC2PgLdJtzqsfuNqa8BihsiNWgz5o'
    nationality="refs:EAr0uvi1743P2VXXqd08a-yX8K_aejHCkdjaW8lWZ_xw"
"#;

        let parsed_instruction = OCAfileParser::parse(Rule::add, instruction).unwrap();
        let instruction = parsed_instruction.into_iter().next().unwrap();
        let registry = OverlayLocalRegistry::from_dir("../overlay-file/core_overlays").unwrap();
        let command = AddInstruction::from_record(instruction, 0, &registry).unwrap();

        match command.object_kind {
            ObjectKind::Overlay(content) => {
                let properties = content.properties.expect("Expected overlay properties");
                let entries = properties
                    .get("attribute_entries")
                    .expect("Expected attribute_entries");
                match entries {
                    NestedValue::Object(map) => {
                        for key in ["issuingState", "issuingStateCode", "nationality"] {
                            match map.get(key) {
                                Some(NestedValue::Reference(RefValue::Said(_))) => {}
                                other => {
                                    panic!("Expected Reference(Said) for {}, got {:?}", key, other)
                                }
                            }
                        }
                    }
                    _ => panic!("Expected attribute_entries to be an object"),
                }
            }
            _ => panic!("Expected Overlay command"),
        }
    }

    #[test]
    fn test_add_with_quoted_keys_and_values() {
        let instructions = vec![
            // Test 1: Simple quoted key and value
            (
                r#"ADD ATTRIBUTE "person.name"=Text"#,
                true,
                vec![("person.name", "Text")],
            ),
            // Test 2: Multiple quoted keys and values
            (
                r#"ADD ATTRIBUTE "first.name"=Text "last.name"=Text"#,
                true,
                vec![("first.name", "Text"), ("last.name", "Text")],
            ),
            // Test 3: Quoted key with special characters
            (
                r#"ADD ATTRIBUTE "person.email@domain"=Text"#,
                true,
                vec![("person.email@domain", "Text")],
            ),
            // Test 4: Quoted key with spaces in value
            (
                r#"ADD ATTRIBUTE "full name"=Text"#,
                true,
                vec![("full name", "Text")],
            ),
            // Test 5: Mixed quoted and unquoted (unquoted should still work)
            (
                r#"ADD ATTRIBUTE name=Text "person.age"=Numeric"#,
                true,
                vec![("name", "Text"), ("person.age", "Numeric")],
            ),
            // Test 6: Overlay with quoted properties
            (
                r#"ADD OVERLAY LABEL
  language="en"
  attributes:
    "person.name"="Full Name"
    "person.age"="Age""#,
                true,
                vec![],
            ),
            // Test 7: Nested object with quoted keys
            (
                r#"ADD OVERLAY META
  language="en"
  "credential_help_text"
    "field.one"="Help text for field one"
    "field.two"="Help text for field two""#,
                true,
                vec![],
            ),
            // Test 9: Complex nested structure with quotes
            (
                r#"ADD OVERLAY META
  language="en"
  name="Test Schema"
  "credential.hint.text"
    "user.email"
        label="Email address hint"
        title="Email Hint"
    "user.phone"
        label="Phone number hint"
        title="Phone Hint""#,
                true,
                vec![],
            ),
            // Test 10: Quoted keys with dots and underscores
            (
                r#"ADD ATTRIBUTE "experiment.range.original_values"=Text "test_field.sub.value"=Numeric"#,
                true,
                vec![
                    ("experiment.range.original_values", "Text"),
                    ("test_field.sub.value", "Numeric"),
                ],
            ),
        ];

        let _ = env_logger::builder().is_test(true).try_init();

        for (idx, (instruction, is_valid, expected_pairs)) in instructions.into_iter().enumerate() {
            debug!("Test case {}: {:?}", idx + 1, instruction);
            let parsed_instruction = OCAfileParser::parse(Rule::add, instruction);
            debug!("Parsed instruction: {:?}", parsed_instruction);

            match parsed_instruction {
                Ok(mut parsed_instruction) => {
                    let instruction = parsed_instruction.next();
                    assert!(
                        instruction.is_some(),
                        "Test case {}: Instruction should be parsed",
                        idx + 1
                    );

                    match instruction {
                        Some(instruction) => {
                            let registry =
                                OverlayLocalRegistry::from_dir("../overlay-file/core_overlays")
                                    .unwrap();
                            let result = AddInstruction::from_record(instruction, 0, &registry);

                            if is_valid {
                                let command = result.unwrap_or_else(|e| {
                                    panic!("Test case {}: Expected valid instruction but got error: {:?}", idx + 1, e)
                                });

                                assert_eq!(
                                    command.kind,
                                    CommandType::Add,
                                    "Test case {}: Should be Add command",
                                    idx + 1
                                );

                                match command.object_kind {
                                    ObjectKind::CaptureBase(content) => {
                                        if let Some(attributes) = content.attributes {
                                            debug!(
                                                "Test case {}: Parsed attributes: {:?}",
                                                idx + 1,
                                                attributes
                                            );

                                            // Verify that keys don't have quotes
                                            for (key, _) in attributes.iter() {
                                                assert!(
                                                    !key.starts_with('"') && !key.ends_with('"'),
                                                    "Test case {}: Key '{}' should not contain quotes",
                                                    idx + 1,
                                                    key
                                                );
                                            }

                                            // Verify expected key-value pairs for attribute tests
                                            if !expected_pairs.is_empty() {
                                                for (expected_key, expected_value) in
                                                    expected_pairs.iter()
                                                {
                                                    assert!(
                                                        attributes.contains_key(*expected_key),
                                                        "Test case {}: Should contain key '{}'",
                                                        idx + 1,
                                                        expected_key
                                                    );

                                                    // For simple type attributes, verify the value
                                                    if !expected_value.is_empty()
                                                        && let Some(attr_type) =
                                                            attributes.get(*expected_key)
                                                    {
                                                        match attr_type {
                                                            NestedAttrType::Value(v) => {
                                                                assert_eq!(
                                                                    format!("{:?}", v),
                                                                    *expected_value,
                                                                    "Test case {}: Value for key '{}' should be '{}'",
                                                                    idx + 1,
                                                                    expected_key,
                                                                    expected_value
                                                                );
                                                            }
                                                            _ => {
                                                                // For complex types, just verify key exists
                                                                debug!(
                                                                    "Test case {}: Complex type for key '{}'",
                                                                    idx + 1,
                                                                    expected_key
                                                                );
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    ObjectKind::Overlay(content) => {
                                        debug!(
                                            "Test case {}: Parsed overlay: {:?}",
                                            idx + 1,
                                            content.overlay_def.get_full_name()
                                        );

                                        if let Some(properties) = content.properties {
                                            debug!(
                                                "Test case {}: Overlay properties: {:?}",
                                                idx + 1,
                                                properties
                                            );

                                            // Verify that property keys don't have quotes
                                            for (key, value) in properties.iter() {
                                                assert!(
                                                    !key.starts_with('"') && !key.ends_with('"'),
                                                    "Test case {}: Property key '{}' should not contain quotes",
                                                    idx + 1,
                                                    key
                                                );

                                                // Verify nested values don't have quotes
                                                match value {
                                                    NestedValue::Value(v) => {
                                                        assert!(
                                                            !v.starts_with('"')
                                                                && !v.ends_with('"'),
                                                            "Test case {}: Value '{}' should not contain quotes",
                                                            idx + 1,
                                                            v
                                                        );
                                                    }
                                                    NestedValue::Object(nested_map) => {
                                                        for (nested_key, nested_value) in
                                                            nested_map.iter()
                                                        {
                                                            assert!(
                                                                !nested_key.starts_with('"')
                                                                    && !nested_key.ends_with('"'),
                                                                "Test case {}: Nested key '{}' should not contain quotes",
                                                                idx + 1,
                                                                nested_key
                                                            );

                                                            if let NestedValue::Value(v) =
                                                                nested_value
                                                            {
                                                                assert!(
                                                                    !v.starts_with('"')
                                                                        && !v.ends_with('"'),
                                                                    "Test case {}: Nested value '{}' should not contain quotes",
                                                                    idx + 1,
                                                                    v
                                                                );
                                                            }
                                                        }
                                                    }
                                                    NestedValue::Array(arr) => {
                                                        for item in arr.iter() {
                                                            if let NestedValue::Value(v) = item {
                                                                assert!(
                                                                    !v.starts_with('"')
                                                                        && !v.ends_with('"'),
                                                                    "Test case {}: Array value '{}' should not contain quotes",
                                                                    idx + 1,
                                                                    v
                                                                );
                                                            }
                                                        }
                                                    }
                                                    _ => {}
                                                }
                                            }
                                        }
                                    }
                                    ObjectKind::OCABundle(_) => {
                                        panic!("Test case {}: Unexpected OCABundle", idx + 1);
                                    }
                                }

                                println!("✓ Test case {} passed", idx + 1);
                            } else {
                                assert!(
                                    result.is_err(),
                                    "Test case {}: Expected error but got success",
                                    idx + 1
                                );
                                println!("✓ Test case {} correctly failed", idx + 1);
                            }
                        }
                        None => {
                            assert!(
                                !is_valid,
                                "Test case {}: Instruction should be invalid",
                                idx + 1
                            );
                        }
                    }
                }
                Err(e) => {
                    if is_valid {
                        panic!(
                            "Test case {}: Parsing should succeed but got error: {:?}",
                            idx + 1,
                            e
                        );
                    } else {
                        debug!("Test case {}: Correctly failed to parse: {:?}", idx + 1, e);
                        println!("✓ Test case {} correctly failed at parse stage", idx + 1);
                    }
                }
            }
        }
    }
}