ocpi-tariffs 0.55.0

OCPI tariff calculations
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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
//! The errors and refusals that fixing a tariff reports.
//!
//! Use [`tariff::fix`](crate::tariff::fix) to fix a tariff.

// Producing the edits and agreeing to apply them are separate steps, which is what lets edits
// drawn from different kinds of warning be resolved together. A `warning::Set<schema::Warning>`
// and a `warning::Set<lint::tariff::Warning>` are different types, so no single call can take
// both; `Edit` is the common form each reduces to, and a caller concatenates them before one
// `apply`.
//
// Applying each set in turn instead would resolve the second against a re-parsed document, where
// the ids of the first no longer mean the same elements, so two edits landing on one element
// could not be resolved against each other at all.
//
// `apply` resolves a whole set of edits against one document in a single pass. Resolving
// them one at a time would be wrong for the same reason within a set: which span removes an
// element depends on which of its siblings survive, so removals have to be resolved together.
// See `json::Document::removal_spans`.

#[cfg(test)]
mod test;

#[cfg(test)]
mod test_apply;

#[cfg(test)]
mod test_defer_enclosing_replacements;

#[cfg(test)]
mod test_edits;

#[cfg(test)]
mod test_json;

#[cfg(test)]
mod test_lint_warning;

#[cfg(test)]
mod test_price_invariant;

#[cfg(test)]
mod test_schema_warning;

use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
};

use crate::{
    datetime, json, lint,
    schema::{self, OcpiEnum as _},
    string, warning, weekday,
};

/// The edits that resolve `warnings`, each beside the id of the warning that proposed it.
///
/// This keeps every rename whose new key would clash, so a caller joining the edits of
/// several calls can refuse the clashing renames once over all of them, with
/// [`refuse_clashing_renames`].
///
/// This doesn't propose removing the last occurrence of a key that occurs more than once in an
/// object, whichever warning's fix asks for it. Schema warnings and lint warnings both have fixes
/// that remove a field. The last occurrence is the one used, so removing it would result in an
/// earlier field's value being used. The removal is proposed once
/// [`DuplicateField`](schema::Warning::DuplicateField) has been resolved and the earlier fields are
/// gone, so [`tariff::fix`](crate::tariff::fix) takes one more pass over such a document. Filtering
/// the warnings never lets a removal change what a document says.
pub(crate) fn proposed_edits<W: Fixable>(
    doc: &json::Document<'_>,
    warnings: &warning::Set<W>,
) -> Result<Vec<Proposed>, Error> {
    let mut out: Vec<Proposed> = Vec::new();
    let last_of_repeated = doc.last_of_repeated_keys();

    for group in warnings {
        let (element, raised) = group.to_parts();
        let live = doc
            .element(element.id)
            .ok_or(Error::UnknownElement(element.id))?;

        for warning in raised {
            let Some(edit) = warning.fix(live) else {
                continue;
            };

            if let Change::Remove(id) = edit.change
                && last_of_repeated.contains(&id)
            {
                continue;
            }

            out.push(Proposed {
                edit,
                warning: warning.id(),
            });
        }
    }

    Ok(out)
}

/// An [`Edit`] beside the id of the warning whose fix proposed it.
///
/// Only `refuse_clashing_renames` reads the id, to name the warning in each [`Refused`]. So the
/// id stays out of [`Edit`], which callers outside this crate see.
pub(crate) struct Proposed {
    edit: Edit,

    warning: warning::Id,
}

impl Proposed {
    pub(crate) fn into_edit(self) -> Edit {
        self.edit
    }
}

/// A fix that [`tariff::fix`](crate::tariff::fix) proposed for a warning and then
/// refused, so the warning remains in the fixed tariff.
/// [`lint::fix::Fixed::refused`](crate::lint::fix::Fixed::refused) lists them.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Refused {
    /// The path of the field the refused fix would have changed. For a rename, that is
    /// the field whose name the fix would have rewritten.
    pub path: json::Path,

    /// The id of the warning whose fix was refused.
    pub warning: warning::Id,

    /// Why the fix was refused.
    pub reason: Refusal,
}

/// Why a proposed fix was refused.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Refusal {
    /// The fix renames a field, and the new name would clash with the name of another
    /// field in the same object.
    RenameClashes,
}

impl fmt::Display for Refusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RenameClashes => f.write_str(
                "renaming the field would clash with the name of another field in the same object",
            ),
        }
    }
}

/// A [`Warning`](crate::Warning) that a mechanical edit can resolve.
///
/// An implementation reports what edit would resolve the warning, not whether the edit should
/// be made. Whether a given fix is wanted is the caller's decision, so a caller that does not
/// want one filters the warning out of the set before calling [`proposed_edits`].
///
/// An implementation also states whether the document means the same after the edit, as the
/// edit's [`Meaning`]. A caller can drop the edits whose meaning it doesn't want, as well as or in
/// place of filtering the warnings.
pub(crate) trait Fixable: crate::Warning {
    /// The edit that resolves this warning at `element`, or `None` if nothing mechanical can
    /// resolve it.
    fn fix(&self, element: &json::Element<'_>) -> Option<Edit>;
}

impl Fixable for schema::Warning {
    #[expect(
        clippy::match_same_arms,
        reason = "one arm per variant, so a new variant has to state whether it can be fixed"
    )]
    fn fix(&self, element: &json::Element<'_>) -> Option<Edit> {
        match self {
            // A `null` value has no semantic meaning in OCPI. The item can be removed.
            Self::NullField => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // The OCPI spec does not define this field so the fix feature can remove it.
            Self::UnexpectedField => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // Removing the field would delete the only record of what the author meant.
            // Renaming it to the one name in `expected` is a guess at that meaning. After the
            // rename, parsing reads the field, so the rename is a `Meaning::Changes` edit. For a
            // pricing field the rename also changes what a session costs. When `expected` holds
            // several names, only the author can choose between them.
            //
            // The arm proposes the rename whatever else is in the object. The function
            // `refuse_clashing_renames` then refuses it for a pass when the new key would clash
            // with another key in the same object, and `refused_renames` lists the three ways it
            // can clash.
            //
            // A field holding `null` records nothing under either name, so the arm
            // removes it instead, which keeps the meaning. Renaming it would count as a change the
            // caller has to allow, and it could block the rename of a sibling field that is
            // nearest to the same name.
            Self::MisspelledField { expected } => {
                if element.is_null() {
                    return Some(Edit::remove(element.id(), Meaning::Preserves));
                }
                let [name] = expected.as_slice() else {
                    return None;
                };
                Some(Edit::rename(
                    element.id(),
                    Json::string(name),
                    Meaning::Changes,
                ))
            }

            // Rewriting the value to the one variant in `expected` is a guess at what the author
            // meant. After the rewrite, parsing reads the value, so the rewrite is a
            // `Meaning::Changes` edit. For a pricing field, such as a price component's `type` or
            // a restriction's `day_of_week`, the rewrite also changes what a session costs.
            //
            // Parsing drops a price component whose `type` it can't read, and pricing rejects a
            // tariff whose `day_of_week` holds a value parsing can't read. When `expected` holds
            // several variants, only the author can choose between them.
            Self::MisspelledValue {
                expected,
                actual: _,
            } => {
                let [variant] = expected.as_slice() else {
                    return None;
                };
                Some(Edit::replace(
                    element.id(),
                    Json::string(variant),
                    Meaning::Changes,
                ))
            }

            // The warning is anchored on a superseded occurrence: a later one carries the value.
            // Removing this one leaves the document semantically identical.
            Self::DuplicateField => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // A non-spec field is off-spec but used because we can infer what it should have been.
            // Removing it would change how the document prices, so there is no fix action.
            Self::NonSpecField => None,

            // Parsing matches the field by its decoded name, so writing the name without its
            // escapes leaves the document semantically identical.
            Self::FieldNameContainsEscapeCodes => plain_field_name(element),

            // Which field the author meant is unknown, so only the author can rewrite the name. The
            // walk also raises `UnexpectedField` on the field. The fix for that warning removes the
            // field when the caller asks for unexpected fields to be removed.
            Self::FieldNameInvalidEscape => None,

            // Write the variant with the correct case.
            Self::IncorrectCase {
                expected,
                actual: _,
            } => Some(Edit::replace(
                element.id(),
                Json::string(expected),
                Meaning::Preserves,
            )),

            // `expected` is the date or time the library read, written in the spec's form, so the
            // document means the same date or time after the rewrite.
            Self::IncorrectFormat {
                expected,
                actual: _,
            } => Some(Edit::replace(
                element.id(),
                Json::string(expected),
                Meaning::Preserves,
            )),

            // Rounding a number changes what a session costs, so it is not a fix this
            // layer makes on its own. #456 decides that policy and needs `Json::number`, which
            // #454 adds.
            Self::ExcessivePrecision { max: _, scale: _ } => None,

            // All the below issues require intervention from the author.
            Self::MissingField { name: _ }
            | Self::InvalidType {
                expected: _,
                actual: _,
            }
            | Self::StringTooLong { max: _, len: _ }
            | Self::InvalidValue {
                expected: _,
                actual: _,
            }
            | Self::Cardinality => None,
        }
    }
}

impl Fixable for lint::tariff::Warning {
    #[expect(
        clippy::match_same_arms,
        reason = "one arm per variant, so a new variant has to state whether it can be fixed"
    )]
    fn fix(&self, element: &json::Element<'_>) -> Option<Edit> {
        match self {
            // A list of all seven days matches every day, which is what leaving the list out
            // means, so the element matches the same days without it.
            Self::ContainsEntireWeek => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // An object holding no restriction restricts nothing, which is the same as no object.
            Self::RestrictionsEmpty => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // A `min_duration` of `0` allows every session, so the element applies to the same
            // sessions without the field. The removal needs no check of its own on the value: the
            // linter raises this warning only for a bound that lowered to a duration of exactly
            // `0`, and a fractional or negative one never lowers at all.
            Self::MinDurationZeroAllowsEverySession => {
                Some(Edit::remove(element.id(), Meaning::Preserves))
            }

            // Which days a list matches is a question of membership, so neither the order of
            // the days nor a repeat of one changes it.
            Self::DayOfWeekDuplicates | Self::DayOfWeekUnsorted => sorted_day_of_week(element),

            // OCPI reads an empty list the same as no list, so the element matches the same days
            // without it.
            Self::DayOfWeekEmpty => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // `23:59` and the `00:00` the spec asks for do not cover the same day, so
            // rewriting one to the other moves a boundary by a minute.
            Self::EndTimeIsNearEndOfDay => None,

            // A `min_kwh`, `min_power` or `min_current` of `0` excludes a negative value, and the
            // library prices a CDR that reports one. Removing the field would change what the
            // session costs. `MinDurationZeroAllowsEverySession` does get that removal, which is
            // safe only because a duration is never negative.
            Self::MinZeroExcludesOnlyNegative => None,

            // Nothing mechanical resolves these. Two fields disagree and only the author knows
            // which of them is wrong, or the value is unusable and only the author knows what
            // it was meant to be. `Duration` is the one wrapped enum with no fixable variant:
            // a duration that does not parse, is not an int, or overflows is all it reports.
            Self::Duration(_)
            | Self::MinPriceIsGreaterThanMax
            | Self::StartDateTimeIsAfterEndDateTime => None,

            // A bound of midnight restricts nothing. Every time of day is at or after a
            // `start_time` of midnight, and parsing reads an `end_time` of midnight as the end of
            // the day. So the element applies under the same conditions without the field.
            //
            // The linter also raises this warning on an `end_time` of `23:59`, and removing that
            // bound would widen the element's time window by a minute, which is
            // `EndTimeIsNearEndOfDay`'s objection. So the fix reads the time the way parsing a
            // tariff does, and removes the bound only when it reads as midnight. Parsing reads
            // `0:00` as midnight, as it does `00:00`.
            //
            // With both bounds present the linter raises the warning on `start_time` alone, and a
            // fix receives only the element its warning sits on. So one pass of the fixing loop
            // removes `start_time`. The linter then raises the warning on the lone `end_time`,
            // which the next pass removes.
            Self::ContainsEntireDay => {
                let json::Value::String(raw) = element.value() else {
                    return None;
                };

                let time = datetime::parse_time(raw.as_unescaped_str()).ok()?;

                if time != jiff::civil::Time::midnight() {
                    return None;
                }

                Some(Edit::remove(element.id(), Meaning::Preserves))
            }

            // TODO #405 Fixable at this element, not yet written. The warning is raised only
            // once the value has parsed as a valid alpha-3, so the `country::Code` behind it
            // already holds the alpha-2 to write in its place, and the lowering normalizes the
            // two strings to that same `Code` regardless. Needs a crate-visible alpha-3
            // lookup, because `Code::from_alpha_3` is reachable from `country` alone.
            Self::CpoCountryCodeShouldBeAlpha2 => None,

            // Pricing never uses this element, so removing it doesn't change any price. Another
            // element may still match a session, so the tariff still has one after the removal,
            // as OCPI requires.
            Self::ElementExcludesEverySession(lint::tariff::OtherElements::SomeMayMatch) => {
                Some(Edit::remove(element.id(), Meaning::Preserves))
            }

            // No other element may match a session. OCPI requires a tariff to have at least one
            // element, and which one to keep is the author's choice, so `lint --fix` removes
            // nothing.
            Self::ElementExcludesEverySession(lint::tariff::OtherElements::NoneMayMatch) => None,

            // While pricing rejects the tariff, `lint` can't tell whether another element may match
            // a session. Removing this one could leave none, so `lint --fix` removes nothing.
            Self::ElementExcludesEverySession(lint::tariff::OtherElements::TariffRejected) => None,

            // For each dimension, pricing uses the first element that has a component for
            // that dimension and whose restrictions match. The split puts the new elements where
            // the original element stood, each with the original's restrictions. Only one new
            // element has components for a given dimension, and that element holds the
            // original's components for the dimension. So for every dimension, pricing finds the
            // same components it found before the split.
            //
            // OCPI 2.1.1 says only that the first element with matching restrictions is used. A
            // reader could take that to mean one element prices the whole session. Under that
            // reading, the split would stop charging every dimension but the first. The 2.1.1
            // example tariff works only under the per-dimension reading, and this crate prices
            // 2.1.1 by that reading.
            Self::ElementPricesMoreThanOneDimension => split_by_dimension(element),

            // Each of these sits on one restriction field. Removing the field would make the
            // element match more sessions, which is the opposite of what its author meant.
            //
            // Where the element's restrictions do exclude every session, `lint` also raises
            // `ElementExcludesEverySession` on the element, and the fix for that warning can remove
            // the whole element.
            Self::LowerBoundAtOrAboveUpper | Self::MaxZeroNeverMatch | Self::NeverValid => None,

            // TODO #407 The lowering's own warnings, each wrapping an enum that mixes the two
            // cases. A lower-case country, currency or string is `IncorrectCase` and a
            // rewrite; so is a value carrying escape codes that decode. An invalid code, a
            // malformed escape or a number out of range is not. Resolving them means `Fixable`
            // reaching into the wrapped enum, since the wrapper is the wrong altitude for the
            // decision.
            Self::Country(_)
            | Self::Currency(_)
            | Self::DateTime(_)
            | Self::Money(_)
            | Self::Number(_)
            | Self::String(_) => None,
        }
    }
}

/// The edit that puts a `day_of_week` list in spec order and drops its repeats.
///
/// Returns `None` unless every item is a day this can name, so a list holding anything else is
/// left exactly as the author wrote it. The schema accepts a day in any case, and the match
/// here is exact, so a lower-case list is one of the lists that keeps its warning.
fn sorted_day_of_week(element: &json::Element<'_>) -> Option<Edit> {
    let items = element.value().as_array()?;
    let mut days: Vec<weekday::Weekday> = Vec::with_capacity(items.len());

    for item in items {
        let json::Value::String(raw) = item.value() else {
            return None;
        };

        days.push(weekday::Weekday::from_canonical(raw.as_unescaped_str())?);
    }

    days.sort_unstable();
    days.dedup();

    let names: Vec<&str> = days.iter().map(|day| day.canonical()).collect();

    Some(Edit::replace(
        element.id(),
        Json::string_array(&names),
        Meaning::Preserves,
    ))
}

/// The edit that replaces the tariff element `element` with one element for each
/// dimension among its price components.
///
/// Each new element is a copy of the element's source with only its `price_components` rewritten,
/// so restrictions, extra fields and layout carry over. The new elements follow the order in which
/// each dimension first appears among the components, and the components of one dimension keep
/// the order they were written in.
///
/// Returns `None` when the element prices fewer than two dimensions, or when the split can't read
/// the components exactly: a repeated `price_components` key, or a component without a `type`
/// written as one of the four dimension names in upper case. The split doesn't guess. If another
/// fix makes the components readable, a later linting pass proposes the split again.
fn split_by_dimension(element: &json::Element<'_>) -> Option<Edit> {
    let source = element.source();
    let fields = element.as_object_fields()?;

    // With two `price_components` keys, the split can't tell which array to split. The fix
    // for the repeated key removes the earlier one, and the split waits for that.
    let mut price_components = fields
        .iter()
        .filter(|field| field.key().eq_any_escape_aware(&["price_components"]));
    let components_field = price_components.next()?;

    if price_components.next().is_some() {
        return None;
    }

    let components_array = components_field.element();
    let components = components_array.value().as_array()?;
    let first_component = components.first()?;
    let last_component = components.last()?;

    // Each dimension with the components that price it, in the order the dimension first
    // appears. OCPI 2.1.1 and 2.2.1 name the same four dimensions, so the 2.2.1 names serve both.
    let mut dimensions: Vec<(schema::v221::TariffDimensionType, Vec<&str>)> = Vec::new();

    for component in components {
        let dimension = dimension_of(component)?;
        let text = slice(source, component.span().start, component.span().end);
        let existing = dimensions.iter_mut().find(|(seen, _)| *seen == dimension);

        match existing {
            Some((_, texts)) => texts.push(text),
            None => dimensions.push((dimension, vec![text])),
        }
    }

    if dimensions.len() < 2 {
        return None;
    }

    let element_span = element.span();
    let array_span = components_array.span();
    let before_array = slice(source, element_span.start, array_span.start);
    let after_array = slice(source, array_span.end, element_span.end);
    let array_open = slice(source, array_span.start, first_component.span().start);
    let array_close = slice(source, last_component.span().end, array_span.end);
    let component_separator = item_separator(first_component);

    let mut items = Vec::with_capacity(dimensions.len());

    for (_, texts) in &dimensions {
        let joined = texts.join(&component_separator);
        items.push(format!(
            "{before_array}{array_open}{joined}{array_close}{after_array}"
        ));
    }

    let items = Json::items(&items, &item_separator(element));

    Some(Edit::replace_with_items(
        element.id(),
        items,
        Meaning::Preserves,
    ))
}

/// The dimension of the price component `component`, read from its `type`.
///
/// Returns `None` unless the component has exactly one `type` field, holding one of the dimension
/// names in upper case.
fn dimension_of(component: &json::Element<'_>) -> Option<schema::v221::TariffDimensionType> {
    let fields = component.as_object_fields()?;

    // Parsing decodes the escapes in a key, so `typ\u0065` is a second `type` field to
    // pricing. Comparing the keys as written would find only one, and the split could then group
    // the component under a dimension that pricing doesn't read.
    let mut types = fields
        .iter()
        .filter(|field| field.key().eq_any_escape_aware(&["type"]));
    let type_field = types.next()?;

    if types.next().is_some() {
        return None;
    }

    let json::Value::String(raw) = type_field.element().value() else {
        return None;
    };

    schema::v221::TariffDimensionType::from_canonical(raw.as_unescaped_str())
}

/// The text between the array item `item` and its neighbor: a comma and the whitespace
/// around it. Joining new items with it lays them out like the rest of the array.
///
/// `item_separator` takes the separator before the item when there is one. The first item has
/// none, so it takes the one after it. The only item in an array has neither, so it gets a comma
/// followed by the whitespace between the `[` and the item.
fn item_separator(item: &json::Element<'_>) -> String {
    let source = item.source();
    let span = item.span();
    let before = slice(source, 0, span.start);
    let after = slice(source, span.end, source_len(source));
    let before_trimmed = before.trim_end_matches(is_json_whitespace);

    // Each separator is sliced by length. `strip_prefix` with the text before it would
    // compare the whole document up to the item, once for every element the fix splits.
    if let Some(rest) = before_trimmed.strip_suffix(',') {
        let previous = rest.trim_end_matches(is_json_whitespace);
        return before.get(previous.len()..).unwrap_or(",").to_owned();
    }

    let after_trimmed = after.trim_start_matches(is_json_whitespace);

    if let Some(rest) = after_trimmed.strip_prefix(',') {
        let next = rest.trim_start_matches(is_json_whitespace);
        let separator_len = after.len().saturating_sub(next.len());
        return after.get(..separator_len).unwrap_or(",").to_owned();
    }

    let indent = before.get(before_trimmed.len()..).unwrap_or("");
    format!(",{indent}")
}

/// Whether `c` is one of the four characters JSON allows as whitespace.
fn is_json_whitespace(c: char) -> bool {
    matches!(c, ' ' | '\t' | '\n' | '\r')
}

/// Removes every rename that would change what the document means and whose new key
/// would clash with another key in the same object. The doc of `refused_renames` lists the ways
/// a key can clash.
///
/// `lint::fix::pass_edits` runs this on the schema warnings' edits and the lint warnings'
/// edits joined, because a rename from one set can write the same key as a rename from the
/// other.
///
/// Returns a [`Refused`] for each rename it removes, naming the field the rename would
/// have rewritten and the warning that proposed it.
pub(crate) fn refuse_clashing_renames(
    doc: &json::Document<'_>,
    proposed: &mut Vec<Proposed>,
) -> Vec<Refused> {
    let refused_values = refused_renames(doc, proposed);
    let extracted = proposed.extract_if(.., |proposed| {
        let Change::Rename { elem, key: _ } = &proposed.edit.change else {
            return false;
        };
        proposed.edit.meaning == Meaning::Changes && refused_values.contains(elem)
    });

    let mut refused = Vec::new();

    for Proposed { edit, warning } in extracted {
        let Change::Rename { elem, key: _ } = edit.change else {
            continue;
        };
        let Some(element) = doc.element(elem) else {
            continue;
        };

        refused.push(Refused {
            path: element.path(),
            warning,
            reason: Refusal::RenameClashes,
        });
    }

    refused
}

/// Finds the renames that `refuse_clashing_renames` refuses for this pass. Returns the id of each
/// refused rename's value, because a rename is anchored on the value of the field it renames.
///
/// Only a rename marked `Meaning::Changes` is ever refused. A rename that keeps the meaning,
/// such as the fix for an escaped field name, always goes ahead.
///
/// The checks below ignore any field that this pass removes, because that field's key is gone
/// once the pass is applied.
///
/// - **Another rename writes the same key in the same object.** Two misspelled fields can both be
///   nearest to one absent field, as `dayOfWeek` and `DayOfWeek` are to `day_of_week`. Applying
///   both renames would repeat the key. Nothing says which of the two the author meant, so
///   both are refused. A `Meaning::Preserves` rename is never refused, so when one shares the
///   key with a `Changes` rename, only the `Changes` rename is refused.
/// - **The object keeps a field with that key.** A `null` field counts as absent in the schema
///   walk, so `dayOfWeek` is reported as a misspelling beside `"day_of_week": null`. When the pass
///   doesn't remove that `null`, the rename would write a key the object still holds, and parsing
///   would read the later of the two.
/// - **The same value has another rename.** A name both escaped and misspelled, such as
///   `"day\u004ffWeek"`, gets the escape fix's rename as well. [`apply`] rejects two renames of
///   one key that write different text. The escape fix's rename goes first, and the next pass
///   proposes the misspelling's rename on its own.
fn refused_renames(doc: &json::Document<'_>, proposed: &[Proposed]) -> BTreeSet<json::ElemId> {
    let mut removed: BTreeSet<json::ElemId> = BTreeSet::new();
    let mut renames_of_value: BTreeMap<json::ElemId, usize> = BTreeMap::new();
    let mut renames_by_key: BTreeMap<(json::ElemId, &str), usize> = BTreeMap::new();

    for Proposed { edit, warning: _ } in proposed {
        match &edit.change {
            Change::Remove(elem) => {
                removed.insert(*elem);
            }
            Change::Rename { elem, key: _ } => {
                let count = renames_of_value.entry(*elem).or_default();
                *count = count.saturating_add(1);
            }
            Change::Replace { elem: _, json: _ }
            | Change::ReplaceWithItems { elem: _, items: _ } => {}
        }
    }

    // The renames that would change what the document means. Each one comes as the id of
    // the renamed field's value, the id of the object holding that field and the new key. A
    // rename of a field that this pass removes is left out.
    let mut changing: Vec<(json::ElemId, json::ElemId, &Json)> = Vec::new();

    for Proposed { edit, warning: _ } in proposed {
        let Change::Rename { elem, key } = &edit.change else {
            continue;
        };
        if removed.contains(elem) {
            continue;
        }
        let Some(object) = doc.object_of_field(*elem) else {
            continue;
        };

        let count = renames_by_key.entry((object, key.as_str())).or_default();
        *count = count.saturating_add(1);

        if edit.meaning == Meaning::Changes {
            changing.push((*elem, object, key));
        }
    }

    let mut refused = BTreeSet::new();

    for (elem, object, key) in changing {
        let shares_key = renames_by_key
            .get(&(object, key.as_str()))
            .map(|count| *count > 1)
            .unwrap_or(false);
        let renamed_twice = renames_of_value
            .get(&elem)
            .map(|count| *count > 1)
            .unwrap_or(false);
        if shares_key || renamed_twice {
            refused.insert(elem);
            continue;
        }

        // One scan per rename would make this quadratic in the object's size.
        // The check above leaves at most one rename per key.
        // Each such key is a name the schema lists for the object.
        // So the schema caps the scans per object, not the input.
        let Some(fields) = doc
            .element(object)
            .and_then(json::Element::as_object_fields)
        else {
            continue;
        };

        // A schema name needs no escapes, so the text between the key's quotes is the
        // name the rename writes.
        let name = key.as_str().trim_matches('"');

        let key_kept = fields.iter().any(|field| {
            let value = field.element().id();
            let field_key = field.element().key().map(json::RawStr::to_key);

            value != elem
                && !removed.contains(&value)
                && field_key.is_some_and(|field_key| field_key.name() == Some(name))
        });
        if key_kept {
            refused.insert(elem);
        }
    }

    refused
}

/// Drops each replacement in `edits` whose element encloses another edit.
///
/// `edits` holds only the edits the pass applies. A replacement dropped for an edit the pass
/// doesn't apply, such as one held back for changing what the tariff means, would never be
/// applied either.
///
/// [`apply`] rejects such a pair as an [`Error::Conflict`], because the replacement's text is
/// written without the inner edit and would discard it. The replacement's fix proposes it again
/// once the inner edit is applied, so the fixing loop applies the two over successive passes.
///
/// In each example below, the carets on an `edit` line mark the span that a fix's edit rewrites.
/// A `pass` line names the edits that pass applies and shows the document it writes.
///
/// ```text
/// document:  {"a": {"b": 1, "c": 2}}
/// edit 1:          ^^^^^^^^^^^^^^^^   replace with {"b": 9}
/// edit 2:                   ^^^^^^    remove
///
/// pass 1 applies edit 2 and drops edit 1:  {"a": {"b": 1}}
/// pass 2 applies edit 1, proposed again:   {"a": {"b": 9}}
/// ```
///
/// A replacement is never dropped for an edit of its own element. A rename and a replacement of
/// one field rewrite different spans, so both go in one pass:
///
/// ```text
/// document:  {"a": 1}
/// edit 1:     ^^^      rename to `b`
/// edit 2:          ^   replace with 2
///
/// pass 1 applies both:  {"b": 2}
/// ```
///
/// Only a replacement is ever dropped. A removal erases every edit inside it, so `apply` makes
/// a removal and any edit it encloses in one pass:
///
/// ```text
/// document:  {"a": {"b": 1}}
/// edit 1:     ^^^^^^^^^^^^^   remove
/// edit 2:                ^    replace with 2
///
/// pass 1 applies both, and edit 1 erases edit 2:  {}
/// ```
///
/// Element spans nest or are disjoint, so the innermost edit of a nested set is never dropped.
/// The result is therefore empty only when `edits` is. An empty result would end the fixing loop
/// with every fix reported applied, while a replacement still waited.
pub(crate) fn defer_enclosing_replacements(
    doc: &json::Document<'_>,
    edits: Vec<Edit>,
) -> Result<Vec<Edit>, Error> {
    let mut spans = Vec::with_capacity(edits.len());

    for edit in &edits {
        let elem = edit.change.elem();
        let element = doc.element(elem).ok_or(Error::UnknownElement(elem))?;
        spans.push(element.span());
    }

    // No two elements share a start offset, so an edit starting where a replacement starts
    // is an edit of the same element. Spans nest or are disjoint, so the first edit
    // starting after the replacement starts lies inside it exactly when it starts before the
    // replacement ends.
    //
    // document:  {"a": {"b": 1, "c": 2}, "d": 3}
    // edit 1:          ^^^^^^^^^^^^^^^^           replace the value of `a`, starts at 6
    // edit 2:          ^^^^^^^^^^^^^^^^           rename `a`, starts at 6
    // edit 3:                        ^            remove `c`, starts at 20
    // edit 4:                                 ^   replace the value of `d`, starts at 29
    //
    // Edit 1 ends at 22. The first start after 6 is 20, which is before 22, so edit 1 encloses
    // edit 3 and is dropped. Edit 2 also starts at 6, and the lookup passes over it as an edit
    // of the same element. No edit starts after 29, so edit 4 is kept.
    //
    // A typical pass proposes a few edits. The input cap allows a 5 MB tariff, though, which
    // could propose tens of thousands. Comparing each replacement with every edit would then
    // cost `replacements * edits` comparisons per pass.
    let mut starts: Vec<u32> = spans.iter().map(|span| span.start).collect();
    starts.sort_unstable();

    let mut kept = Vec::with_capacity(edits.len());

    for (edit, span) in edits.into_iter().zip(&spans) {
        let replaces = match edit.change {
            Change::Replace { elem: _, json: _ }
            | Change::ReplaceWithItems { elem: _, items: _ } => true,
            Change::Remove(_) | Change::Rename { elem: _, key: _ } => false,
        };

        if !replaces {
            kept.push(edit);
            continue;
        }

        let next = starts.partition_point(|start| *start <= span.start);
        let encloses_another = starts.get(next).is_some_and(|start| *start < span.end);

        if !encloses_another {
            kept.push(edit);
        }
    }

    Ok(kept)
}

/// The edit that writes the name of the field holding `element` without escapes. The edit
/// rewrites only the name and leaves the field's value as written.
///
/// Returns `None` when `element` isn't the value of an object field, or when JSON can't write the
/// decoded name without an escape.
fn plain_field_name(element: &json::Element<'_>) -> Option<Edit> {
    let raw = element.key()?;
    let json::Key::Decoded(name) = raw.to_key() else {
        return None;
    };
    let key = Json::string(&name);

    // JSON can write a `"` or a `\` in a name only as an escape. The walk raises the
    // warning for any escape, so it would raise the warning again on the renamed field. The next
    // pass would propose a rename to the name the field already has, and the fixing loop would
    // repeat it until it reached its limit.
    if key.as_str().contains('\\') {
        return None;
    }

    Some(Edit::rename(element.id(), key, Meaning::Preserves))
}

/// Apply `edits` to the source of `doc` and return the edited JSON.
///
/// The output is re-parsed before it is returned. A replacement payload is one JSON value
/// by construction, and a value is legal wherever another one was. The payload of
/// [`Change::ReplaceWithItems`] is several values, and the split builds that change only for an
/// array item, where a run of items is legal. So the re-parse should not be able to fail.
/// It is kept as a backstop on the splicing, and on the payload builders in a release build
/// where their own assertion is compiled out.
///
/// Edits interact, and the rules are not symmetric:
///
/// | Case | Outcome |
/// |---|---|
/// | Two removals of the same element | Removed once |
/// | A removal of an element inside another removed element | The ancestor's span covers it |
/// | A replacement of an element that is also removed | The removal wins |
/// | A replacement of an element inside a removed element | The removal wins |
/// | Two replacements of the same element, same text | Replaced once |
/// | Two replacements of the same element, differing text | [`Error::Duplicate`] |
/// | A replacement of an element inside another replaced element | [`Error::Conflict`] |
/// | A removal of an element inside a replaced element | [`Error::Conflict`] |
/// | A replacement with several items of the root or a field value | [`Error::Internal`] |
/// | Two renames of the same field, same text | Renamed once |
/// | Two renames of the same field, differing text | [`Error::Duplicate`] |
///
/// A rename rewrites a field's key, and `apply` treats it as a replacement of the key.
/// The fixes for [`schema::Warning::FieldNameContainsEscapeCodes`] and
/// [`schema::Warning::MisspelledField`] both propose renames. A rename and a replacement of the
/// same field both apply, because the key and the value don't overlap.
///
/// A removal makes any edit inside it redundant, because the bytes go away either way. Nothing an
/// inner edit intended is lost. A replacement doesn't make an inner edit redundant. Its payload was
/// written without knowledge of the inner edit, so applying it would discard that edit silently.
///
/// Two replacements asking for the same text are one edit proposed twice, not a disagreement:
/// a `day_of_week` list can be both unsorted and repeating, and the same sorted list resolves
/// either warning. Only replacements that disagree about the text are an error.
pub(crate) fn apply(doc: &json::Document<'_>, edits: &[Edit]) -> Result<String, Error> {
    let splices = resolve(doc, edits)?;
    let edited = splice(doc.source(), &splices)?;

    check_parses(&edited)?;

    Ok(edited)
}

/// A single change to one element of a document.
///
/// Opaque, and produced only by [`proposed_edits`]. Which edit resolves a warning is this crate's
/// decision. A caller decides which edits to apply in two ways. It can filter the
/// [`warning::Set`] before calling [`proposed_edits`], which leaves out every edit for the warnings it
/// removed. An `Edit` doesn't record which warning asked for it, so that is the only way to choose
/// by warning. A caller can also leave out the edits whose [`Edit::meaning`] it doesn't want.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Edit {
    change: Change,
    meaning: Meaning,
}

impl Edit {
    /// Remove the element from its parent, along with the separator that joined it to its
    /// siblings.
    pub(crate) fn remove(elem: json::ElemId, meaning: Meaning) -> Self {
        Self {
            change: Change::Remove(elem),
            meaning,
        }
    }

    /// Replace the element's value with `json`, leaving an object field's key in place.
    pub(crate) fn replace(elem: json::ElemId, json: Json, meaning: Meaning) -> Self {
        Self {
            change: Change::Replace { elem, json },
            meaning,
        }
    }

    /// Replace the key of the object field whose value is `elem` with `key`, leaving the value in
    /// place.
    pub(crate) fn rename(elem: json::ElemId, key: Json, meaning: Meaning) -> Self {
        Self {
            change: Change::Rename { elem, key },
            meaning,
        }
    }

    /// Replace the array item `elem` with the items in `items`.
    pub(crate) fn replace_with_items(elem: json::ElemId, items: Json, meaning: Meaning) -> Self {
        Self {
            change: Change::ReplaceWithItems { elem, items },
            meaning,
        }
    }

    /// Whether the document means the same under OCPI after this edit.
    pub fn meaning(&self) -> Meaning {
        self.meaning
    }
}

/// Whether a document means the same under OCPI after an [`Edit`].
///
/// The answer is about what the document says, not about what a session costs. Removing a `null`
/// element is [`Meaning::Preserves`], because a `null` has no meaning in OCPI, even when the
/// tariff can't be priced until the `null` is gone. An edit that supplies what the author probably
/// meant is [`Meaning::Changes`], because the document as written doesn't say it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Meaning {
    /// The document means the same under OCPI after the edit.
    Preserves,

    /// The document means something else under OCPI after the edit.
    Changes,
}

/// What an [`Edit`] does to its element.
#[derive(Clone, Debug, Eq, PartialEq)]
enum Change {
    /// Remove the element from its parent, along with the separator that joined it to its
    /// siblings.
    Remove(json::ElemId),

    /// Replace the element's value with `json`, leaving an object field's key in place.
    Replace {
        /// The element whose value is rewritten.
        elem: json::ElemId,

        /// The value taking its place.
        json: Json,
    },

    /// Replace the key of the object field whose value is `elem`, leaving the value in place.
    Rename {
        /// The value of the field whose key is rewritten.
        elem: json::ElemId,

        /// The key to write, as a quoted JSON string such as `"min_kwh"`.
        key: Json,
    },

    /// Replace the array item `elem` with several items.
    ///
    /// `items` is several JSON values joined by commas, which only an array has room for.
    /// Written over the root or a field value, the text isn't JSON, so the re-parse in [`apply`]
    /// returns [`Error::Internal`].
    ReplaceWithItems {
        /// The array item replaced.
        elem: json::ElemId,

        /// The items taking its place, built by [`Json::items`].
        items: Json,
    },
}

impl Change {
    /// The element the change names: the element removed or replaced, or the value of the field
    /// renamed.
    fn elem(&self) -> json::ElemId {
        match self {
            Self::Remove(elem)
            | Self::Replace { elem, json: _ }
            | Self::Rename { elem, key: _ }
            | Self::ReplaceWithItems { elem, items: _ } => *elem,
        }
    }
}

/// JSON text to splice into a document, represented as a `String`.
///
/// Every constructor but [`Json::items`] builds one JSON value. That text is spliced in place of
/// an element's own span or of a field's quoted key, so it holds no `"key":` prefix and no comma.
/// Any JSON value is a valid replacement for an element, from a JSON spec point of view.
/// A key has to be a quoted JSON string, so every rename is given text built by `Json::string`.
///
/// Each of those constructors takes the content to write and builds the text itself,
/// escaping what it writes, so the text is one valid JSON value by construction.
///
/// [`Json::items`] joins items copied from the document's own source with commas.
/// Only an array item has room for that text.
///
/// No constructor checks the text against the OCPI schema for the position it lands in, so
/// [`apply`] will happily write a number where an array was.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Json(String);

impl Json {
    /// A JSON array holding each of `values` as a JSON string.
    ///
    /// The quoting and escaping happen here, so a caller passes the string content it wants
    /// written rather than JSON source: a value holding a quote or a backslash arrives in the
    /// document as that same one character.
    pub(crate) fn string_array(values: &[&str]) -> Self {
        let mut json = String::from("[");

        for (index, value) in values.iter().enumerate() {
            if index > 0 {
                json.push_str(", ");
            }

            push_json_string(&mut json, value);
        }

        json.push(']');

        Self::built(json)
    }

    /// A JSON string.
    ///
    /// `value` is quoted and escaped, so a caller passes the string content it wants
    /// written rather than JSON source.
    pub(crate) fn string(value: &str) -> Self {
        let mut json = String::new();

        push_json_string(&mut json, value);

        Self::built(json)
    }

    /// Several JSON values, written as `items` joined by `separator`.
    ///
    /// Each item is copied from the source of the document it is spliced into, and `separator`
    /// is a comma with the whitespace around it. The text is the inside of an array rather than
    /// one value, so only [`Change::ReplaceWithItems`] holds it.
    pub(crate) fn items(items: &[String], separator: &str) -> Self {
        let text = items.join(separator);

        debug_assert!(
            is_one_json_value(&format!("[{text}]")),
            "`fix` built items that are not JSON values joined by commas: `{text}`"
        );

        Self(text)
    }

    /// The text this value will be written as, exactly as it was built.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Take text built by a constructor above, holding it to being a single JSON value.
    ///
    /// Every constructor ends here, so the check covers all of them. It is a `debug_assert`
    /// rather than a returned error because the producer is always this crate. Text that is not
    /// one JSON value is a bug in the constructor that built it, not something a caller passed in
    /// or can act on. A release build still cannot write a corrupt document, since [`apply`]
    /// re-parses the whole result and reports [`Error::Internal`]; what the assertion adds is the
    /// producer's own stack rather than that after-the-fact report.
    fn built(text: String) -> Self {
        debug_assert!(
            is_one_json_value(&text),
            "`fix` built text that is not a single JSON value: `{text}`"
        );

        Self(text)
    }

    /// Take `text` verbatim, for tests needing a payload shape no constructor above builds.
    #[cfg(test)]
    fn raw(text: &str) -> Self {
        Self::built(text.to_owned())
    }
}

impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Write `value` into `json` as a quoted JSON string.
fn push_json_string(json: &mut String, value: &str) {
    json.push('"');

    for c in value.chars() {
        match c {
            '"' => json.push_str(r#"\""#),
            '\\' => json.push_str(r"\\"),
            '\n' => json.push_str(r"\n"),
            '\r' => json.push_str(r"\r"),
            '\t' => json.push_str(r"\t"),
            '\u{8}' => json.push_str(r"\b"),
            '\u{c}' => json.push_str(r"\f"),

            // JSON forbids a literal control character inside a string, and the ones above are
            // the only control characters with a shorthand, so the rest need the `\u` form.
            c if c < ' ' => {
                let code = u32::from(c);

                json.push_str(r"\u00");
                json.push(hex_digit(code >> 4));
                json.push(hex_digit(code & 0xf));
            }

            c => json.push(c),
        }
    }

    json.push('"');
}

/// The lower-case hex digit for `nibble`, which every caller here has already masked to one.
fn hex_digit(nibble: u32) -> char {
    char::from_digit(nibble, 16).unwrap_or('0')
}

/// Whether `text` is exactly one JSON value, which is what a replacement has room for.
fn is_one_json_value(text: &str) -> bool {
    let Ok(checked) = string::ReasonableLen::new(text) else {
        return false;
    };

    json::parse(checked).is_ok()
}

/// Why a set of edits could not be applied.
///
/// Most of these say the edits asked for something contradictory, or named an element that is
/// not there, and the caller can act on them. [`Error::Internal`] and [`Error::OverlappingSpans`]
/// are different in kind: no set of edits can ask for either, so reaching one is a bug in this
/// module rather than anything the caller did. They are returned rather than panicked on because
/// the caller is about to write the result over someone's tariff, and refusing to is better than
/// crashing in their process or, worse, handing back JSON that has been corrupted.
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
    /// More than one replacement, or more than one rename, targets this element, and they disagree
    /// about the text.
    Duplicate(json::ElemId),

    /// Applying `outer` would silently discard the edit to `inner`, which sits inside it.
    Conflict {
        /// The replaced element.
        outer: json::ElemId,

        /// The element edited inside it.
        inner: json::ElemId,
    },

    /// The document has no element with this id.
    UnknownElement(json::ElemId),

    /// The edits were made from a different document than the one they are applied to. An edit
    /// renames the field holding this element, but in this document the element is the root or an
    /// item of an array, so it has no key.
    NotAField(json::ElemId),

    /// The removals could not be resolved to spans.
    Removal(json::RemovalError),

    /// Splicing produced source that is no longer valid JSON, which is a bug in this
    /// module.
    ///
    /// A replacement carries a payload that is one JSON value by construction, and a
    /// value is legal wherever another value was. A payload of several items is built only
    /// for an array item. So no payload should cause this. What is left is the
    /// removal spans and the splice itself, so reaching this means one of those is wrong - or, in
    /// a release build, that a payload builder is, since its own assertion is compiled out.
    Internal(json::Error),

    /// The spliced source exceeds the maximum size deemed reasonable.
    ///
    /// A caller can reach this: replacements longer than what they stand in for can take a
    /// document that was within the limit past it. This is the only size bound in the module, and
    /// it is on the whole output, since a bound on one payload would not catch that.
    OutputTooLarge,

    /// Two resolved spans overlap, so erasing both would corrupt the output. No set of edits
    /// should reach this; it means resolution itself is wrong.
    OverlappingSpans {
        /// The span that starts first.
        first: json::Span,

        /// The span that starts inside it.
        second: json::Span,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Duplicate(id) => {
                write!(f, "More than one edit rewrites the element with id `{id}`.")
            }
            Self::Conflict { outer, inner } => write!(
                f,
                "Replacing the element with id `{outer}` would discard the edit to the element with id `{inner}` inside it."
            ),
            Self::UnknownElement(id) => write!(f, "The document has no element with id `{id}`."),
            Self::NotAField(id) => write!(
                f,
                "The edits were made from a different document than the one they are applied to. The element with id `{id}` is the root or an item of an array, so it has no key to rename."
            ),
            Self::Removal(error) => write!(f, "{error}"),
            Self::Internal(error) => write!(
                f,
                "The edits spliced into JSON that does not parse, which is a bug in `fix`: {error}"
            ),
            Self::OutputTooLarge => write!(
                f,
                "The edited JSON exceeds the reasonable maximum `{} MB`.",
                string::ReasonableLen::FACTOR
            ),
            Self::OverlappingSpans { first, second } => write!(
                f,
                "The spans `{first:?}` and `{second:?}` overlap, so the edits can not both be applied."
            ),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Removal(error) => Some(error),
            Self::Internal(error) => Some(error),
            Self::Duplicate(_)
            | Self::Conflict { outer: _, inner: _ }
            | Self::UnknownElement(_)
            | Self::NotAField(_)
            | Self::OutputTooLarge
            | Self::OverlappingSpans {
                first: _,
                second: _,
            } => None,
        }
    }
}

/// One resolved edit: the span of source it covers and the text that takes its place.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Splice<'edit> {
    span: json::Span,

    /// Empty for a removal.
    text: &'edit str,
}

/// A replacement that has been resolved to the span it rewrites.
#[derive(Clone, Copy, Debug)]
struct Replacement<'edit> {
    elem: json::ElemId,
    span: json::Span,
    text: &'edit str,
}

/// Resolve `edits` into the spans to rewrite, sorted by start offset.
fn resolve<'edit>(
    doc: &json::Document<'_>,
    edits: &'edit [Edit],
) -> Result<Vec<Splice<'edit>>, Error> {
    let mut removals: BTreeSet<json::ElemId> = BTreeSet::new();
    let mut replacements: BTreeMap<json::ElemId, &'edit str> = BTreeMap::new();
    let mut renames: BTreeMap<json::ElemId, &'edit str> = BTreeMap::new();

    for edit in edits {
        match &edit.change {
            Change::Remove(id) => {
                removals.insert(*id);
            }
            // A split rewrites the span of the array item it replaces, as a replacement
            // rewrites the span of its element. So both go in the `replacements` map, and two
            // edits of one element that disagree on its text are a `Duplicate`.
            Change::Replace { elem, json: text }
            | Change::ReplaceWithItems { elem, items: text } => {
                let earlier = replacements.insert(*elem, text.as_str());

                if earlier.is_some_and(|earlier| earlier != text.as_str()) {
                    return Err(Error::Duplicate(*elem));
                }
            }
            // A rename and a replacement of the same field share the id of the field's value, but
            // they rewrite different spans. Sharing the `replacements` map would make the two
            // collide as a `Duplicate`, so renames are kept in a map of their own. Only two renames
            // with different keys are a `Duplicate`.
            Change::Rename { elem, key } => {
                let earlier = renames.insert(*elem, key.as_str());

                if earlier.is_some_and(|earlier| earlier != key.as_str()) {
                    return Err(Error::Duplicate(*elem));
                }
            }
        }
    }

    let removed = doc.removal_spans(&removals).map_err(Error::Removal)?;
    let replaced = resolve_replacements(doc, &replacements, &renames, &removals, &removed)?;

    check_no_removal_inside_a_replacement(doc, &removals, &replaced)?;

    let mut splices: Vec<Splice<'edit>> = Vec::new();

    for span in removed {
        splices.push(Splice { span, text: "" });
    }

    for replacement in replaced {
        splices.push(Splice {
            span: replacement.span,
            text: replacement.text,
        });
    }

    splices.sort_by_key(|splice| splice.span);

    Ok(splices)
}

/// Resolve each replacement and each rename to its span, dropping each one that a removal makes
/// redundant. A removal erases the span of every edit inside the removed element, so such an edit
/// would change nothing.
///
/// A rename becomes a replacement of the span of the field's key. The checks that follow treat it
/// like any other replacement. So replacing an element that contains the field is a conflict, just
/// as replacing an element that contains another replacement is.
fn resolve_replacements<'edit>(
    doc: &json::Document<'_>,
    replacements: &BTreeMap<json::ElemId, &'edit str>,
    renames: &BTreeMap<json::ElemId, &'edit str>,
    removals: &BTreeSet<json::ElemId>,
    removed: &[json::Span],
) -> Result<Vec<Replacement<'edit>>, Error> {
    let mut resolved: Vec<Replacement<'edit>> = Vec::new();

    for (elem, text) in renames {
        if removals.contains(elem) {
            continue;
        }

        doc.element(*elem).ok_or(Error::UnknownElement(*elem))?;
        let span = doc.key_span(*elem).ok_or(Error::NotAField(*elem))?;

        // A removal erases the bytes of this key, so renaming it would change nothing.
        if enclosing(removed, |erased| *erased, span).is_some() {
            continue;
        }

        resolved.push(Replacement {
            elem: *elem,
            span,
            text,
        });
    }

    for (elem, text) in replacements {
        if removals.contains(elem) {
            continue;
        }

        let element = doc.element(*elem).ok_or(Error::UnknownElement(*elem))?;
        let span = element.span();

        // A removal erases the bytes of this element, so replacing it would change nothing.
        if enclosing(removed, |erased| *erased, span).is_some() {
            continue;
        }

        resolved.push(Replacement {
            elem: *elem,
            span,
            text,
        });
    }

    resolved.sort_by_key(|replacement| replacement.span);

    check_no_nested_replacement(&resolved)?;

    Ok(resolved)
}

/// Reject a replacement that sits inside another replacement.
///
/// Element spans nest or are disjoint, and no two elements share a start offset, so sorting
/// by span puts an enclosing replacement before the one it encloses.
fn check_no_nested_replacement(replaced: &[Replacement<'_>]) -> Result<(), Error> {
    let mut outer: Option<Replacement<'_>> = None;

    for replacement in replaced {
        if let Some(open) = outer
            && replacement.span.start < open.span.end
        {
            return Err(Error::Conflict {
                outer: open.elem,
                inner: replacement.elem,
            });
        }

        outer = Some(*replacement);
    }

    Ok(())
}

/// Reject a removal that sits inside a replacement.
///
/// `replaced` must be sorted by span with no two spans overlapping, as it is once
/// [`check_no_nested_replacement`] has accepted it, because [`enclosing`] relies on that.
fn check_no_removal_inside_a_replacement(
    doc: &json::Document<'_>,
    removals: &BTreeSet<json::ElemId>,
    replaced: &[Replacement<'_>],
) -> Result<(), Error> {
    for id in removals {
        let element = doc.element(*id).ok_or(Error::UnknownElement(*id))?;
        let span = element.span();
        let outer = enclosing(replaced, |replacement| replacement.span, span);

        if let Some(replacement) = outer {
            return Err(Error::Conflict {
                outer: replacement.elem,
                inner: *id,
            });
        }
    }

    Ok(())
}

/// Rewrite `source` by replacing each span with its text.
fn splice(source: &str, splices: &[Splice<'_>]) -> Result<String, Error> {
    let mut out = String::with_capacity(source.len());
    let mut pos: u32 = 0;

    for splice in splices {
        if splice.span.start < pos {
            let previous = splices
                .iter()
                .find(|earlier| earlier.span.end == pos)
                .map(|earlier| earlier.span)
                .unwrap_or_default();

            return Err(Error::OverlappingSpans {
                first: previous,
                second: splice.span,
            });
        }

        out.push_str(slice(source, pos, splice.span.start));
        out.push_str(splice.text);
        pos = splice.span.end;
    }

    out.push_str(slice(source, pos, source_len(source)));

    Ok(out)
}

/// Return the item of `sorted` whose span covers every byte of `inner`, if one does.
///
/// `sorted` must be sorted by span start, with no two spans overlapping. Then only the last span
/// starting at or before `inner` can cover it:
///
/// ```text
/// sorted:  [----a----)    [------b------)   [--c--)
/// inner:                    [-----)
///                         ^ b, the last start <= inner.start
/// d:                         [--)   d would start inside b, so d would overlap b
/// ```
///
/// Checking every item would cost one comparison per pair of spans, quadratic in [`resolve`] for
/// a tariff whose elements each have a field to remove and a value to rewrite.
fn enclosing<T>(sorted: &[T], span_of: impl Fn(&T) -> json::Span, inner: json::Span) -> Option<&T> {
    let after = sorted.partition_point(|item| span_of(item).start <= inner.start);
    let index = after.checked_sub(1)?;
    let candidate = sorted.get(index)?;

    if !contains(span_of(candidate), inner) {
        return None;
    }

    Some(candidate)
}

/// Return true if `outer` covers every byte of `inner`.
fn contains(outer: json::Span, inner: json::Span) -> bool {
    inner.start >= outer.start && inner.end <= outer.end
}

/// Re-parse edited JSON, so a corrupted splice is reported rather than written.
fn check_parses(json: &str) -> Result<(), Error> {
    let json = string::ReasonableLen::new(json).map_err(|_e| Error::OutputTooLarge)?;

    json::parse(json).map_err(Error::Internal)?;

    Ok(())
}

/// The byte range `start..end` of `source`.
///
/// Every span comes from the parser that read `source`, so it always lands on a character
/// boundary; an out of range span yields an empty `&str` rather than a panic.
fn slice(source: &str, start: u32, end: u32) -> &str {
    let Ok(start) = usize::try_from(start) else {
        return "";
    };
    let Ok(end) = usize::try_from(end) else {
        return "";
    };

    source.get(start..end).unwrap_or("")
}

/// The length of `source` as a span offset.
fn source_len(source: &str) -> u32 {
    u32::try_from(source.len()).unwrap_or(u32::MAX)
}