ucp-schema 1.3.0

Runtime resolution of UCP schema annotations
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
//! Schema resolution - transforms UCP annotated schemas into standard JSON Schema.

use serde_json::{Map, Value};

use crate::error::ResolveError;
use crate::types::{
    is_valid_schema_transition, json_type_name, Direction, ResolveOptions, SchemaTransitionInfo,
    Visibility, UCP_ANNOTATIONS,
};

/// Resolve a schema for a specific direction and operation.
///
/// Returns a standard JSON Schema with UCP annotations removed.
/// When `options.strict` is true, sets `additionalProperties: false`
/// on all object schemas to reject unknown fields. Default is false
/// to respect UCP's extensibility model.
///
/// # Errors
///
/// Returns `ResolveError` if the schema contains invalid annotations.
pub fn resolve(schema: &Value, options: &ResolveOptions) -> Result<Value, ResolveError> {
    let mut resolved = resolve_value(schema, options, "")?;

    if options.strict {
        close_additional_properties(&mut resolved);
    }

    Ok(resolved)
}

/// Recursively close object schemas to reject unknown properties.
///
/// For simple object schemas: sets `additionalProperties: false`
/// For schemas with composition (allOf/anyOf/oneOf): sets `unevaluatedProperties: false`
///
/// The distinction matters because `additionalProperties` is evaluated per-schema,
/// while `unevaluatedProperties` (JSON Schema 2020-12) looks across all subschemas.
/// This allows $ref inheritance patterns to work correctly in strict mode.
fn close_additional_properties(value: &mut Value) {
    close_additional_properties_inner(value, false);
}

/// Inner implementation with context tracking.
///
/// `in_composition_branch` is true when processing direct children of allOf/anyOf/oneOf.
/// We skip setting additionalProperties on these because each branch is validated
/// independently and doesn't see properties from sibling branches.
fn close_additional_properties_inner(value: &mut Value, in_composition_branch: bool) {
    if let Value::Object(map) = value {
        // Check if this schema uses composition keywords
        let has_composition =
            map.contains_key("allOf") || map.contains_key("anyOf") || map.contains_key("oneOf");

        // Check if this is an object schema (has "type": "object" or has "properties")
        let is_object_schema = map
            .get("type")
            .and_then(|t| t.as_str())
            .map(|t| t == "object")
            .unwrap_or(false)
            || map.contains_key("properties");

        // Close the schema if we're not inside a composition branch
        if !in_composition_branch && (is_object_schema || has_composition) {
            if has_composition {
                // Use unevaluatedProperties for composition - it looks across all subschemas
                // so $ref inheritance works correctly
                match map.get("unevaluatedProperties") {
                    None => {
                        map.insert("unevaluatedProperties".to_string(), Value::Bool(false));
                    }
                    Some(Value::Bool(true)) => {
                        map.insert("unevaluatedProperties".to_string(), Value::Bool(false));
                    }
                    _ => {}
                }
            } else {
                // Simple object schema - use additionalProperties
                match map.get("additionalProperties") {
                    None => {
                        map.insert("additionalProperties".to_string(), Value::Bool(false));
                    }
                    Some(Value::Bool(true)) => {
                        map.insert("additionalProperties".to_string(), Value::Bool(false));
                    }
                    _ => {}
                }
            }
        }

        // Recurse into all values
        for (key, child) in map.iter_mut() {
            match key.as_str() {
                "properties" => {
                    // Recurse into each property definition
                    if let Value::Object(props) = child {
                        for prop_value in props.values_mut() {
                            close_additional_properties_inner(prop_value, false);
                        }
                    }
                }
                "items" | "additionalProperties" | "unevaluatedProperties" => {
                    // Schema values - recurse
                    close_additional_properties_inner(child, false);
                }
                "$defs" | "definitions" => {
                    // Definitions - recurse into each
                    if let Value::Object(defs) = child {
                        for def_value in defs.values_mut() {
                            close_additional_properties_inner(def_value, false);
                        }
                    }
                }
                "allOf" | "anyOf" | "oneOf" => {
                    // Composition branches - recurse but mark as in_composition
                    // so we don't set additionalProperties on them directly
                    if let Value::Array(arr) = child {
                        for item in arr {
                            close_additional_properties_inner(item, true);
                        }
                    }
                }
                _ => {}
            }
        }
    }
}

/// Get visibility for a single property.
///
/// Looks up the appropriate annotation (`ucp_request` or `ucp_response`) and
/// determines the visibility for the given operation.
///
/// # Errors
///
/// Returns `ResolveError` if the annotation has invalid type or unknown visibility value.
pub fn get_visibility(
    prop: &Value,
    direction: Direction,
    operation: &str,
    path: &str,
) -> Result<(Visibility, Option<SchemaTransitionInfo>), ResolveError> {
    let key = direction.annotation_key();
    let Some(annotation) = prop.get(key) else {
        return Ok((Visibility::Include, None));
    };
    get_visibility_from_annotation(annotation, operation, path)
}

/// Parse visibility (and optional transition info) from a raw annotation value.
///
/// Shared between `get_visibility` (which extracts annotation by direction key)
/// and `inject_annotations` (which already has the annotation from allOf propagation).
fn get_visibility_from_annotation(
    annotation: &Value,
    operation: &str,
    path: &str,
) -> Result<(Visibility, Option<SchemaTransitionInfo>), ResolveError> {
    match annotation {
        // Shorthand: "ucp_request": "omit" - applies to all operations
        Value::String(s) => Ok((parse_visibility_string(s, path)?, None)),

        // Object form: "ucp_request": { "create": "omit", "update": "required" }
        Value::Object(map) => {
            // Lookup operation (already lowercase from ResolveOptions)
            match map.get(operation) {
                Some(Value::String(s)) => Ok((parse_visibility_string(s, path)?, None)),
                Some(Value::Object(obj)) => {
                    parse_transition_value(obj, &format!("{}/{}", path, operation))
                }
                Some(other) => Err(ResolveError::InvalidAnnotationType {
                    path: format!("{}/{}", path, operation),
                    actual: json_type_name(other).to_string(),
                }),
                None => {
                    // Check for shorthand transition form
                    if let Some(Value::Object(t)) = map.get("transition") {
                        parse_transition_value(t, path)
                    } else {
                        Ok((Visibility::Include, None))
                    }
                }
            }
        }

        // Invalid type
        other => Err(ResolveError::InvalidAnnotationType {
            path: path.to_string(),
            actual: json_type_name(other).to_string(),
        }),
    }
}

fn parse_transition_value(
    obj: &Map<String, Value>,
    path: &str,
) -> Result<(Visibility, Option<SchemaTransitionInfo>), ResolveError> {
    let t = obj
        .get("transition")
        .and_then(|v| v.as_object())
        .unwrap_or(obj);

    let from = t.get("from").and_then(|v| v.as_str()).unwrap_or("");
    let to = t.get("to").and_then(|v| v.as_str()).unwrap_or("");
    let description = t.get("description").and_then(|v| v.as_str()).unwrap_or("");

    if description.is_empty() {
        return Err(ResolveError::InvalidSchemaTransition {
            path: path.to_string(),
            message: "missing required field \"description\"".to_string(),
        });
    }
    if !is_valid_schema_transition(from, to) {
        return Err(ResolveError::InvalidSchemaTransition {
            path: path.to_string(),
            message: format!(
                "\"from\" ({}) and \"to\" ({}) must be distinct visibility values",
                from, to
            ),
        });
    }

    let vis = parse_visibility_string(from, path)?;
    Ok((
        vis,
        Some(SchemaTransitionInfo {
            from: from.to_string(),
            to: to.to_string(),
            description: description.to_string(),
        }),
    ))
}

/// Strip all UCP annotations from a schema.
///
/// Recursively removes `ucp_request` and `ucp_response`.
pub fn strip_annotations(schema: &Value) -> Value {
    strip_annotations_recursive(schema)
}

// --- Internal implementation ---

fn resolve_value(
    value: &Value,
    options: &ResolveOptions,
    path: &str,
) -> Result<Value, ResolveError> {
    match value {
        Value::Object(map) => resolve_object(map, options, path),
        Value::Array(arr) => resolve_array(arr, options, path),
        // Primitives pass through unchanged
        other => Ok(other.clone()),
    }
}

fn resolve_object(
    map: &Map<String, Value>,
    options: &ResolveOptions,
    path: &str,
) -> Result<Value, ResolveError> {
    let mut result = Map::new();

    // Track required array modifications
    let original_required: Vec<String> = map
        .get("required")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let mut new_required: Vec<String> = original_required.clone();

    for (key, value) in map {
        // Skip UCP annotations in output
        if UCP_ANNOTATIONS.contains(&key.as_str()) {
            continue;
        }

        let child_path = format!("{}/{}", path, key);

        match key.as_str() {
            "properties" => {
                let resolved = resolve_properties(value, options, &child_path, &mut new_required)?;
                result.insert(key.clone(), resolved);
            }
            "items" => {
                // Array items - recurse
                let resolved = resolve_value(value, options, &child_path)?;
                result.insert(key.clone(), resolved);
            }
            "$defs" | "definitions" => {
                // Definitions - recurse into each definition
                let resolved = resolve_defs(value, options, &child_path)?;
                result.insert(key.clone(), resolved);
            }
            "allOf" => {
                // allOf gets special handling: annotations from later branches
                // propagate to earlier branches (last-writer-wins), enabling
                // extension schemas to control visibility of inherited fields.
                let resolved = resolve_allof(value, options, &child_path)?;
                result.insert(key.clone(), resolved);
            }
            "anyOf" | "oneOf" => {
                // anyOf/oneOf branches are independent alternatives —
                // no annotation propagation across branches.
                let resolved = resolve_composition(value, options, &child_path)?;
                result.insert(key.clone(), resolved);
            }
            "additionalProperties" => {
                // If it's a schema (object), recurse; otherwise keep as-is
                if value.is_object() {
                    let resolved = resolve_value(value, options, &child_path)?;
                    result.insert(key.clone(), resolved);
                } else {
                    result.insert(key.clone(), value.clone());
                }
            }
            "required" => {
                // Will be handled at the end after processing properties
                continue;
            }
            _ => {
                // Other keys - recurse if object/array, otherwise copy
                let resolved = resolve_value(value, options, &child_path)?;
                result.insert(key.clone(), resolved);
            }
        }
    }

    // Add updated required array if non-empty or if original existed
    if !new_required.is_empty() || map.contains_key("required") {
        result.insert(
            "required".to_string(),
            Value::Array(new_required.into_iter().map(Value::String).collect()),
        );
    }

    Ok(Value::Object(result))
}

fn resolve_properties(
    value: &Value,
    options: &ResolveOptions,
    path: &str,
    required: &mut Vec<String>,
) -> Result<Value, ResolveError> {
    let Some(props) = value.as_object() else {
        return Ok(value.clone());
    };

    let mut result = Map::new();

    for (prop_name, prop_value) in props {
        let prop_path = format!("{}/{}", path, prop_name);

        // Get visibility for this property
        let (visibility, transition) = get_visibility(
            prop_value,
            options.direction,
            &options.operation,
            &prop_path,
        )?;

        match visibility {
            Visibility::Omit => {
                // Include future fields: currently omit but transitioning to non-omit.
                // Completes transition lifecycle symmetry — deprecations (to=omit) are
                // already surfaced; this surfaces planned additions (from=omit).
                let is_future =
                    options.include_future && transition.as_ref().is_some_and(|t| t.to != "omit");

                if is_future {
                    let resolved = resolve_value(prop_value, options, &prop_path)?;
                    let mut stripped = strip_annotations(&resolved);
                    apply_transition_metadata(&mut stripped, &transition);
                    result.insert(prop_name.clone(), stripped);
                    // NOT added to required — current visibility is omit
                }
                required.retain(|r| r != prop_name);
            }
            Visibility::Required => {
                // Keep property, ensure in required
                let resolved = resolve_value(prop_value, options, &prop_path)?;
                let mut stripped = strip_annotations(&resolved);
                apply_transition_metadata(&mut stripped, &transition);
                result.insert(prop_name.clone(), stripped);
                if !required.contains(prop_name) {
                    required.push(prop_name.clone());
                }
            }
            Visibility::Optional => {
                // Keep property, remove from required
                let resolved = resolve_value(prop_value, options, &prop_path)?;
                let mut stripped = strip_annotations(&resolved);
                apply_transition_metadata(&mut stripped, &transition);
                result.insert(prop_name.clone(), stripped);
                required.retain(|r| r != prop_name);
            }
            Visibility::Include => {
                // Keep as-is (preserve original required status)
                let resolved = resolve_value(prop_value, options, &prop_path)?;
                let mut stripped = strip_annotations(&resolved);
                apply_transition_metadata(&mut stripped, &transition);
                result.insert(prop_name.clone(), stripped);
            }
        }
    }

    Ok(Value::Object(result))
}

fn resolve_defs(
    value: &Value,
    options: &ResolveOptions,
    path: &str,
) -> Result<Value, ResolveError> {
    let Some(defs) = value.as_object() else {
        return Ok(value.clone());
    };

    let mut result = Map::new();
    for (name, def) in defs {
        let def_path = format!("{}/{}", path, name);
        let resolved = resolve_value(def, options, &def_path)?;
        result.insert(name.clone(), resolved);
    }

    Ok(Value::Object(result))
}

fn resolve_array(
    arr: &[Value],
    options: &ResolveOptions,
    path: &str,
) -> Result<Value, ResolveError> {
    let mut result = Vec::new();
    for (i, item) in arr.iter().enumerate() {
        let item_path = format!("{}/{}", path, i);
        let resolved = resolve_value(item, options, &item_path)?;
        result.push(resolved);
    }
    Ok(Value::Array(result))
}

fn resolve_composition(
    value: &Value,
    options: &ResolveOptions,
    path: &str,
) -> Result<Value, ResolveError> {
    let Some(arr) = value.as_array() else {
        return Ok(value.clone());
    };

    let mut result = Vec::new();
    for (i, item) in arr.iter().enumerate() {
        let item_path = format!("{}/{}", path, i);
        let resolved = resolve_value(item, options, &item_path)?;
        result.push(resolved);
    }

    Ok(Value::Array(result))
}

/// allOf-specific resolution with cross-branch annotation propagation.
///
/// Three-phase approach:
/// 1. **Collect**: scan all branches for annotations (last-writer-wins)
/// 2. **Validate**: check for type conflicts across branches
/// 3. **Inject + Resolve**: copy collected annotations into branches that lack them,
///    enforcing monotonicity (extensions cannot weaken required fields), then resolve
///
/// Why last-writer-wins: in UCP's allOf convention, the base schema is allOf[0]
/// and extensions follow. Later branches (extensions) should override earlier ones.
fn resolve_allof(
    value: &Value,
    options: &ResolveOptions,
    path: &str,
) -> Result<Value, ResolveError> {
    let Some(arr) = value.as_array() else {
        return Ok(value.clone());
    };

    let ann_key = options.direction.annotation_key();
    let merged = collect_allof_annotations(arr, ann_key);
    validate_allof_types(arr, path)?;

    let mut result = Vec::new();
    for (i, item) in arr.iter().enumerate() {
        let item_path = format!("{}/{}", path, i);
        let item = if !merged.is_empty() {
            inject_annotations(item, &merged, ann_key, options, &item_path)?
        } else {
            item.clone()
        };
        let resolved = resolve_value(&item, options, &item_path)?;
        result.push(resolved);
    }

    Ok(Value::Array(result))
}

/// Scan allOf branches and collect annotations per property (last-writer-wins).
///
/// Returns a map of property_name → annotation_value for properties that have
/// a UCP annotation in any branch. When multiple branches annotate the same
/// property, the last branch's annotation wins.
fn collect_allof_annotations(branches: &[Value], ann_key: &str) -> Map<String, Value> {
    let mut merged = Map::new();
    for branch in branches {
        let props = branch
            .as_object()
            .and_then(|o| o.get("properties"))
            .and_then(|p| p.as_object());
        if let Some(props) = props {
            for (name, prop) in props {
                if let Some(ann) = prop.as_object().and_then(|p| p.get(ann_key)) {
                    merged.insert(name.clone(), ann.clone());
                }
            }
        }
    }
    merged
}

/// Inject collected annotations into a branch's properties where they're missing.
///
/// Enforces monotonicity: if a field is `required` in a base branch's required
/// array, an extension annotation cannot weaken it to `omit` or `optional`.
///
/// | base required? | extension annotation | result     |
/// |---------------|---------------------|------------|
/// | yes           | required            | OK         |
/// | yes           | optional            | ERROR      |
/// | yes           | omit                | ERROR      |
/// | no            | any                 | OK         |
fn inject_annotations(
    branch: &Value,
    annotations: &Map<String, Value>,
    ann_key: &str,
    options: &ResolveOptions,
    path: &str,
) -> Result<Value, ResolveError> {
    let mut branch = branch.clone();

    let base_required: Vec<String> = branch
        .as_object()
        .and_then(|o| o.get("required"))
        .and_then(|r| r.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    if let Some(props) = branch
        .as_object_mut()
        .and_then(|o| o.get_mut("properties"))
        .and_then(|p| p.as_object_mut())
    {
        for (name, ann) in annotations {
            if let Some(prop) = props.get_mut(name) {
                if let Some(obj) = prop.as_object_mut() {
                    // Skip if this property already has its own annotation
                    if obj.contains_key(ann_key) {
                        continue;
                    }

                    // Monotonicity check: required fields cannot be weakened
                    if base_required.contains(name) {
                        let (vis, _) = get_visibility_from_annotation(
                            ann,
                            &options.operation,
                            &format!("{}/properties/{}", path, name),
                        )?;
                        if matches!(vis, Visibility::Omit | Visibility::Optional) {
                            return Err(ResolveError::MonotonicityViolation {
                                path: format!("{}/properties/{}", path, name),
                                field: name.clone(),
                                base_status: "required".into(),
                                attempted: match vis {
                                    Visibility::Omit => "omit",
                                    Visibility::Optional => "optional",
                                    Visibility::Required => "required",
                                    Visibility::Include => "include",
                                }
                                .into(),
                            });
                        }
                    }

                    obj.insert(ann_key.to_string(), ann.clone());
                }
            }
        }
    }

    Ok(branch)
}

/// Validate that allOf branches don't declare contradictory types on the same property.
///
/// Only checks string-form `"type"` values. Array-form types (e.g. `["string", "null"]`)
/// are intentionally skipped — they're rare and the semantic comparison is non-trivial.
fn validate_allof_types(branches: &[Value], path: &str) -> Result<(), ResolveError> {
    let mut prop_types: std::collections::HashMap<String, String> =
        std::collections::HashMap::new();
    for branch in branches {
        let props = branch
            .as_object()
            .and_then(|o| o.get("properties"))
            .and_then(|p| p.as_object());
        if let Some(props) = props {
            for (name, prop) in props {
                if let Some(type_val) = prop.as_object().and_then(|p| p.get("type")) {
                    if let Some(type_str) = type_val.as_str() {
                        if let Some(existing) = prop_types.get(name) {
                            if existing != type_str {
                                return Err(ResolveError::TypeConflict {
                                    path: format!("{}/properties/{}", path, name),
                                    base_type: existing.clone(),
                                    ext_type: type_str.to_string(),
                                });
                            }
                        } else {
                            prop_types.insert(name.clone(), type_str.to_string());
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

fn strip_annotations_recursive(value: &Value) -> Value {
    match value {
        Value::Object(map) => {
            let mut result = Map::new();
            for (k, v) in map {
                if !UCP_ANNOTATIONS.contains(&k.as_str()) {
                    result.insert(k.clone(), strip_annotations_recursive(v));
                }
            }
            Value::Object(result)
        }
        Value::Array(arr) => Value::Array(arr.iter().map(strip_annotations_recursive).collect()),
        other => other.clone(),
    }
}

fn apply_transition_metadata(value: &mut Value, transition: &Option<SchemaTransitionInfo>) {
    if let (Value::Object(map), Some(info)) = (value, transition) {
        map.insert(
            "x-ucp-schema-transition".to_string(),
            serde_json::json!({
                "from": info.from,
                "to": info.to,
                "description": info.description,
            }),
        );
        if info.to == "omit" {
            map.insert("deprecated".to_string(), Value::Bool(true));
        }
    }
}

fn parse_visibility_string(s: &str, path: &str) -> Result<Visibility, ResolveError> {
    Visibility::parse(s).ok_or_else(|| ResolveError::UnknownVisibility {
        path: path.to_string(),
        value: s.to_string(),
    })
}

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

    // === Visibility Parsing Tests ===

    #[test]
    fn get_visibility_shorthand_omit() {
        let prop = json!({
            "type": "string",
            "ucp_request": "omit"
        });
        let (vis, _) = get_visibility(&prop, Direction::Request, "create", "/test").unwrap();
        assert_eq!(vis, Visibility::Omit);
    }

    #[test]
    fn get_visibility_shorthand_required() {
        let prop = json!({
            "type": "string",
            "ucp_request": "required"
        });
        let (vis, _) = get_visibility(&prop, Direction::Request, "create", "/test").unwrap();
        assert_eq!(vis, Visibility::Required);
    }

    #[test]
    fn get_visibility_object_form() {
        let prop = json!({
            "type": "string",
            "ucp_request": {
                "create": "omit",
                "update": "required"
            }
        });
        let (vis, _) = get_visibility(&prop, Direction::Request, "create", "/test").unwrap();
        assert_eq!(vis, Visibility::Omit);

        let (vis, _) = get_visibility(&prop, Direction::Request, "update", "/test").unwrap();
        assert_eq!(vis, Visibility::Required);
    }

    #[test]
    fn get_visibility_schema_transition_object() {
        let prop = json!({
            "type": "string",
            "ucp_request": {
                "update": {
                    "transition": {
                        "from": "required",
                        "to": "omit",
                        "description": "Legacy id will be removed in v2."
                    }
                }
            }
        });
        let (vis, dep) = get_visibility(&prop, Direction::Request, "update", "/test").unwrap();
        assert_eq!(vis, Visibility::Required);
        let info = dep.unwrap();
        assert_eq!(info.from, "required");
        assert_eq!(info.to, "omit");
        assert_eq!(info.description, "Legacy id will be removed in v2.");
    }

    #[test]
    fn get_visibility_missing_annotation() {
        let prop = json!({
            "type": "string"
        });
        let (vis, _) = get_visibility(&prop, Direction::Request, "create", "/test").unwrap();
        assert_eq!(vis, Visibility::Include);
    }

    #[test]
    fn get_visibility_missing_operation_in_dict() {
        let prop = json!({
            "type": "string",
            "ucp_request": {
                "create": "omit"
            }
        });
        // "update" not in dict, should default to include
        let (vis, _) = get_visibility(&prop, Direction::Request, "update", "/test").unwrap();
        assert_eq!(vis, Visibility::Include);
    }

    #[test]
    fn get_visibility_response_direction() {
        let prop = json!({
            "type": "string",
            "ucp_response": "omit"
        });
        let (vis, _) = get_visibility(&prop, Direction::Response, "create", "/test").unwrap();
        assert_eq!(vis, Visibility::Omit);

        // Request direction should see include (no ucp_request annotation)
        let (vis, _) = get_visibility(&prop, Direction::Request, "create", "/test").unwrap();
        assert_eq!(vis, Visibility::Include);
    }

    #[test]
    fn get_visibility_invalid_type_errors() {
        let prop = json!({
            "type": "string",
            "ucp_request": 123
        });
        let result = get_visibility(&prop, Direction::Request, "create", "/test");
        assert!(matches!(
            result,
            Err(ResolveError::InvalidAnnotationType { .. })
        ));
    }

    #[test]
    fn get_visibility_unknown_visibility_errors() {
        let prop = json!({
            "type": "string",
            "ucp_request": "readonly"
        });
        let result = get_visibility(&prop, Direction::Request, "create", "/test");
        assert!(matches!(
            result,
            Err(ResolveError::UnknownVisibility { value, .. }) if value == "readonly"
        ));
    }

    #[test]
    fn get_visibility_unknown_in_dict_errors() {
        let prop = json!({
            "type": "string",
            "ucp_request": {
                "create": "maybe"
            }
        });
        let result = get_visibility(&prop, Direction::Request, "create", "/test");
        assert!(matches!(
            result,
            Err(ResolveError::UnknownVisibility { value, .. }) if value == "maybe"
        ));
    }

    #[test]
    fn get_visibility_invalid_schema_transition_errors() {
        let prop = json!({
            "type": "string",
            "ucp_request": {
                "update": {
                    "transition": {
                        "from": "required",
                        "to": "omit"
                    }
                }
            }
        });
        let result = get_visibility(&prop, Direction::Request, "update", "/test");
        assert!(matches!(
            result,
            Err(ResolveError::InvalidSchemaTransition { .. })
        ));
    }

    // === Transformation Tests ===

    #[test]
    fn resolve_omit_removes_field() {
        let schema = json!({
            "type": "object",
            "properties": {
                "id": { "type": "string", "ucp_request": "omit" },
                "name": { "type": "string" }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        assert!(result["properties"].get("id").is_none());
        assert!(result["properties"].get("name").is_some());
    }

    #[test]
    fn resolve_omit_removes_from_required() {
        let schema = json!({
            "type": "object",
            "required": ["id", "name"],
            "properties": {
                "id": { "type": "string", "ucp_request": "omit" },
                "name": { "type": "string" }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        let required = result["required"].as_array().unwrap();
        assert!(!required.contains(&json!("id")));
        assert!(required.contains(&json!("name")));
    }

    #[test]
    fn resolve_required_adds_to_required() {
        let schema = json!({
            "type": "object",
            "properties": {
                "id": { "type": "string", "ucp_request": "required" }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        let required = result["required"].as_array().unwrap();
        assert!(required.contains(&json!("id")));
    }

    #[test]
    fn resolve_optional_removes_from_required() {
        let schema = json!({
            "type": "object",
            "required": ["id"],
            "properties": {
                "id": { "type": "string", "ucp_request": "optional" }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        let required = result["required"].as_array().unwrap();
        assert!(!required.contains(&json!("id")));
    }

    #[test]
    fn resolve_schema_transition_emits_transition_info() {
        let schema = json!({
            "type": "object",
            "required": ["id"],
            "properties": {
                "id": {
                    "type": "string",
                    "ucp_request": {
                        "transition": {
                            "from": "required",
                            "to": "optional",
                            "description": "Will become optional in v2."
                        }
                    }
                }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        assert!(result["properties"].get("id").is_some());
        let required = result["required"].as_array().unwrap();
        assert!(required.contains(&json!("id")));
        let transition = result["properties"]["id"]
            .get("x-ucp-schema-transition")
            .unwrap();
        assert_eq!(transition["from"], "required");
        assert_eq!(transition["to"], "optional");
        assert_eq!(transition["description"], "Will become optional in v2.");
        assert!(result["properties"]["id"].get("deprecated").is_none());
    }

    #[test]
    fn resolve_schema_transition_sets_deprecated_when_to_omit() {
        let schema = json!({
            "type": "object",
            "required": ["id"],
            "properties": {
                "id": {
                    "type": "string",
                    "ucp_request": {
                        "transition": {
                            "from": "optional",
                            "to": "omit",
                            "description": "Will be removed in v2."
                        }
                    }
                }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        assert!(result["properties"].get("id").is_some());
        let required = result["required"].as_array().unwrap();
        assert!(!required.contains(&json!("id")));
        assert!(result["properties"]["id"]
            .get("x-ucp-schema-transition")
            .is_some());
        assert_eq!(result["properties"]["id"]["deprecated"], true);
    }

    #[test]
    fn resolve_schema_transition_per_operation() {
        let schema = json!({
            "type": "object",
            "required": ["id"],
            "properties": {
                "id": {
                    "type": "string",
                    "ucp_request": {
                        "create": "omit",
                        "update": {
                            "transition": {
                                "from": "required",
                                "to": "omit",
                                "description": "Removing in v2."
                            }
                        }
                    }
                }
            }
        });

        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();
        assert!(result["properties"].get("id").is_none());

        let options = ResolveOptions::new(Direction::Request, "update");
        let result = resolve(&schema, &options).unwrap();
        assert!(result["properties"].get("id").is_some());
        let required = result["required"].as_array().unwrap();
        assert!(required.contains(&json!("id")));
        assert_eq!(
            result["properties"]["id"]["x-ucp-schema-transition"]["description"],
            "Removing in v2."
        );
    }

    #[test]
    fn resolve_include_future_surfaces_omit_to_nonomit_transition() {
        let schema = json!({
            "type": "object",
            "properties": {
                "existing": { "type": "string", "ucp_request": "required" },
                "planned": {
                    "type": "string",
                    "description": "A future field.",
                    "ucp_request": {
                        "transition": {
                            "from": "omit",
                            "to": "required",
                            "description": "Planned for v2."
                        }
                    }
                }
            }
        });

        // Without include_future: planned field is absent
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();
        assert!(result["properties"].get("existing").is_some());
        assert!(result["properties"].get("planned").is_none());

        // With include_future: planned field is present with transition metadata
        let options = ResolveOptions::new(Direction::Request, "create").include_future(true);
        let result = resolve(&schema, &options).unwrap();
        assert!(result["properties"].get("existing").is_some());
        assert!(result["properties"].get("planned").is_some());

        // Transition metadata is emitted
        let transition = &result["properties"]["planned"]["x-ucp-schema-transition"];
        assert_eq!(transition["from"], "omit");
        assert_eq!(transition["to"], "required");
        assert_eq!(transition["description"], "Planned for v2.");

        // NOT in required (current visibility is omit)
        let required = result.get("required").and_then(|r| r.as_array());
        if let Some(req) = required {
            assert!(!req.contains(&json!("planned")));
        }

        // Not marked deprecated (to != "omit")
        assert!(result["properties"]["planned"].get("deprecated").is_none());
    }

    #[test]
    fn resolve_include_future_does_not_surface_plain_omit() {
        // A plain omit field (no transition) stays hidden even with include_future.
        let schema = json!({
            "type": "object",
            "properties": {
                "hidden": { "type": "string", "ucp_request": "omit" }
            }
        });

        let options = ResolveOptions::new(Direction::Request, "create").include_future(true);
        let result = resolve(&schema, &options).unwrap();
        assert!(result["properties"].get("hidden").is_none());
    }

    #[test]
    fn resolve_include_future_per_operation_transition() {
        // Transition scoped to a single operation: "search" is future, "lookup" is omit.
        let schema = json!({
            "type": "object",
            "properties": {
                "like": {
                    "type": "array",
                    "ucp_request": {
                        "search": {
                            "transition": {
                                "from": "omit",
                                "to": "optional",
                                "description": "Planned for search."
                            }
                        },
                        "lookup": "omit"
                    }
                }
            }
        });

        // search with include_future: like appears
        let options = ResolveOptions::new(Direction::Request, "search").include_future(true);
        let result = resolve(&schema, &options).unwrap();
        assert!(result["properties"].get("like").is_some());
        assert_eq!(
            result["properties"]["like"]["x-ucp-schema-transition"]["to"],
            "optional"
        );

        // lookup with include_future: like stays hidden (plain omit, no transition)
        let options = ResolveOptions::new(Direction::Request, "lookup").include_future(true);
        let result = resolve(&schema, &options).unwrap();
        assert!(result["properties"].get("like").is_none());
    }

    #[test]
    fn resolve_include_future_coexists_with_deprecated() {
        // Three fields: normal, future (from=omit), deprecated (to=omit).
        // All three should be present with include_future, each with correct metadata.
        let schema = json!({
            "type": "object",
            "properties": {
                "stable": { "type": "string", "ucp_request": "required" },
                "planned": {
                    "type": "string",
                    "ucp_request": {
                        "transition": {
                            "from": "omit",
                            "to": "optional",
                            "description": "Coming soon."
                        }
                    }
                },
                "legacy": {
                    "type": "string",
                    "ucp_request": {
                        "transition": {
                            "from": "optional",
                            "to": "omit",
                            "description": "Being removed."
                        }
                    }
                }
            }
        });

        let options = ResolveOptions::new(Direction::Request, "create").include_future(true);
        let result = resolve(&schema, &options).unwrap();

        // stable: present, no transition
        assert!(result["properties"].get("stable").is_some());
        assert!(result["properties"]["stable"]
            .get("x-ucp-schema-transition")
            .is_none());

        // planned: present via include_future, transition metadata, not deprecated
        assert!(result["properties"].get("planned").is_some());
        assert_eq!(
            result["properties"]["planned"]["x-ucp-schema-transition"]["from"],
            "omit"
        );
        assert!(result["properties"]["planned"].get("deprecated").is_none());

        // legacy: present (from=optional), transition metadata, deprecated=true
        assert!(result["properties"].get("legacy").is_some());
        assert_eq!(
            result["properties"]["legacy"]["x-ucp-schema-transition"]["to"],
            "omit"
        );
        assert_eq!(result["properties"]["legacy"]["deprecated"], true);

        // required: only stable (planned is omit-visibility, legacy is optional)
        let required = result["required"].as_array().unwrap();
        assert!(required.contains(&json!("stable")));
        assert!(!required.contains(&json!("planned")));
        assert!(!required.contains(&json!("legacy")));
    }

    #[test]
    fn resolve_include_preserves_original() {
        let schema = json!({
            "type": "object",
            "required": ["id"],
            "properties": {
                "id": { "type": "string" },
                "name": { "type": "string" }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        // Both fields should be present
        assert!(result["properties"].get("id").is_some());
        assert!(result["properties"].get("name").is_some());

        // Required should be preserved
        let required = result["required"].as_array().unwrap();
        assert!(required.contains(&json!("id")));
        assert!(!required.contains(&json!("name")));
    }

    #[test]
    fn resolve_strips_annotations() {
        let schema = json!({
            "type": "object",
            "properties": {
                "id": {
                    "type": "string",
                    "ucp_request": "required",
                    "ucp_response": "omit"
                }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        // Annotations should be stripped
        assert!(result["properties"]["id"].get("ucp_request").is_none());
        assert!(result["properties"]["id"].get("ucp_response").is_none());
    }

    #[test]
    fn resolve_empty_schema_after_filtering() {
        let schema = json!({
            "type": "object",
            "required": ["id"],
            "properties": {
                "id": { "type": "string", "ucp_request": "omit" }
            }
        });
        let options = ResolveOptions::new(Direction::Request, "create");
        let result = resolve(&schema, &options).unwrap();

        // Properties should be empty object
        assert_eq!(result["properties"], json!({}));
        // Required should be empty array
        assert_eq!(result["required"], json!([]));
    }

    // === Strip Annotations Tests ===

    #[test]
    fn strip_annotations_removes_all_ucp() {
        let schema = json!({
            "type": "object",
            "properties": {
                "id": {
                    "type": "string",
                    "ucp_request": "omit",
                    "ucp_response": "required"
                }
            }
        });
        let result = strip_annotations(&schema);

        assert!(result["properties"]["id"].get("ucp_request").is_none());
        assert!(result["properties"]["id"].get("ucp_response").is_none());
    }
}