vimanam 1.7.0

OpenAPI/Swagger to Markdown documentation generator with grouping, filtering, and detail levels for docs and LLM context
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
//! `vimanam diff <OLD> <NEW>`: compares two versions of a spec and reports
//! what changed, classified as breaking, non-breaking or needing review.
//!
//! [`diff`] derives a data-only [`SpecDiff`] from two intermediate
//! representations; [`severity`] classifies each [`Change`]; [`write_diff`]
//! renders the result as Markdown. Keeping the three apart lets the rule table
//! be unit-tested row by row and lets another front end reuse the data.
//!
//! # What is compared
//!
//! Endpoints are matched by `(METHOD, path)`, parameters by `(name, in)` and
//! responses by status code. Request and response bodies are compared as
//! **resolved** schemas: every `$ref` is inlined
//! (`resolve_schema_value`) and the result canonicalised
//! (`canonicalize_schema_value`) before a generic JSON differ
//! (`diff_values`) reports field-level changes as JSON pointers. That is what
//! makes a change behind a shared component visible: an operation whose object
//! is byte-identical in both specs still reports "response schema changed" when
//! the `Widget` it points at gained a required property.
//!
//! Only a response's first media type is compared (the same one the renderer
//! documents, see `response_schema`), and only the first request-body media
//! type. `allOf`/`oneOf`/`anyOf` lists are compared index-wise. A path-template
//! rename (`/pets/{id}` → `/pets/{petId}`) appears as a removal plus an
//! addition.
//!
//! # Determinism
//!
//! Changes are emitted in old-spec order (old endpoints first, then endpoints
//! only the new spec has, each in its spec's order) and the canonical schema
//! values have sorted keys, so the same pair of specs always produces
//! byte-identical output.

pub mod json;
mod render;
mod value;

pub use render::write_diff;
use value::{Location, diff_values, locate};
pub use value::{ValueChange, ValueChangeKind};

use std::collections::{HashMap, HashSet};

use anyhow::{Context, Result};
use indexmap::IndexSet;
use serde_json::Value;

use crate::markdown::{estimate_tokens, generate_markdown, response_schema};
use crate::models::{ApiDocumentation, DocConfig, Endpoint, Parameter};
use crate::report;
pub use crate::report::EndpointRef;
use crate::utils::{canonicalize_schema_value, resolve_schema_value};

use render::required_member_pointer;

// ── changes ─────────────────────────────────────────────────────────────────

/// How a change affects existing clients of the API.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// Existing clients can break: something they rely on went away or became
    /// stricter.
    Breaking,
    /// Purely additive or relaxing; existing clients keep working.
    NonBreaking,
    /// The shape changed in a way whose impact depends on usage (a `format`, a
    /// bound, a composition variant); a human should look. Never trips
    /// `--fail-on-breaking`.
    Review,
}

/// One difference between the two specs, attributed to an endpoint.
#[derive(Debug, Clone, PartialEq)]
pub struct Change {
    /// The HTTP operation to which this change is attributed.
    pub endpoint: EndpointRef,
    /// The concrete difference or operation applied at this location.
    pub kind: ChangeKind,
}

/// The kind of contract difference. Future versions may add variants.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ChangeKind {
    /// An operation exists only in the new spec.
    EndpointAdded,
    /// An operation from the old spec was removed.
    EndpointRemoved {
        /// Whether the removed endpoint was already deprecated.
        was_deprecated: bool,
    },
    /// A parameter was added to a surviving operation.
    ParameterAdded {
        /// The declared name.
        name: String,
        /// Parameter location such as `path`, `query`, `header`, or `body`.
        location: String,
        /// Whether clients must supply this parameter.
        required: bool,
    },
    /// A parameter was removed from a surviving operation.
    ParameterRemoved {
        /// The declared name.
        name: String,
        /// Parameter location such as `path`, `query`, `header`, or `body`.
        location: String,
    },
    /// A parameter changed between optional and required.
    ParameterRequiredChanged {
        /// The declared name.
        name: String,
        /// Parameter location such as `path`, `query`, `header`, or `body`.
        location: String,
        /// Whether the parameter is required in the new spec.
        now_required: bool,
    },
    /// A parameter that disappeared from one location and reappeared, under the
    /// same name, in another (detected only when the name is unambiguous on
    /// both sides).
    ParameterLocationChanged {
        /// The declared name.
        name: String,
        /// Parameter location in the old spec.
        old_location: String,
        /// Parameter location in the new spec.
        new_location: String,
    },
    /// A parameter schema has a field-level change.
    ParameterSchemaChanged {
        /// The declared name.
        name: String,
        /// Parameter location such as `path`, `query`, `header`, or `body`.
        location: String,
        /// The field-level change in the resolved, canonicalized schema.
        change: ValueChange,
    },
    /// A response status was added.
    ResponseAdded {
        /// Response status code exactly as declared, including `default`.
        status: String,
    },
    /// A response status was removed.
    ResponseRemoved {
        /// Response status code exactly as declared, including `default`.
        status: String,
    },
    /// An operationId changed, appeared, or disappeared.
    OperationIdChanged {
        /// The value or count in the old spec.
        old: Option<String>,
        /// The value or count in the new spec.
        new: Option<String>,
    },
    /// An operation changed its deprecation flag.
    DeprecatedChanged {
        /// Whether the endpoint is deprecated in the new spec.
        now: bool,
    },
    /// A field-level change in the resolved request body schema.
    RequestSchemaChanged {
        /// The field-level change in the resolved, canonicalized schema.
        change: ValueChange,
    },
    /// A field-level change in the resolved schema of one response.
    ResponseSchemaChanged {
        /// Response status code exactly as declared, including `default`.
        status: String,
        /// The field-level change in the resolved, canonicalized schema.
        change: ValueChange,
    },
}

/// The outcome of comparing two specs.
#[derive(Debug, Clone, PartialEq)]
pub struct SpecDiff {
    /// Title declared by the old spec.
    pub old_title: String,
    /// API version declared by the old spec.
    pub old_version: String,
    /// Title declared by the new spec.
    pub new_title: String,
    /// API version declared by the new spec.
    pub new_version: String,
    /// Every change, in report order (see the module docs).
    pub changes: Vec<Change>,
}

impl SpecDiff {
    /// Count operations present only in the new spec.
    pub fn endpoints_added(&self) -> usize {
        self.changes
            .iter()
            .filter(|change| matches!(change.kind, ChangeKind::EndpointAdded))
            .count()
    }

    /// Count operations present only in the old spec.
    pub fn endpoints_removed(&self) -> usize {
        self.changes
            .iter()
            .filter(|change| matches!(change.kind, ChangeKind::EndpointRemoved { .. }))
            .count()
    }

    /// Endpoints present in both specs with at least one change.
    pub fn endpoints_changed(&self) -> usize {
        self.changes
            .iter()
            .filter(|change| {
                !matches!(
                    change.kind,
                    ChangeKind::EndpointAdded | ChangeKind::EndpointRemoved { .. }
                )
            })
            .map(|change| &change.endpoint)
            .collect::<IndexSet<_>>()
            .len()
    }

    /// Count changes with the requested severity.
    pub fn count(&self, level: Severity) -> usize {
        self.changes
            .iter()
            .filter(|change| severity(change) == level)
            .count()
    }

    /// Whether any change has breaking severity.
    pub fn has_breaking(&self) -> bool {
        self.changes
            .iter()
            .any(|change| severity(change) == Severity::Breaking)
    }
}

/// Classifies a change. The rule table:
///
/// | Change | Severity |
/// |---|---|
/// | Endpoint removed | Breaking |
/// | Endpoint added | Non-breaking |
/// | Parameter removed | Breaking |
/// | Parameter added, required | Breaking |
/// | Parameter added, optional | Non-breaking |
/// | Parameter newly required | Breaking |
/// | Parameter made optional | Non-breaking |
/// | Parameter location changed | Breaking |
/// | Response code removed | Breaking |
/// | Response code added | Non-breaking |
/// | `operationId` changed (Some→Some, Some→None) | Breaking |
/// | `operationId` added (None→Some) | Non-breaking |
/// | `deprecated` flag changed either way | Non-breaking |
///
/// Parameter and request schemas (what the client sends):
///
/// | Change | Severity |
/// |---|---|
/// | member added to `required` | Breaking |
/// | member removed from `required` | Non-breaking |
/// | `type` changed at any pointer | Breaking |
/// | property removed | Breaking |
/// | property added | Non-breaking |
/// | `enum` member removed | Breaking |
/// | `enum` member added | Non-breaking |
/// | `additionalProperties` became `false` | Breaking |
/// | `nullable` became `true` | Non-breaking |
/// | `nullable` became `false` (clients sending `null` now fail) | Breaking |
/// | anything else (`format`, bounds, `pattern`, `items` shape, `allOf`/`oneOf`/`anyOf` variants, other `additionalProperties`) | Review |
///
/// Response schemas (what the client receives):
///
/// | Change | Severity |
/// |---|---|
/// | schema removed entirely (root became absent) | Breaking |
/// | property removed | Breaking |
/// | property added | Non-breaking |
/// | `type` changed at any pointer | Breaking |
/// | `enum` member removed | Breaking |
/// | `enum` member added (strictly typed clients reject unknown values) | Review |
/// | member removed from `required` (consumers relied on it) | Breaking |
/// | member added to `required` | Non-breaking |
/// | `nullable` became `true` | Breaking |
/// | `nullable` became `false` | Non-breaking |
/// | anything else | Review |
///
/// When a property is removed, the companion "removed from `required`" row for
/// the same property is not reported at all (see `value_changes`).
pub fn severity(change: &Change) -> Severity {
    match &change.kind {
        ChangeKind::EndpointAdded => Severity::NonBreaking,
        ChangeKind::EndpointRemoved { .. } => Severity::Breaking,
        ChangeKind::ParameterAdded { required, .. } => {
            if *required {
                Severity::Breaking
            } else {
                Severity::NonBreaking
            }
        }
        ChangeKind::ParameterRemoved { .. } => Severity::Breaking,
        ChangeKind::ParameterRequiredChanged { now_required, .. } => {
            if *now_required {
                Severity::Breaking
            } else {
                Severity::NonBreaking
            }
        }
        ChangeKind::ParameterLocationChanged { .. } => Severity::Breaking,
        ChangeKind::ParameterSchemaChanged { change, .. }
        | ChangeKind::RequestSchemaChanged { change } => request_schema_severity(change),
        ChangeKind::ResponseAdded { .. } => Severity::NonBreaking,
        ChangeKind::ResponseRemoved { .. } => Severity::Breaking,
        ChangeKind::OperationIdChanged {
            old: None,
            new: Some(_),
        } => Severity::NonBreaking,
        ChangeKind::OperationIdChanged { .. } => Severity::Breaking,
        ChangeKind::DeprecatedChanged { .. } => Severity::NonBreaking,
        ChangeKind::ResponseSchemaChanged { change, .. } => response_schema_severity(change),
    }
}

/// True when the change leaves a boolean keyword equal to `flag` (added or
/// changed to it, or removed when its old value was the opposite).
fn became(kind: &ValueChangeKind, flag: bool) -> bool {
    match kind {
        ValueChangeKind::Added(Value::Bool(now))
        | ValueChangeKind::Changed {
            new: Value::Bool(now),
            ..
        } => *now == flag,
        ValueChangeKind::Removed(Value::Bool(was)) => *was != flag,
        _ => false,
    }
}

fn request_schema_severity(change: &ValueChange) -> Severity {
    use ValueChangeKind::{Added, Removed};

    match (locate(&change.pointer), &change.kind) {
        (Location::RequiredElement, Added(_)) => Severity::Breaking,
        (Location::RequiredElement, Removed(_)) => Severity::NonBreaking,
        (Location::Type, _) => Severity::Breaking,
        (Location::Property, Removed(_)) => Severity::Breaking,
        (Location::Property, Added(_)) => Severity::NonBreaking,
        (Location::EnumElement, Removed(_)) => Severity::Breaking,
        (Location::EnumElement, Added(_)) => Severity::NonBreaking,
        (Location::AdditionalProperties, kind) if became(kind, false) => Severity::Breaking,
        (Location::Nullable, kind) if became(kind, true) => Severity::NonBreaking,
        (Location::Nullable, kind) if became(kind, false) => Severity::Breaking,
        _ => Severity::Review,
    }
}

fn response_schema_severity(change: &ValueChange) -> Severity {
    use ValueChangeKind::{Added, Changed, Removed};

    if change.pointer.is_empty()
        && let Changed {
            new: Value::Null, ..
        } = &change.kind
    {
        // The response used to document a body and no longer does.
        return Severity::Breaking;
    }

    match (locate(&change.pointer), &change.kind) {
        (Location::Property, Removed(_)) => Severity::Breaking,
        (Location::Property, Added(_)) => Severity::NonBreaking,
        (Location::Type, _) => Severity::Breaking,
        (Location::EnumElement, Removed(_)) => Severity::Breaking,
        (Location::EnumElement, Added(_)) => Severity::Review,
        (Location::RequiredElement, Removed(_)) => Severity::Breaking,
        (Location::RequiredElement, Added(_)) => Severity::NonBreaking,
        (Location::Nullable, kind) if became(kind, true) => Severity::Breaking,
        (Location::Nullable, kind) if became(kind, false) => Severity::NonBreaking,
        _ => Severity::Review,
    }
}

// ── structural diff ─────────────────────────────────────────────────────────

/// Compares two specs (see the module docs for identity and ordering rules).
pub fn diff(old: &ApiDocumentation, new: &ApiDocumentation) -> SpecDiff {
    let mut changes = Vec::new();

    // Lookup tables only; iteration always follows the endpoint vectors so the
    // report order never depends on hashing.
    let new_by_key: HashMap<(&str, &str), &Endpoint> = new
        .endpoints
        .iter()
        .map(|endpoint| ((endpoint.method.as_str(), endpoint.path.as_str()), endpoint))
        .collect();
    let old_keys: HashSet<(&str, &str)> = old
        .endpoints
        .iter()
        .map(|endpoint| (endpoint.method.as_str(), endpoint.path.as_str()))
        .collect();

    for old_endpoint in &old.endpoints {
        let key = (old_endpoint.method.as_str(), old_endpoint.path.as_str());
        match new_by_key.get(&key) {
            Some(new_endpoint) => diff_endpoint(old_endpoint, new_endpoint, old, new, &mut changes),
            None => changes.push(Change {
                endpoint: EndpointRef::from(old_endpoint),
                kind: ChangeKind::EndpointRemoved {
                    was_deprecated: old_endpoint.deprecated,
                },
            }),
        }
    }

    for new_endpoint in &new.endpoints {
        let key = (new_endpoint.method.as_str(), new_endpoint.path.as_str());
        if !old_keys.contains(&key) {
            changes.push(Change {
                endpoint: EndpointRef::from(new_endpoint),
                kind: ChangeKind::EndpointAdded,
            });
        }
    }

    SpecDiff {
        old_title: old.title.clone(),
        old_version: old.version.clone(),
        new_title: new.title.clone(),
        new_version: new.version.clone(),
        changes,
    }
}

fn diff_endpoint(
    old_endpoint: &Endpoint,
    new_endpoint: &Endpoint,
    old_doc: &ApiDocumentation,
    new_doc: &ApiDocumentation,
    changes: &mut Vec<Change>,
) {
    let endpoint = EndpointRef::from(old_endpoint);

    if old_endpoint.operation_id != new_endpoint.operation_id {
        changes.push(Change {
            endpoint: endpoint.clone(),
            kind: ChangeKind::OperationIdChanged {
                old: old_endpoint.operation_id.clone(),
                new: new_endpoint.operation_id.clone(),
            },
        });
    }

    if old_endpoint.deprecated != new_endpoint.deprecated {
        changes.push(Change {
            endpoint: endpoint.clone(),
            kind: ChangeKind::DeprecatedChanged {
                now: new_endpoint.deprecated,
            },
        });
    }

    diff_parameters(
        &endpoint,
        old_endpoint,
        new_endpoint,
        old_doc,
        new_doc,
        changes,
    );
    diff_request_body(
        &endpoint,
        old_endpoint,
        new_endpoint,
        old_doc,
        new_doc,
        changes,
    );
    diff_responses(
        &endpoint,
        old_endpoint,
        new_endpoint,
        old_doc,
        new_doc,
        changes,
    );
}

fn is_body(parameter: &Parameter) -> bool {
    parameter.parameter_in == "body"
}

/// Compares the non-body parameters by `(name, in)`. A parameter that vanished
/// from one location and appeared under the same name in another is reported
/// as a location change rather than a removal plus an addition, provided the
/// name is unambiguous on both sides.
fn diff_parameters(
    endpoint: &EndpointRef,
    old_endpoint: &Endpoint,
    new_endpoint: &Endpoint,
    old_doc: &ApiDocumentation,
    new_doc: &ApiDocumentation,
    changes: &mut Vec<Change>,
) {
    let old_params: Vec<&Parameter> = old_endpoint
        .parameters
        .iter()
        .filter(|parameter| !is_body(parameter))
        .collect();
    let new_params: Vec<&Parameter> = new_endpoint
        .parameters
        .iter()
        .filter(|parameter| !is_body(parameter))
        .collect();

    let mut removed: Vec<&Parameter> = Vec::new();
    for old_param in &old_params {
        match find_parameter(&new_params, old_param) {
            Some(new_param) => {
                diff_parameter_pair(endpoint, old_param, new_param, old_doc, new_doc, changes)
            }
            None => removed.push(old_param),
        }
    }
    let added: Vec<&Parameter> = new_params
        .iter()
        .copied()
        .filter(|new_param| find_parameter(&old_params, new_param).is_none())
        .collect();

    let mut paired: Vec<usize> = Vec::new();
    for old_param in &removed {
        let same_name_removed = removed
            .iter()
            .filter(|candidate| candidate.name == old_param.name)
            .count();
        let candidates: Vec<usize> = added
            .iter()
            .enumerate()
            .filter(|(index, candidate)| {
                candidate.name == old_param.name && !paired.contains(index)
            })
            .map(|(index, _)| index)
            .collect();

        if same_name_removed == 1 && candidates.len() == 1 {
            let index = candidates[0];
            let new_param = added[index];
            paired.push(index);
            changes.push(Change {
                endpoint: endpoint.clone(),
                kind: ChangeKind::ParameterLocationChanged {
                    name: old_param.name.clone(),
                    old_location: old_param.parameter_in.clone(),
                    new_location: new_param.parameter_in.clone(),
                },
            });
            diff_parameter_pair(endpoint, old_param, new_param, old_doc, new_doc, changes);
        } else {
            changes.push(Change {
                endpoint: endpoint.clone(),
                kind: ChangeKind::ParameterRemoved {
                    name: old_param.name.clone(),
                    location: old_param.parameter_in.clone(),
                },
            });
        }
    }

    for (index, new_param) in added.iter().enumerate() {
        if paired.contains(&index) {
            continue;
        }
        changes.push(Change {
            endpoint: endpoint.clone(),
            kind: ChangeKind::ParameterAdded {
                name: new_param.name.clone(),
                location: new_param.parameter_in.clone(),
                required: new_param.required.unwrap_or(false),
            },
        });
    }
}

/// The parameter in `haystack` with the same `(name, in)` identity as `needle`.
fn find_parameter<'a>(haystack: &[&'a Parameter], needle: &Parameter) -> Option<&'a Parameter> {
    haystack.iter().copied().find(|candidate| {
        candidate.name == needle.name && candidate.parameter_in == needle.parameter_in
    })
}

/// Compares two versions of the same parameter: its `required` flag and its
/// (resolved, canonical) type schema.
fn diff_parameter_pair(
    endpoint: &EndpointRef,
    old_param: &Parameter,
    new_param: &Parameter,
    old_doc: &ApiDocumentation,
    new_doc: &ApiDocumentation,
    changes: &mut Vec<Change>,
) {
    let old_required = old_param.required.unwrap_or(false);
    let new_required = new_param.required.unwrap_or(false);
    if old_required != new_required {
        changes.push(Change {
            endpoint: endpoint.clone(),
            kind: ChangeKind::ParameterRequiredChanged {
                name: new_param.name.clone(),
                location: new_param.parameter_in.clone(),
                now_required: new_required,
            },
        });
    }

    let old_schema = parameter_schema_value(old_param, old_doc);
    let new_schema = parameter_schema_value(new_param, new_doc);
    for change in value_changes(&old_schema, &new_schema) {
        changes.push(Change {
            endpoint: endpoint.clone(),
            kind: ChangeKind::ParameterSchemaChanged {
                name: new_param.name.clone(),
                location: new_param.parameter_in.clone(),
                change,
            },
        });
    }
}

/// The canonical type of a parameter: its resolved `schema` (OpenAPI 3), or
/// for a Swagger 2 non-body parameter the inline `type`/`format`/`items`/`enum`
/// keywords, which the model keeps in `extensions`. `Null` when it has neither.
fn parameter_schema_value(parameter: &Parameter, doc: &ApiDocumentation) -> Value {
    let mut value = match &parameter.schema {
        Some(schema) => resolve_schema_value(schema, doc),
        None => {
            let mut inline = serde_json::Map::new();
            for key in ["type", "format", "items", "enum"] {
                if let Some(keyword) = parameter.extensions.get(key) {
                    inline.insert(key.to_string(), keyword.clone());
                }
            }
            if inline.is_empty() {
                Value::Null
            } else {
                Value::Object(inline)
            }
        }
    };
    canonicalize_schema_value(&mut value);
    value
}

/// The canonical resolved form of an optional schema; `Null` when absent.
fn optional_schema_value(schema: Option<&crate::models::Schema>, doc: &ApiDocumentation) -> Value {
    match schema {
        Some(schema) => {
            let mut value = resolve_schema_value(schema, doc);
            canonicalize_schema_value(&mut value);
            value
        }
        None => Value::Null,
    }
}

/// All differences between two canonical schemas, minus the redundant
/// "removed from `required`" row that accompanies every removed property: once
/// `/properties/x` is gone, `/required/x` going with it is not a second change.
fn value_changes(old: &Value, new: &Value) -> Vec<ValueChange> {
    let mut out = Vec::new();
    diff_values(old, new, &mut String::new(), &mut out);

    let removed_properties: HashSet<String> = out
        .iter()
        .filter(|change| {
            matches!(change.kind, ValueChangeKind::Removed(_))
                && locate(&change.pointer) == Location::Property
        })
        .map(|change| change.pointer.clone())
        .collect();
    if removed_properties.is_empty() {
        return out;
    }

    out.retain(|change| {
        !(matches!(change.kind, ValueChangeKind::Removed(_))
            && locate(&change.pointer) == Location::RequiredElement
            && removed_properties.contains(&required_member_pointer(&change.pointer)))
    });
    out
}

/// Compares the request bodies: the parser represents a body as a synthetic
/// `in: body` parameter (one per media type; the first is compared).
fn diff_request_body(
    endpoint: &EndpointRef,
    old_endpoint: &Endpoint,
    new_endpoint: &Endpoint,
    old_doc: &ApiDocumentation,
    new_doc: &ApiDocumentation,
    changes: &mut Vec<Change>,
) {
    let old_body = old_endpoint.parameters.iter().find(|p| is_body(p));
    let new_body = new_endpoint.parameters.iter().find(|p| is_body(p));

    match (old_body, new_body) {
        (None, None) => {}
        (Some(old_body), None) => changes.push(Change {
            endpoint: endpoint.clone(),
            kind: ChangeKind::ParameterRemoved {
                name: old_body.name.clone(),
                location: old_body.parameter_in.clone(),
            },
        }),
        (None, Some(new_body)) => changes.push(Change {
            endpoint: endpoint.clone(),
            kind: ChangeKind::ParameterAdded {
                name: new_body.name.clone(),
                location: new_body.parameter_in.clone(),
                required: new_body.required.unwrap_or(false),
            },
        }),
        (Some(old_body), Some(new_body)) => {
            let old_required = old_body.required.unwrap_or(false);
            let new_required = new_body.required.unwrap_or(false);
            if old_required != new_required {
                changes.push(Change {
                    endpoint: endpoint.clone(),
                    kind: ChangeKind::ParameterRequiredChanged {
                        name: new_body.name.clone(),
                        location: new_body.parameter_in.clone(),
                        now_required: new_required,
                    },
                });
            }

            let old_schema = optional_schema_value(old_body.schema.as_ref(), old_doc);
            let new_schema = optional_schema_value(new_body.schema.as_ref(), new_doc);
            for change in value_changes(&old_schema, &new_schema) {
                changes.push(Change {
                    endpoint: endpoint.clone(),
                    kind: ChangeKind::RequestSchemaChanged { change },
                });
            }
        }
    }
}

/// Compares responses by status code, then the resolved schema of each status
/// present in both.
fn diff_responses(
    endpoint: &EndpointRef,
    old_endpoint: &Endpoint,
    new_endpoint: &Endpoint,
    old_doc: &ApiDocumentation,
    new_doc: &ApiDocumentation,
    changes: &mut Vec<Change>,
) {
    for (status, old_response) in &old_endpoint.responses {
        let Some(new_response) = new_endpoint.responses.get(status) else {
            changes.push(Change {
                endpoint: endpoint.clone(),
                kind: ChangeKind::ResponseRemoved {
                    status: status.clone(),
                },
            });
            continue;
        };

        let old_schema = optional_schema_value(response_schema(old_response), old_doc);
        let new_schema = optional_schema_value(response_schema(new_response), new_doc);
        for change in value_changes(&old_schema, &new_schema) {
            changes.push(Change {
                endpoint: endpoint.clone(),
                kind: ChangeKind::ResponseSchemaChanged {
                    status: status.clone(),
                    change,
                },
            });
        }
    }

    for status in new_endpoint.responses.keys() {
        if !old_endpoint.responses.contains_key(status) {
            changes.push(Change {
                endpoint: endpoint.clone(),
                kind: ChangeKind::ResponseAdded {
                    status: status.clone(),
                },
            });
        }
    }
}

// ── --report deltas ─────────────────────────────────────────────────────────

/// Whole-document hygiene counts and token estimates for both specs
/// (`--report`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Deltas {
    /// `(check label, old count, new count)` in hygiene-report order.
    pub hygiene: Vec<(&'static str, usize, usize)>,
    /// Estimated tokens of the old spec at `--detail full --include-schemas`.
    pub tokens_old: usize,
    /// Estimated tokens of the new spec at `--detail full --include-schemas`.
    pub tokens_new: usize,
}

/// Runs the hygiene checks and a full-detail render over both specs with an
/// unfiltered configuration ([`DocConfig::unfiltered`]).
pub fn compute_deltas(old: &ApiDocumentation, new: &ApiDocumentation) -> Result<Deltas> {
    let config = DocConfig::unfiltered();

    let old_report = report::analyze(old, &config);
    let new_report = report::analyze(new, &config);
    let hygiene = old_report
        .counts()
        .into_iter()
        .zip(new_report.counts())
        .map(|((label, old_count), (_, new_count))| (label, old_count, new_count))
        .collect();

    Ok(Deltas {
        hygiene,
        tokens_old: estimate_document(old, &config).context("Failed to render the old spec")?,
        tokens_new: estimate_document(new, &config).context("Failed to render the new spec")?,
    })
}

fn estimate_document(doc: &ApiDocumentation, config: &DocConfig) -> Result<usize> {
    let mut buffer = Vec::new();
    generate_markdown(&mut buffer, doc, config)?;
    Ok(estimate_tokens(&buffer))
}

#[cfg(test)]
pub(crate) mod test_support {
    use super::*;

    fn endpoint() -> EndpointRef {
        EndpointRef {
            method: "GET".into(),
            path: "/widgets".into(),
        }
    }

    pub(crate) fn change(kind: ChangeKind) -> Change {
        Change {
            endpoint: endpoint(),
            kind,
        }
    }

    pub(crate) fn added(pointer: &str, value: Value) -> ValueChange {
        ValueChange {
            pointer: pointer.into(),
            kind: ValueChangeKind::Added(value),
        }
    }

    pub(crate) fn removed(pointer: &str, value: Value) -> ValueChange {
        ValueChange {
            pointer: pointer.into(),
            kind: ValueChangeKind::Removed(value),
        }
    }

    pub(crate) fn changed(pointer: &str, old: Value, new: Value) -> ValueChange {
        ValueChange {
            pointer: pointer.into(),
            kind: ValueChangeKind::Changed { old, new },
        }
    }

    pub(crate) fn request(change: ValueChange) -> Severity {
        severity(&self::change(ChangeKind::RequestSchemaChanged { change }))
    }

    pub(crate) fn response(change: ValueChange) -> Severity {
        severity(&self::change(ChangeKind::ResponseSchemaChanged {
            status: "200".into(),
            change,
        }))
    }

    pub(crate) fn parameter(change: ValueChange) -> Severity {
        severity(&self::change(ChangeKind::ParameterSchemaChanged {
            name: "limit".into(),
            location: "query".into(),
            change,
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::test_support::{
        added, change, changed, parameter, removed, request, response,
    };
    use serde_json::json;

    // ── diff_values ──────────────────────────────────────────────────────

    #[test]
    fn diff_values_treats_property_named_properties_as_a_field() {
        // A GeoJSON-style `properties` field is a property, not the keyword:
        // adding it is one property added, not a descent into its schema.
        let old = json!({"type": "object", "properties": {"id": {"type": "string"}}});
        let new = json!({
            "type": "object",
            "properties": {
                "id": {"type": "string"},
                "properties": {"type": "object", "additionalProperties": true}
            }
        });
        let changes = value_changes(&old, &new);
        assert_eq!(
            changes,
            vec![added(
                "/properties/properties",
                json!({"type": "object", "additionalProperties": true})
            )]
        );
        assert_eq!(response(changes[0].clone()), Severity::NonBreaking);
        assert_eq!(request(changes[0].clone()), Severity::NonBreaking);

        // Removing it is likewise one row, and removing a field called
        // `required` or `enum` does not turn into set arithmetic.
        let old = json!({"properties": {
            "properties": {"type": "object"},
            "required": {"type": "array", "items": {"type": "string"}},
            "enum": {"type": "array"}
        }});
        let new = json!({"properties": {}});
        assert_eq!(
            value_changes(&old, &new),
            vec![
                removed("/properties/properties", json!({"type": "object"})),
                removed(
                    "/properties/required",
                    json!({"type": "array", "items": {"type": "string"}})
                ),
                removed("/properties/enum", json!({"type": "array"})),
            ]
        );
    }

    #[test]
    fn diff_values_treats_property_named_required_as_a_field() {
        let old = json!({"type": "object", "properties": {"required": {"type": "boolean"}}});
        let new = json!({"type": "object", "properties": {"required": {"type": "string"}}});
        let changes = value_changes(&old, &new);
        assert_eq!(
            changes,
            vec![changed(
                "/properties/required/type",
                json!("boolean"),
                json!("string")
            )]
        );
        assert_eq!(request(changes[0].clone()), Severity::Breaking);
        assert_eq!(response(changes[0].clone()), Severity::Breaking);
    }

    #[test]
    fn value_changes_suppresses_required_removal_of_a_removed_property() {
        let old = json!({
            "type": "object",
            "required": ["a", "b"],
            "properties": {"a": {"type": "string"}, "b": {"type": "string"}}
        });
        let new = json!({
            "type": "object",
            "required": ["b"],
            "properties": {"b": {"type": "string"}}
        });
        assert_eq!(
            value_changes(&old, &new),
            vec![removed("/properties/a", json!({"type": "string"}))]
        );

        // Nested schemas get the same treatment, scoped to their own level.
        let old = json!({"items": {
            "required": ["id"],
            "properties": {"id": {"type": "string"}}
        }});
        let new = json!({"items": {"properties": {}}});
        assert_eq!(
            value_changes(&old, &new),
            vec![removed("/items/properties/id", json!({"type": "string"}))]
        );
    }

    #[test]
    fn value_changes_keeps_required_removal_when_the_property_stays() {
        let old = json!({"required": ["a"], "properties": {"a": {"type": "string"}}});
        let new = json!({"properties": {"a": {"type": "string"}}});
        assert_eq!(
            value_changes(&old, &new),
            vec![removed("/required/a", json!("a"))]
        );
    }

    // ── severity: structural rows ────────────────────────────────────────

    #[test]
    fn severity_endpoint_rows() {
        assert_eq!(
            severity(&change(ChangeKind::EndpointAdded)),
            Severity::NonBreaking
        );
        assert_eq!(
            severity(&change(ChangeKind::EndpointRemoved {
                was_deprecated: true
            })),
            Severity::Breaking
        );
        assert_eq!(
            severity(&change(ChangeKind::EndpointRemoved {
                was_deprecated: false
            })),
            Severity::Breaking
        );
    }

    #[test]
    fn severity_parameter_rows() {
        let name = || "limit".to_string();
        let location = || "query".to_string();
        assert_eq!(
            severity(&change(ChangeKind::ParameterAdded {
                name: name(),
                location: location(),
                required: false
            })),
            Severity::NonBreaking
        );
        assert_eq!(
            severity(&change(ChangeKind::ParameterAdded {
                name: name(),
                location: location(),
                required: true
            })),
            Severity::Breaking
        );
        assert_eq!(
            severity(&change(ChangeKind::ParameterRemoved {
                name: name(),
                location: location()
            })),
            Severity::Breaking
        );
        assert_eq!(
            severity(&change(ChangeKind::ParameterRequiredChanged {
                name: name(),
                location: location(),
                now_required: true
            })),
            Severity::Breaking
        );
        assert_eq!(
            severity(&change(ChangeKind::ParameterRequiredChanged {
                name: name(),
                location: location(),
                now_required: false
            })),
            Severity::NonBreaking
        );
        assert_eq!(
            severity(&change(ChangeKind::ParameterLocationChanged {
                name: name(),
                old_location: location(),
                new_location: "header".into()
            })),
            Severity::Breaking
        );
    }

    #[test]
    fn severity_response_code_rows() {
        assert_eq!(
            severity(&change(ChangeKind::ResponseAdded {
                status: "404".into()
            })),
            Severity::NonBreaking
        );
        assert_eq!(
            severity(&change(ChangeKind::ResponseRemoved {
                status: "404".into()
            })),
            Severity::Breaking
        );
    }

    #[test]
    fn severity_operation_id_rows() {
        let id = |s: &str| Some(s.to_string());
        assert_eq!(
            severity(&change(ChangeKind::OperationIdChanged {
                old: id("a"),
                new: id("b")
            })),
            Severity::Breaking
        );
        assert_eq!(
            severity(&change(ChangeKind::OperationIdChanged {
                old: id("a"),
                new: None
            })),
            Severity::Breaking
        );
        assert_eq!(
            severity(&change(ChangeKind::OperationIdChanged {
                old: None,
                new: id("b")
            })),
            Severity::NonBreaking
        );
    }

    #[test]
    fn severity_deprecated_rows() {
        assert_eq!(
            severity(&change(ChangeKind::DeprecatedChanged { now: true })),
            Severity::NonBreaking
        );
        assert_eq!(
            severity(&change(ChangeKind::DeprecatedChanged { now: false })),
            Severity::NonBreaking
        );
    }

    // ── severity: parameter schema rows ──────────────────────────────────

    #[test]
    fn severity_parameter_schema_rows() {
        assert_eq!(
            parameter(changed("/type", json!("string"), json!("integer"))),
            Severity::Breaking
        );
        assert_eq!(
            parameter(removed("/enum/a", json!("a"))),
            Severity::Breaking
        );
        assert_eq!(
            parameter(added("/enum/z", json!("z"))),
            Severity::NonBreaking
        );
        assert_eq!(
            parameter(changed("/format", json!("int32"), json!("int64"))),
            Severity::Review
        );
    }

    // ── severity: request schema rows ────────────────────────────────────

    #[test]
    fn severity_request_schema_breaking_rows() {
        assert_eq!(
            request(added("/required/x", json!("x"))),
            Severity::Breaking
        );
        assert_eq!(
            request(changed("/type", json!("string"), json!("integer"))),
            Severity::Breaking
        );
        assert_eq!(
            request(changed(
                "/properties/a/items/type",
                json!("string"),
                json!("number")
            )),
            Severity::Breaking
        );
        assert_eq!(request(added("/type", json!("string"))), Severity::Breaking);
        assert_eq!(
            request(removed("/properties/x", json!({"type": "string"}))),
            Severity::Breaking
        );
        assert_eq!(
            request(removed("/properties/a/properties/b", json!({}))),
            Severity::Breaking
        );
        assert_eq!(request(removed("/enum/a", json!("a"))), Severity::Breaking);
        assert_eq!(
            request(changed("/additionalProperties", json!(true), json!(false))),
            Severity::Breaking
        );
        assert_eq!(
            request(added("/additionalProperties", json!(false))),
            Severity::Breaking
        );
        // Clients that were sending `null` now get rejected.
        assert_eq!(
            request(changed("/nullable", json!(true), json!(false))),
            Severity::Breaking
        );
        assert_eq!(
            request(removed("/nullable", json!(true))),
            Severity::Breaking
        );
        assert_eq!(
            request(added("/properties/a/nullable", json!(false))),
            Severity::Breaking
        );
    }

    #[test]
    fn severity_request_schema_non_breaking_rows() {
        assert_eq!(
            request(added("/properties/x", json!({"type": "string"}))),
            Severity::NonBreaking
        );
        assert_eq!(
            request(removed("/required/x", json!("x"))),
            Severity::NonBreaking
        );
        assert_eq!(request(added("/enum/z", json!("z"))), Severity::NonBreaking);
        assert_eq!(
            request(added("/nullable", json!(true))),
            Severity::NonBreaking
        );
        assert_eq!(
            request(changed("/properties/a/nullable", json!(false), json!(true))),
            Severity::NonBreaking
        );
    }

    #[test]
    fn severity_request_schema_review_rows() {
        assert_eq!(
            request(changed("/format", json!("float"), json!("double"))),
            Severity::Review
        );
        assert_eq!(request(added("/minimum", json!(0))), Severity::Review);
        assert_eq!(request(removed("/maximum", json!(10))), Severity::Review);
        assert_eq!(
            request(changed("/pattern", json!("a"), json!("b"))),
            Severity::Review
        );
        assert_eq!(
            request(changed("/items/format", json!("a"), json!("b"))),
            Severity::Review
        );
        assert_eq!(request(added("/allOf/1", json!({}))), Severity::Review);
        assert_eq!(request(removed("/oneOf/0", json!({}))), Severity::Review);
        assert_eq!(
            request(changed("/additionalProperties", json!(false), json!(true))),
            Severity::Review
        );
        assert_eq!(
            request(added("/additionalProperties", json!({"type": "string"}))),
            Severity::Review
        );
        assert_eq!(
            request(changed("", Value::Null, json!({"type": "object"}))),
            Severity::Review
        );
    }

    // ── severity: response schema rows ───────────────────────────────────

    #[test]
    fn severity_response_schema_breaking_rows() {
        assert_eq!(
            response(removed("/properties/x", json!({}))),
            Severity::Breaking
        );
        assert_eq!(
            response(changed("/type", json!("object"), json!("array"))),
            Severity::Breaking
        );
        assert_eq!(
            response(changed(
                "/properties/a/type",
                json!("string"),
                json!("integer")
            )),
            Severity::Breaking
        );
        assert_eq!(response(removed("/enum/a", json!("a"))), Severity::Breaking);
        assert_eq!(
            response(removed("/required/x", json!("x"))),
            Severity::Breaking
        );
        assert_eq!(
            response(added("/nullable", json!(true))),
            Severity::Breaking
        );
        assert_eq!(
            response(changed("/properties/a/nullable", json!(false), json!(true))),
            Severity::Breaking
        );
        // The response schema went away entirely.
        assert_eq!(
            response(changed("", json!({"type": "object"}), Value::Null)),
            Severity::Breaking
        );
    }

    #[test]
    fn severity_response_schema_non_breaking_rows() {
        assert_eq!(
            response(added("/properties/pricing", json!({"type": "object"}))),
            Severity::NonBreaking
        );
        assert_eq!(
            response(added("/required/x", json!("x"))),
            Severity::NonBreaking
        );
        assert_eq!(
            response(changed("/nullable", json!(true), json!(false))),
            Severity::NonBreaking
        );
        assert_eq!(
            response(removed("/nullable", json!(true))),
            Severity::NonBreaking
        );
    }

    #[test]
    fn severity_response_schema_review_rows() {
        assert_eq!(
            response(changed("/format", json!("float"), json!("double"))),
            Severity::Review
        );
        // Strictly typed clients reject values they do not know.
        assert_eq!(response(added("/enum/z", json!("z"))), Severity::Review);
        assert_eq!(
            response(added("/properties/status/enum/archived", json!("archived"))),
            Severity::Review
        );
        // A response that gained a body: nothing existing clients parse broke.
        assert_eq!(
            response(changed("", Value::Null, json!({"type": "object"}))),
            Severity::Review
        );
        assert_eq!(
            response(changed("/additionalProperties", json!(true), json!(false))),
            Severity::Review
        );
        assert_eq!(response(added("/allOf/1", json!({}))), Severity::Review);
        assert_eq!(response(added("/minimum", json!(1))), Severity::Review);
    }
}