enshwick 1.0.0-alpha.3

The Enshwick Loader's modding API for Enshrouded: the one crate mods are written against
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
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
//! Typed mod settings, in `mod-configs/<id>.toml` beside the game.
//!
//! `#[derive(Config)]` writes the file from the type and describes every
//! field in a [`Schema`]: when it takes effect ([`Stage`]), the values it
//! accepts, its documentation and the text key a translation of it uses. The
//! loader reads the schema to answer `enshwick config` on the console and to check values before it
//! writes them; a settings menu builds on the same description.

use serde::{Deserialize, Serialize};

/// A mod's settings type: parsed from its file, which is written from the
/// type on first start.
///
/// Derive it with `#[derive(Config)]` together with serde's `Deserialize` and
/// `Serialize` and `Default`; doc comments become the file's comments. Field
/// attributes:
///
/// - a stage, one of `#[config(startup)]` (applied when a world loads),
///   `#[config(runtime)]` (the default: applied while the game runs),
///   `#[config(client)]` (each player's own, never sent to or from a server),
///   `#[config(sync)]` (the server's value applies on its joined clients) and
///   `#[config(restart)]` (read once at start; a change waits for the next
///   start of the game);
/// - `#[config(startup, sync)]`, the one pair of stages a field may name:
///   applied when a world loads, and a joined client runs with the server's
///   value, which stays the same while the world runs;
/// - `range = a..=b` (also `a..` or `..=b`) for numbers and `choices = [..]`
///   for values from a list. The console and the Mods screen refuse a value
///   outside them; a file that holds a number outside its range, a list's
///   element too, still reads, the number held to the range with a warning
///   in the mod's log;
/// - `text = "key"`, the text key of the field's translated label in the
///   mod's texts, `config.<field>` by default; its description is the key
///   with `.doc` appended, and for a list each element's label is the key
///   with `.element` appended, `{n}` in it standing for the element's number;
/// - `first = n`, for a list, the number its first element shows with, 1 by
///   default;
/// - `#[config(group)]` on a field whose type is a `Config` of its own: its
///   settings are a table of the file, `[<field>]`, with dotted keys such as
///   `<field>.<key>`, and the Mods screen shows them together. A group's
///   fields take their own stages, ranges and texts.
///
/// `#[config(validate = path)]` on the struct adds a check of its own, and
/// `#[config(text = "key")]` names the text key of the whole set, `config`
/// by default.
///
/// A field takes one stage, or `startup, sync`; any other two fail the
/// build:
///
/// ```compile_fail
/// /// Settings.
/// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
/// struct Settings {
///     /// Both at once.
///     #[config(client, sync)]
///     shared: bool,
/// }
/// ```
///
/// Join values go to every client and into the server's public rules, so a
/// secret that would join them fails the build:
///
/// ```compile_fail
/// /// Settings.
/// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
/// struct Settings {
///     /// A password every client would see.
///     #[config(sync, secret)]
///     password: String,
/// }
/// ```
///
/// `sync` pairs with `startup` alone:
///
/// ```compile_fail
/// /// Settings.
/// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
/// struct Settings {
///     /// Live and from the server at once.
///     #[config(runtime, sync)]
///     rate: u32,
/// }
/// ```
///
/// and a `startup, sync` secret would reach every client too:
///
/// ```compile_fail
/// /// Settings.
/// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
/// struct Settings {
///     /// A password every client would see.
///     #[config(startup, sync, secret)]
///     password: String,
/// }
/// ```
///
/// The file, the schema and the checks name each field as it is written, so
/// a serde attribute that reads another key fails the build:
///
/// ```compile_fail
/// /// Settings.
/// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
/// struct Settings {
///     /// Renamed.
///     #[serde(rename = "max-count")]
///     limit: u32,
/// }
/// ```
///
/// # Examples
///
/// ```
/// use enshwick::config::Config;
///
/// /// Altar settings.
/// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
/// struct Settings {
///     /// Altars allowed at each Flame level.
///     altars: Vec<u8>,
/// }
///
/// assert!(Settings::template().contains("# Altars allowed at each Flame level."));
/// ```
pub trait Config: serde::de::DeserializeOwned + Default {
    /// The commented file written when the mod's settings are missing.
    fn template() -> String;

    /// The template's entries without its heading, its tables under
    /// `path`, for a group of another `Config`.
    #[doc(hidden)]
    #[must_use]
    fn __template_body(path: &str) -> String {
        let _ = path;
        Self::template()
    }

    /// What every field is, for the loader, the console and a settings menu.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Config, Stage};
    ///
    /// /// Locker settings.
    /// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
    /// struct Settings {
    ///     /// How many lockers one player may own.
    ///     #[config(startup, range = 1..=16)]
    ///     limit: u32,
    /// }
    ///
    /// let schema = Settings::schema();
    /// let limit = schema.field("limit").ok_or("no field")?;
    /// assert_eq!(limit.stage, Stage::Startup);
    /// assert_eq!((limit.min, limit.max), (Some(1.0), Some(16.0)));
    /// assert_eq!(limit.text, "config.limit");
    /// # Ok::<(), &str>(())
    /// ```
    #[must_use]
    fn schema() -> Schema {
        Schema::default()
    }

    /// The values of the fields at `stage`, as an inline TOML table; `None`
    /// when the type has none there.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Config, Stage};
    ///
    /// /// Locker settings.
    /// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
    /// struct Settings {
    ///     /// How many lockers one player may own.
    ///     #[config(startup)]
    ///     limit: u32,
    ///     /// The language of replies.
    ///     language: String,
    /// }
    ///
    /// let settings = Settings { limit: 4, language: "uk".into() };
    /// assert_eq!(settings.values(Stage::Startup).as_deref(), Some("{ limit = 4 }"));
    /// assert_eq!(settings.values(Stage::Sync), None);
    /// ```
    fn values(&self, _stage: Stage) -> Option<String> {
        None
    }

    /// Puts `values`, as [`values`](Config::values) writes them for `stage`,
    /// over the fields at `stage`; fields `values` lacks keep their values,
    /// and an error leaves `self` as it was.
    ///
    /// # Errors
    ///
    /// A message for the log when `values` does not parse or a value does
    /// not fit its field.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Config, Stage};
    ///
    /// /// Locker settings.
    /// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
    /// struct Settings {
    ///     /// How many lockers one player may own.
    ///     #[config(startup)]
    ///     limit: u32,
    /// }
    ///
    /// let mut settings = Settings { limit: 9 };
    /// settings.merge_values(Stage::Startup, "{ limit = 4 }")?;
    /// assert_eq!(settings.limit, 4);
    /// # Ok::<(), enshwick::config::ConfigError>(())
    /// ```
    fn merge_values(&mut self, _stage: Stage, _values: &str) -> Result<(), ConfigError> {
        Ok(())
    }

    /// Checks parsed values against each field's range and choices and the
    /// struct's own check; an error turns the mod off with the message at
    /// init, and skips a changed file at run time.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Value`] for a value out of its field's range or
    /// choices, [`ConfigError::Invalid`] when the struct's own check refuses.
    ///
    /// # Examples
    ///
    /// The default accepts every value; the derive takes a checking function
    /// whose error is any `Display`:
    ///
    /// ```
    /// use enshwick::config::Config;
    ///
    /// /// Comfort settings.
    /// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
    /// #[config(validate = Settings::check)]
    /// struct Settings {
    ///     /// Comfort per piece of furniture, times this factor.
    ///     multiplier: f32,
    /// }
    ///
    /// impl Settings {
    ///     fn check(&self) -> Result<(), String> {
    ///         (self.multiplier >= 0.0).then_some(()).ok_or_else(|| "a negative multiplier".into())
    ///     }
    /// }
    ///
    /// assert!(Settings { multiplier: -1.0 }.validate().is_err());
    /// ```
    fn validate(&self) -> Result<(), ConfigError> {
        Ok(())
    }

    /// The join values: the fields marked `#[config(sync)]` or
    /// `#[config(startup, sync)]`, as an inline TOML table; `None` when the
    /// type has none.
    ///
    /// A join value is one the server and its players must agree on, such as
    /// a table the client's interface also reads. The server advertises these
    /// values, and a client that joins it runs with them over its own file:
    /// its [`on_config_change`](crate::Load::on_config_change) handler gets
    /// the merged settings.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::Config;
    ///
    /// /// Altar settings.
    /// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
    /// struct Settings {
    ///     /// Altars allowed at each Flame level.
    ///     #[config(sync)]
    ///     altars: Vec<u8>,
    ///     /// Log every placed altar; this side's own business.
    ///     verbose: bool,
    /// }
    ///
    /// let settings = Settings { altars: vec![2, 4], verbose: true };
    /// assert_eq!(settings.synced().as_deref(), Some("{ altars = [2, 4] }"));
    /// ```
    fn synced(&self) -> Option<String> {
        self.values(Stage::Sync)
    }

    /// Puts the join values of `synced`, as [`synced`](Config::synced) writes
    /// them, over `self`; fields `synced` lacks keep their values, and an
    /// error leaves `self` as it was.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Parse`] when `synced` does not parse or a value does
    /// not fit its field.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::Config;
    ///
    /// /// Altar settings.
    /// #[derive(Default, serde::Deserialize, serde::Serialize, enshwick::Config)]
    /// struct Settings {
    ///     /// Altars allowed at each Flame level.
    ///     #[config(sync)]
    ///     altars: Vec<u8>,
    ///     /// Log every placed altar; this side's own business.
    ///     verbose: bool,
    /// }
    ///
    /// let mut settings = Settings { altars: vec![1], verbose: true };
    /// settings.merge_synced("{ altars = [2, 4] }")?;
    /// assert_eq!((settings.altars, settings.verbose), (vec![2, 4], true));
    /// # Ok::<(), enshwick::config::ConfigError>(())
    /// ```
    fn merge_synced(&mut self, synced: &str) -> Result<(), ConfigError> {
        self.merge_values(Stage::Sync, synced)
    }
}

/// Why settings did not read or did not pass their checks; at init it turns
/// the mod off with its message, at run time the changed file is skipped.
///
/// # Examples
///
/// ```
/// use enshwick::config::{ConfigError, Field, Stage};
///
/// let field = Field::new("limit", Stage::Startup, &4).with_range(Some(1.0), Some(16.0));
/// let refused = field.check(&toml::Value::Integer(20)).unwrap_err();
/// assert_eq!(refused, ConfigError::Value { key: "limit".into(), need: "is 1 to 16".into() });
/// assert_eq!(refused.to_string(), "limit is 1 to 16");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// The text is not settings TOML, or a value does not fit its field's
    /// type.
    #[error("{0}")]
    Parse(String),
    /// A value lies outside what its field accepts.
    #[error("{key} {need}")]
    Value {
        /// The field's key.
        key: String,
        /// What the field needs, such as `is 1 to 16`.
        need: String,
    },
    /// The settings type's own check refused the values.
    #[error("{0}")]
    Invalid(String),
}

impl ConfigError {
    /// An [`Invalid`](Self::Invalid) with `why`, as the derive wraps a
    /// `validate` function's error.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::ConfigError;
    ///
    /// assert_eq!(ConfigError::invalid("first after last").to_string(), "first after last");
    /// ```
    #[must_use]
    pub fn invalid(why: impl core::fmt::Display) -> Self {
        Self::Invalid(why.to_string())
    }
}

impl From<toml::de::Error> for ConfigError {
    fn from(error: toml::de::Error) -> Self {
        Self::Parse(error.message().to_owned())
    }
}

/// When a change to a setting takes effect.
///
/// # Examples
///
/// ```
/// use enshwick::config::Stage;
///
/// assert_eq!(Stage::default(), Stage::Runtime);
/// assert!(Stage::Restart.needs_restart());
/// assert!(!Stage::Startup.needs_restart());
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Stage {
    /// Read when a world loads (or at start, with none); a change takes
    /// effect when the world loads again, and the running values stay until
    /// then.
    Startup,
    /// Applied while the game runs, through the mod's
    /// [`on_config_change`](crate::Load::on_config_change).
    #[default]
    Runtime,
    /// Each player's own: never sent to or taken from a server.
    Client,
    /// The server's value: a joined client runs with it over its own file.
    Sync,
    /// Read once as the game starts, for what only a start can set up, such
    /// as hooks or content: kept in the settings file for every world, and a
    /// change waits for the next start.
    Restart,
}

impl Stage {
    /// Whether a change waits for the next start of the game.
    ///
    /// # Examples
    ///
    /// See [`Stage`].
    #[must_use]
    pub const fn needs_restart(self) -> bool {
        matches!(self, Self::Restart)
    }

    /// Where a setting at this stage lives.
    ///
    /// # Examples
    ///
    /// See [`Scope`].
    #[must_use]
    pub const fn scope(self) -> Scope {
        match self {
            Self::Client | Self::Restart => Scope::User,
            _ => Scope::World,
        }
    }

    /// The stage's name in the schema and in messages, such as `startup`.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(enshwick::config::Stage::Client.name(), "client");
    /// ```
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Startup => "startup",
            Self::Runtime => "runtime",
            Self::Client => "client",
            Self::Sync => "sync",
            Self::Restart => "restart",
        }
    }
}

/// Where a setting lives: with each player, or with the world.
///
/// # Examples
///
/// ```
/// use enshwick::config::{Scope, Stage};
///
/// assert_eq!(Stage::Client.scope(), Scope::User);
/// assert_eq!(Stage::Restart.scope(), Scope::User);
/// assert_eq!(Stage::Startup.scope(), Scope::World);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
    /// The game's own, in the settings file `mod-configs/<id>.toml`, for
    /// every world: the `client` and `restart` stages.
    User,
    /// The world's, kept with it in `mod-data/<id>/worlds/<key>/`; a new
    /// world starts from the settings file. The `startup`, `runtime` and
    /// `sync` stages.
    #[default]
    World,
}

/// The TOML type of a setting's value.
///
/// # Examples
///
/// ```
/// use enshwick::config::Kind;
///
/// assert_eq!(Kind::of(&toml::Value::Integer(3)), Kind::Integer);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    /// `true` or `false`.
    Bool,
    /// A whole number.
    Integer,
    /// A number with a fraction; whole numbers are accepted too.
    Float,
    /// Text.
    String,
    /// A list.
    Array,
    /// A table.
    Table,
    /// A date or time.
    Datetime,
}

impl Kind {
    /// The kind of `value`.
    ///
    /// # Examples
    ///
    /// See [`Kind`].
    #[must_use]
    pub const fn of(value: &toml::Value) -> Self {
        match value {
            toml::Value::Boolean(_) => Self::Bool,
            toml::Value::Integer(_) => Self::Integer,
            toml::Value::Float(_) => Self::Float,
            toml::Value::String(_) => Self::String,
            toml::Value::Array(_) => Self::Array,
            toml::Value::Table(_) => Self::Table,
            toml::Value::Datetime(_) => Self::Datetime,
        }
    }

    /// Whether a value of `kind` fits a setting of this kind.
    const fn accepts(self, kind: Self) -> bool {
        matches!(
            (self, kind),
            (Self::Bool, Self::Bool)
                | (Self::Integer, Self::Integer)
                | (Self::Float, Self::Float | Self::Integer)
                | (Self::String, Self::String)
                | (Self::Array, Self::Array)
                | (Self::Table, Self::Table)
                | (Self::Datetime, Self::Datetime)
        )
    }
}

/// One setting, as [`Config::schema`] describes it.
///
/// # Examples
///
/// ```
/// use enshwick::config::{Field, Stage};
///
/// let field = Field::new("radius", Stage::Runtime, &8.0_f32).with_range(Some(1.0), Some(50.0));
/// assert!(field.check(&toml::Value::Float(10.0)).is_ok());
/// assert!(field.check(&toml::Value::Float(80.0)).is_err());
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Field {
    /// The key in the settings file.
    pub key: String,
    /// When a change takes effect.
    pub stage: Stage,
    /// Where it lives, as its stage says.
    #[serde(default)]
    pub scope: Scope,
    /// The type of its value; `None` when the default has none TOML can
    /// write, such as `None`.
    pub kind: Option<Kind>,
    /// The default value, as TOML; empty when it has none TOML can write.
    pub default: String,
    /// The smallest number it accepts.
    pub min: Option<f64>,
    /// The largest number it accepts.
    pub max: Option<f64>,
    /// The values it accepts, as TOML; empty for any.
    pub choices: Vec<String>,
    /// Its documentation, in English: the field's doc comment.
    pub doc: String,
    /// The key of its translated label in the mod's texts; the description
    /// is under this key with `.doc` appended.
    pub text: String,
    /// A secret, such as a password: never sent to a client, and changed in
    /// the file only.
    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
    pub secret: bool,
    /// A `startup` setting a joined client takes from the server, as it
    /// would a `sync` one: `#[config(startup, sync)]`.
    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
    pub synced: bool,
    /// The number a list's first element shows with on the Mods screen,
    /// such as 0 for a list by Flame level: `#[config(first = 0)]`.
    #[serde(default = "first_element", skip_serializing_if = "is_first_element")]
    pub first: u32,
}

/// The number a list's first element shows with unless the field says.
const fn first_element() -> u32 {
    1
}

#[expect(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde passes a reference"
)]
const fn is_first_element(first: &u32) -> bool {
    *first == 1
}

impl Field {
    /// A field at `stage` whose default is `default`, documented by nothing
    /// yet and translated under `config.<key>`.
    ///
    /// # Examples
    ///
    /// See [`Field`].
    #[must_use]
    pub fn new<T: Serialize + ?Sized>(key: &str, stage: Stage, default: &T) -> Self {
        let value = toml::Value::try_from(default).ok().map(tidy);
        Self {
            key: key.to_owned(),
            stage,
            scope: stage.scope(),
            kind: value.as_ref().map(Kind::of),
            default: value.map(|v| v.to_string()).unwrap_or_default(),
            text: format!("config.{key}"),
            first: first_element(),
            ..Self::default()
        }
    }

    /// The field numbering a list's elements from `first` on the Mods
    /// screen.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Stage};
    ///
    /// let per_level = Field::new("per_level", Stage::Startup, &[2, 4]).with_first(0);
    /// assert_eq!(per_level.first, 0);
    /// ```
    #[must_use]
    pub const fn with_first(mut self, first: u32) -> Self {
        self.first = first;
        self
    }

    /// The field inside the group `group`: its key and its default text key
    /// prefixed with the group's.
    #[doc(hidden)]
    #[must_use]
    pub fn __in_group(mut self, group: &str) -> Self {
        let inner = format!("config.{}", self.key);
        self.key = format!("{group}.{}", self.key);
        if self.text == inner {
            self.text = format!("config.{}", self.key);
        }
        self
    }

    /// The field accepting numbers from `min` to `max`, each `None` for no
    /// bound.
    ///
    /// # Examples
    ///
    /// See [`Field`].
    #[must_use]
    pub const fn with_range(mut self, min: Option<f64>, max: Option<f64>) -> Self {
        self.min = min;
        self.max = max;
        self
    }

    /// The field accepting only `choices`.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Stage};
    ///
    /// let field = Field::new("mode", Stage::Runtime, "auto").with_choices(&["auto", "on", "off"]);
    /// assert!(field.check(&toml::Value::String("on".into())).is_ok());
    /// assert!(field.check(&toml::Value::String("maybe".into())).is_err());
    /// ```
    #[must_use]
    pub fn with_choices<T: Serialize>(mut self, choices: &[T]) -> Self {
        self.choices = choices
            .iter()
            .filter_map(|choice| toml::Value::try_from(choice).ok())
            .map(|value| tidy(value).to_string())
            .collect();
        self
    }

    /// The field documented by `doc` and translated under `text`; an empty
    /// `text` keeps `config.<key>`.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Stage};
    ///
    /// let field = Field::new("limit", Stage::Startup, &4).with_doc("How many.", "lockers.limit");
    /// assert_eq!((field.doc.as_str(), field.text.as_str()), ("How many.", "lockers.limit"));
    /// ```
    #[must_use]
    pub fn with_doc(mut self, doc: &str, text: &str) -> Self {
        doc.trim().clone_into(&mut self.doc);
        if !text.is_empty() {
            text.clone_into(&mut self.text);
        }
        self
    }

    /// The field marked secret, or not.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Stage};
    ///
    /// let field = Field::new("password", Stage::Runtime, "").with_secret(true);
    /// assert!(field.secret);
    /// ```
    #[must_use]
    pub const fn with_secret(mut self, secret: bool) -> Self {
        self.secret = secret;
        self
    }

    /// The field, at [`Stage::Startup`], also taken from the server by a
    /// joined client, or not.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Stage};
    ///
    /// let field = Field::new("rules", Stage::Startup, &true).with_synced(true);
    /// assert!(field.follows_server());
    /// ```
    #[must_use]
    pub const fn with_synced(mut self, synced: bool) -> Self {
        self.synced = synced;
        self
    }

    /// Whether a joined client runs with the server's value of the field:
    /// a `sync` field, or a `startup` one marked `sync` too.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Stage};
    ///
    /// assert!(Field::new("radius", Stage::Sync, &8).follows_server());
    /// assert!(!Field::new("limit", Stage::Startup, &4).follows_server());
    /// ```
    #[must_use]
    pub fn follows_server(&self) -> bool {
        self.stage == Stage::Sync || self.synced
    }

    /// Checks `value` against the field's type, range and choices; the range
    /// applies to every element of a list.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Value`] naming the field and what it accepts.
    ///
    /// # Examples
    ///
    /// See [`ConfigError`].
    pub fn check(&self, value: &toml::Value) -> Result<(), ConfigError> {
        let value = &tidy(value.clone());
        if let Some(kind) = self.kind
            && !kind.accepts(Kind::of(value))
        {
            return Err(self.refused(format!("takes {}", kind_name(kind))));
        }
        if let toml::Value::Array(items) = value {
            let element = self.element_kind();
            for item in items {
                if element.is_some_and(|kind| !kind.accepts(Kind::of(item))) {
                    return Err(self.refused(format!(
                        "takes a list of {}",
                        element.map_or("values", kind_name)
                    )));
                }
                self.check_bounds(item)?;
            }
        }
        let number = self.check_bounds(value)?;
        let chosen = |choice: &String| {
            *choice == value.to_string()
                || number.is_some_and(|n| {
                    choice
                        .parse::<f64>()
                        .is_ok_and(|c| c.to_bits() == n.to_bits())
                })
        };
        if !self.choices.is_empty() && !self.choices.iter().any(chosen) {
            return Err(self.refused(format!("is {}", self.accepts())));
        }
        Ok(())
    }

    /// Holds the number `value`, named `key`, to the range; the log line
    /// when it was outside.
    fn clamp_one(&self, value: &mut toml::Value, key: &str) -> Option<String> {
        #[expect(
            clippy::cast_precision_loss,
            reason = "bounds are compared as f64; a setting near 2^53 is no setting"
        )]
        let n = match value {
            toml::Value::Integer(n) => *n as f64,
            toml::Value::Float(n) => *n,
            _ => return None,
        };
        let bound = match (self.min, self.max) {
            (Some(min), _) if n < min => min,
            (_, Some(max)) if n > max => max,
            _ => return None,
        };
        let was = value.to_string();
        *value = match value {
            #[expect(
                clippy::cast_possible_truncation,
                reason = "a whole-number range's ends are whole numbers"
            )]
            toml::Value::Integer(_) => toml::Value::Integer(bound.round() as i64),
            _ => toml::Value::Float(bound),
        };
        Some(format!(
            "{key} = {was} is outside {}; {value} applies",
            self.accepts()
        ))
    }

    /// The kind of each element of a list setting, from its default.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Kind, Stage};
    ///
    /// let per_level = Field::new("per_level", Stage::Startup, &[2, 4, 8]);
    /// assert_eq!(per_level.element_kind(), Some(Kind::Integer));
    /// ```
    #[must_use]
    pub fn element_kind(&self) -> Option<Kind> {
        let table: toml::Table = toml::from_str(&format!("v = {}", self.default)).ok()?;
        match table.get("v")? {
            toml::Value::Array(items) => items.first().map(Kind::of),
            _ => None,
        }
    }

    /// Checks a number against the range; the number, `None` for a value
    /// that is none.
    fn check_bounds(&self, value: &toml::Value) -> Result<Option<f64>, ConfigError> {
        #[expect(
            clippy::cast_precision_loss,
            reason = "bounds are compared as f64; a setting near 2^53 is no setting"
        )]
        let number = match value {
            toml::Value::Integer(n) => Some(*n as f64),
            toml::Value::Float(n) => Some(*n),
            _ => None,
        };
        if let Some(n) = number
            && !(self.min.is_none_or(|min| n >= min) && self.max.is_none_or(|max| n <= max))
        {
            return Err(self.refused(format!("is {}", self.accepts())));
        }
        Ok(number)
    }

    fn refused(&self, need: String) -> ConfigError {
        ConfigError::Value {
            key: self.key.clone(),
            need,
        }
    }

    /// What the field accepts, for messages: `1 to 16`, `at least 0`,
    /// `one of "auto", "on", "off"` or its type.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Stage};
    ///
    /// let field = Field::new("limit", Stage::Startup, &4).with_range(Some(1.0), Some(16.0));
    /// assert_eq!(field.accepts(), "1 to 16");
    /// ```
    #[must_use]
    pub fn accepts(&self) -> String {
        if !self.choices.is_empty() {
            return format!("one of {}", self.choices.join(", "));
        }
        match (self.min, self.max) {
            (Some(min), Some(max)) => format!("{min} to {max}"),
            (Some(min), None) => format!("at least {min}"),
            (None, Some(max)) => format!("at most {max}"),
            (None, None) => self.kind.map_or("any value", kind_name).to_owned(),
        }
    }
}

/// How messages name a kind.
const fn kind_name(kind: Kind) -> &'static str {
    match kind {
        Kind::Bool => "true or false",
        Kind::Integer => "a whole number",
        Kind::Float => "a number",
        Kind::String => "text in quotes",
        Kind::Array => "a list in [ ]",
        Kind::Table => "a table in { }",
        Kind::Datetime => "a date or time",
    }
}

/// A mod's settings described for the loader, the console and a settings menu:
/// what [`Config::schema`] returns, and what a mod hands the loader as text.
///
/// # Examples
///
/// ```
/// use enshwick::config::{Field, Schema, Stage};
///
/// let schema = Schema::new("Locker settings.", "config", vec![Field::new("limit", Stage::Startup, &4)]);
/// assert_eq!(Schema::parse(&schema.to_text())?, schema);
/// # Ok::<(), enshwick::config::ConfigError>(())
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Schema {
    /// What the settings are for, in English: the struct's doc comment.
    pub doc: String,
    /// The key of the set's translated title in the mod's texts.
    pub text: String,
    /// Every field, in file order; a field of a group has a dotted key,
    /// `<group>.<key>`.
    #[serde(default, rename = "field")]
    pub fields: Vec<Field>,
    /// The groups, each a table in the settings file, in file order.
    #[serde(default, rename = "group", skip_serializing_if = "Vec::is_empty")]
    pub groups: Vec<Group>,
}

/// A group of settings: a table of the settings file, such as `[comfort]`,
/// which the Mods screen shows together.
///
/// # Examples
///
/// See [`Config`].
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Group {
    /// The table's key; a dotted path for a group inside a group.
    pub key: String,
    /// Its documentation, in English: the field's doc comment.
    pub doc: String,
    /// The key of its translated title in the mod's texts.
    pub text: String,
}

impl Group {
    /// The group `key`, documented by `doc`, translated under
    /// `config.<key>`.
    ///
    /// # Examples
    ///
    /// ```
    /// let group = enshwick::config::Group::new("comfort", "Comfort rules.");
    /// assert_eq!(group.text, "config.comfort");
    /// ```
    #[must_use]
    pub fn new(key: &str, doc: &str) -> Self {
        Self {
            key: key.to_owned(),
            doc: doc.trim().to_owned(),
            text: format!("config.{key}"),
        }
    }

    /// The group inside the group `outer`.
    #[doc(hidden)]
    #[must_use]
    pub fn __in_group(mut self, outer: &str) -> Self {
        let inner = format!("config.{}", self.key);
        self.key = format!("{outer}.{}", self.key);
        if self.text == inner {
            self.text = format!("config.{}", self.key);
        }
        self
    }
}

/// The value at the dotted `key` of `settings`, to change.
fn value_at_mut<'a>(settings: &'a mut toml::Table, key: &str) -> Option<&'a mut toml::Value> {
    let mut parts = key.split('.');
    let mut value = settings.get_mut(parts.next()?)?;
    for part in parts {
        value = value.as_table_mut()?.get_mut(part)?;
    }
    Some(value)
}

/// The value at `key` of `settings`, a dotted key reaching into tables:
/// `comfort.multiplier` is `multiplier` in `[comfort]`.
///
/// # Examples
///
/// ```
/// let settings: toml::Table = toml::from_str("limit = 4\n[comfort]\nmultiplier = 2.0\n")?;
/// let at = |key| enshwick::config::value_at(&settings, key).cloned();
/// assert_eq!(at("comfort.multiplier"), Some(toml::Value::Float(2.0)));
/// assert_eq!(at("limit"), Some(toml::Value::Integer(4)));
/// assert_eq!(at("comfort.missing"), None);
/// # Ok::<(), toml::de::Error>(())
/// ```
#[must_use]
pub fn value_at<'a>(settings: &'a toml::Table, key: &str) -> Option<&'a toml::Value> {
    let mut parts = key.split('.');
    let mut value = settings.get(parts.next()?)?;
    for part in parts {
        value = value.as_table()?.get(part)?;
    }
    Some(value)
}

impl Schema {
    /// A schema documented by `doc`, translated under `text`, with `fields`.
    ///
    /// # Examples
    ///
    /// See [`Schema`].
    #[must_use]
    pub fn new(doc: &str, text: &str, fields: Vec<Field>) -> Self {
        Self {
            doc: doc.trim().to_owned(),
            text: text.to_owned(),
            fields,
            groups: Vec::new(),
        }
    }

    /// The schema with `groups`.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Group, Schema, Stage};
    ///
    /// let multiplier = Field::new("comfort.multiplier", Stage::Runtime, &1.0);
    /// let schema = Schema::new("", "config", vec![multiplier])
    ///     .with_groups(vec![Group::new("comfort", "Comfort rules.")]);
    /// assert_eq!(schema.groups[0].key, "comfort");
    /// ```
    #[must_use]
    pub fn with_groups(mut self, groups: Vec<Group>) -> Self {
        self.groups = groups;
        self
    }

    /// Holds every number of `settings` that lies outside its field's range,
    /// list elements too, to the nearest end of the range; returns a line
    /// per value held, for the log. A file a player wrote keeps reading.
    #[must_use]
    pub(crate) fn clamp(&self, settings: &mut toml::Table) -> Vec<String> {
        let mut held = Vec::new();
        for field in &self.fields {
            if field.min.is_none() && field.max.is_none() {
                continue;
            }
            let Some(value) = value_at_mut(settings, &field.key) else {
                continue;
            };
            if let toml::Value::Array(items) = value {
                for (i, item) in items.iter_mut().enumerate() {
                    if let Some(line) = field.clamp_one(item, &format!("{}[{i}]", field.key)) {
                        held.push(line);
                    }
                }
            } else if let Some(line) = field.clamp_one(value, &field.key) {
                held.push(line);
            }
        }
        held
    }

    /// The group a field with key `key` belongs to, if any.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Group, Schema};
    ///
    /// let schema = Schema::new("", "config", vec![])
    ///     .with_groups(vec![Group::new("comfort", "")]);
    /// assert_eq!(schema.group_of("comfort.multiplier").map(|g| g.key.as_str()), Some("comfort"));
    /// assert!(schema.group_of("limit").is_none());
    /// ```
    #[must_use]
    pub fn group_of(&self, key: &str) -> Option<&Group> {
        let (group, _) = key.rsplit_once('.')?;
        self.groups.iter().find(|g| g.key == group)
    }

    /// The field with key `key`.
    ///
    /// # Examples
    ///
    /// See [`Config::schema`].
    #[must_use]
    pub fn field(&self, key: &str) -> Option<&Field> {
        self.fields.iter().find(|f| f.key == key)
    }

    /// The schema as TOML text, as it crosses to the loader.
    ///
    /// # Examples
    ///
    /// See [`Schema`].
    #[must_use]
    pub fn to_text(&self) -> String {
        toml::to_string(self).unwrap_or_default()
    }

    /// Reads a schema written by [`to_text`](Self::to_text).
    ///
    /// # Errors
    ///
    /// [`ConfigError::Parse`] when `text` is not one.
    ///
    /// # Examples
    ///
    /// See [`Schema`].
    pub fn parse(text: &str) -> Result<Self, ConfigError> {
        toml::from_str(text)
            .map_err(|e| ConfigError::Parse(format!("settings schema: {}", e.message())))
    }

    /// Checks every field of `settings` that has a value against its
    /// [`Field::check`].
    ///
    /// # Errors
    ///
    /// The first field's [`ConfigError::Value`].
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::config::{Field, Schema, Stage};
    ///
    /// let limit = Field::new("limit", Stage::Startup, &4).with_range(Some(1.0), Some(16.0));
    /// let schema = Schema::new("", "config", vec![limit]);
    /// assert!(schema.check(&toml::from_str("limit = 20")?).is_err());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn check(&self, settings: &toml::Table) -> Result<(), ConfigError> {
        self.fields.iter().try_for_each(|field| {
            value_at(settings, &field.key).map_or(Ok(()), |value| field.check(value))
        })
    }
}

/// Checks the serialized fields of `settings` against `schema`, for the
/// derive's `validate`.
#[doc(hidden)]
pub fn __check_field<T: Serialize>(
    schema: &Schema,
    key: &str,
    value: &T,
) -> Result<(), ConfigError> {
    let Some(field) = schema.field(key) else {
        return Ok(());
    };
    // In a table, so a `None` is left out rather than refused.
    let mut one = std::collections::BTreeMap::new();
    one.insert(key, value);
    match toml::Value::try_from(one) {
        Ok(toml::Value::Table(table)) => table.get(key).map_or(Ok(()), |v| field.check(v)),
        _ if field.min.is_none() && field.max.is_none() && field.choices.is_empty() => Ok(()),
        _ => Err(ConfigError::Value {
            key: key.to_owned(),
            need: "cannot be checked: TOML cannot hold its value".to_owned(),
        }),
    }
}

/// `value` with each float an `f32` field gave, such as 0.10000000149011612,
/// back at the decimal written for it, 0.1, so that bounds and texts read as
/// the author wrote them.
fn tidy(value: toml::Value) -> toml::Value {
    match value {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "only a float an f32 holds exactly is replaced"
        )]
        toml::Value::Float(n) if f64::from(n as f32).to_bits() == n.to_bits() => {
            toml::Value::Float((n as f32).to_string().parse().unwrap_or(n))
        }
        toml::Value::Array(items) => toml::Value::Array(items.into_iter().map(tidy).collect()),
        toml::Value::Table(table) => {
            toml::Value::Table(table.into_iter().map(|(k, v)| (k, tidy(v))).collect())
        }
        other => other,
    }
}

/// `key` as a TOML key: bare when it may be, quoted otherwise.
fn toml_key(key: &str) -> String {
    let bare = !key.is_empty()
        && key
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
    if bare {
        key.to_owned()
    } else {
        toml::Value::String(key.to_owned()).to_string()
    }
}

/// The values of a settings value at one stage, built by `#[derive(Config)]`.
#[doc(hidden)]
#[derive(Debug, Default)]
pub struct __Values(toml::Table);

impl __Values {
    /// Adds `key`; a value TOML cannot hold, such as `None`, is left out.
    pub fn put<T: Serialize>(&mut self, key: &str, value: &T) {
        if let Ok(value) = toml::Value::try_from(value) {
            self.0.insert(key.to_owned(), value);
        }
    }

    /// Adds the values `text` of the group `key`, an inline table as
    /// [`finish`](Self::finish) writes it.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Parse`] when `text` is not one.
    pub fn put_group(&mut self, key: &str, text: &str) -> Result<(), ConfigError> {
        let group = Self::parse(text)?;
        self.0.insert(key.to_owned(), toml::Value::Table(group.0));
        Ok(())
    }

    /// The values of the group `key` as an inline table, `None` when it is
    /// absent.
    #[must_use]
    pub fn group(&self, key: &str) -> Option<String> {
        self.0
            .get(key)
            .and_then(toml::Value::as_table)
            .map(|table| toml::Value::Table(table.clone()).to_string())
    }

    /// The values as an inline table, keys sorted.
    #[must_use]
    pub fn finish(self) -> String {
        toml::Value::Table(self.0).to_string()
    }

    /// Reads an inline table.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Parse`] when `text` is not one.
    pub fn parse(text: &str) -> Result<Self, ConfigError> {
        let mut document: toml::Table = toml::from_str(&format!("synced = {text}"))
            .map_err(|e| ConfigError::Parse(format!("values: {}", e.message())))?;
        match document.remove("synced") {
            Some(toml::Value::Table(table)) if document.is_empty() => Ok(Self(table)),
            _ => Err(ConfigError::Parse("values: not an inline table".to_owned())),
        }
    }

    /// The value of `key` as `T`, `None` when it is absent.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Parse`] when the value does not fit `T`.
    pub fn take<T: serde::de::DeserializeOwned>(
        &self,
        key: &str,
    ) -> Result<Option<T>, ConfigError> {
        self.0
            .get(key)
            .map(|value| {
                value.clone().try_into().map_err(|e: toml::de::Error| {
                    ConfigError::Parse(format!("value {key}: {}", e.message()))
                })
            })
            .transpose()
    }
}

/// The keys whose values differ between two inline tables of
/// [`__Values`], sorted and joined, for a log line that shows no values: a
/// secret field may be among them.
pub(crate) fn changed_keys(before: &str, after: &str) -> String {
    let table = |text| {
        __Values::parse(text)
            .map(|values| values.0)
            .unwrap_or_default()
    };
    let (before, after) = (table(before), table(after));
    let mut keys: Vec<&str> = before
        .keys()
        .chain(after.keys())
        .filter(|key| before.get(*key) != after.get(*key))
        .map(String::as_str)
        .collect();
    keys.sort_unstable();
    keys.dedup();
    keys.join(", ")
}

/// `key = value` for a template, from any serializable value.
#[doc(hidden)]
#[must_use]
pub fn __entry<T: Serialize>(key: &str, value: &T) -> String {
    match toml::Value::try_from(value) {
        Ok(value) => format!("{} = {}\n\n", toml_key(key), tidy(value)),
        Err(_) => format!("# {key}: no default could be written\n\n"),
    }
}

#[cfg(test)]
mod tests {
    use super::Config;

    /// Test settings.
    #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, crate::Config)]
    #[serde(default)]
    struct Settings {
        /// A join value.
        #[config(sync)]
        table: Vec<u16>,
        /// Another join value.
        #[config(sync)]
        name: String,
        /// This side's own.
        local: u32,
    }

    fn settings() -> Settings {
        Settings {
            table: vec![2, 4, 8],
            name: "Base \"one\"".into(),
            local: 7,
        }
    }

    #[test]
    fn only_join_values_are_written_sorted_and_inline() {
        assert_eq!(
            settings().synced().as_deref(),
            Some("{ name = 'Base \"one\"', table = [2, 4, 8] }")
        );
    }

    #[test]
    fn join_values_merge_over_the_rest_and_round_trip() {
        let synced = settings().synced().unwrap();
        let mut local = Settings {
            local: 3,
            ..Settings::default()
        };
        local.merge_synced(&synced).unwrap();
        assert_eq!(
            local,
            Settings {
                local: 3,
                ..settings()
            }
        );
        local.merge_synced("{ table = [1] }").unwrap();
        assert_eq!(local.table, [1]);
        assert_eq!(local.name, "Base \"one\"");
    }

    #[test]
    fn a_bad_value_leaves_the_settings_as_they_were() {
        let mut local = settings();
        assert!(local.merge_synced("{ name = 'x', table = 'no' }").is_err());
        assert!(local.merge_synced("table = [1]").is_err());
        assert!(local.merge_synced("{ table = [1] }\nname = 'x'").is_err());
        assert_eq!(local, settings());
    }

    /// Staged settings.
    #[derive(Debug, PartialEq, serde::Deserialize, serde::Serialize, crate::Config)]
    #[config(text = "lockers.config")]
    struct Staged {
        /// How many, read when the world loads.
        #[config(startup, range = 1..=16)]
        limit: u32,
        /// Workers, read as the game starts.
        #[config(restart)]
        workers: u8,
        /// The mode.
        #[config(choices = ["auto", "on"], text = "lockers.mode")]
        mode: String,
        /// This player's own.
        #[config(client, range = 0.0..)]
        volume: f32,
    }

    impl Default for Staged {
        fn default() -> Self {
            Self {
                limit: 4,
                workers: 2,
                mode: "auto".into(),
                volume: 1.0,
            }
        }
    }

    /// World rules a joined client takes from the server.
    #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, crate::Config)]
    struct Rules {
        /// The rule of the world.
        #[config(startup, sync)]
        rule: bool,
        /// Read when the world loads, this side's own.
        #[config(startup)]
        limit: u32,
        /// The server's, live.
        #[config(sync)]
        rate: u32,
    }

    #[test]
    fn a_startup_sync_field_waits_for_a_world_and_joins_the_server_s_values() {
        use super::Stage;

        let rules = Rules {
            rule: true,
            limit: 4,
            rate: 2,
        };
        assert_eq!(
            rules.values(Stage::Startup).as_deref(),
            Some("{ limit = 4, rule = true }")
        );
        assert_eq!(rules.synced().as_deref(), Some("{ rate = 2, rule = true }"));
        let mut joined = Rules::default();
        joined.merge_synced("{ rule = true, rate = 2 }").unwrap();
        assert_eq!((joined.rule, joined.limit, joined.rate), (true, 0, 2));
        let schema = Rules::schema();
        let rule = schema.field("rule").unwrap();
        assert_eq!((rule.stage, rule.synced), (Stage::Startup, true));
        assert!(rule.follows_server());
        assert!(!schema.field("limit").unwrap().follows_server());
        assert!(schema.field("rate").unwrap().follows_server());
        assert_eq!(super::Schema::parse(&schema.to_text()).unwrap(), schema);
        assert!(Rules::template().contains(
            "# Takes effect when the world loads; joined players run with the server's value.\nrule = false"
        ));
    }

    #[test]
    fn the_schema_describes_stages_ranges_choices_and_texts() {
        use super::{Kind, Stage};

        let schema = Staged::schema();
        assert_eq!(schema.doc, "Staged settings.");
        assert_eq!(schema.text, "lockers.config");
        let limit = schema.field("limit").unwrap();
        assert_eq!(
            (limit.stage, limit.kind, limit.min, limit.max),
            (Stage::Startup, Some(Kind::Integer), Some(1.0), Some(16.0))
        );
        assert_eq!(
            (limit.default.as_str(), limit.doc.as_str()),
            ("4", "How many, read when the world loads.")
        );
        assert_eq!(limit.text, "config.limit");
        let mode = schema.field("mode").unwrap();
        assert_eq!(mode.stage, Stage::Runtime);
        assert_eq!(mode.choices, ["\"auto\"", "\"on\""]);
        assert_eq!(mode.text, "lockers.mode");
        let volume = schema.field("volume").unwrap();
        assert_eq!(
            (volume.stage, volume.min, volume.max),
            (Stage::Client, Some(0.0), None)
        );
        assert_eq!(super::Schema::parse(&schema.to_text()).unwrap(), schema);
        let workers = schema.field("workers").unwrap();
        assert_eq!(
            (workers.stage, workers.scope),
            (Stage::Restart, super::Scope::User)
        );
        assert!(Staged::template().contains(
            "# Takes effect when the world loads.
limit = 4"
        ));
        assert!(Staged::template().contains(
            "# Takes effect when the game starts again.
workers = 2"
        ));
    }

    #[test]
    fn values_follow_their_stage_and_validation_uses_the_schema() {
        use super::Stage;

        let mut staged = Staged::default();
        assert_eq!(
            staged.values(Stage::Startup).as_deref(),
            Some("{ limit = 4 }")
        );
        assert_eq!(
            staged.values(Stage::Client).as_deref(),
            Some("{ volume = 1.0 }")
        );
        assert_eq!(
            staged.values(Stage::Restart).as_deref(),
            Some("{ workers = 2 }")
        );
        assert_eq!(staged.values(Stage::Sync), None);
        assert_eq!(staged.synced(), None);
        staged
            .merge_values(Stage::Startup, "{ limit = 9 }")
            .unwrap();
        assert_eq!(staged.limit, 9);
        assert!(staged.validate().is_ok());
        staged.limit = 17;
        assert!(
            staged
                .validate()
                .unwrap_err()
                .to_string()
                .contains("1 to 16")
        );
        staged.limit = 3;
        staged.mode = "off".into();
        assert!(
            staged
                .validate()
                .unwrap_err()
                .to_string()
                .contains("one of")
        );
    }

    #[test]
    fn an_f32_at_its_decimal_bound_passes_and_reads_as_written() {
        /// Ratio.
        #[derive(Debug, serde::Deserialize, serde::Serialize, crate::Config)]
        struct Ratio {
            /// Share.
            #[config(range = 0.0..=0.1, choices = [0.05, 0.1, 1.0])]
            share: f32,
        }
        impl Default for Ratio {
            fn default() -> Self {
                Self { share: 0.1 }
            }
        }
        assert!(Ratio::default().validate().is_ok());
        assert!(Ratio::template().contains("share = 0.1\n"));
        assert_eq!(Ratio::schema().field("share").unwrap().default, "0.1");
        assert!(Ratio { share: 0.11 }.validate().is_err());
        let field = &Ratio::schema().fields[0];
        assert!(field.check(&toml::Value::Integer(1)).is_err());
        let whole =
            super::Field::new("whole", super::Stage::Runtime, &1.0_f64).with_choices(&[0.5, 1.0]);
        assert!(whole.check(&toml::Value::Integer(1)).is_ok());
        assert!(whole.check(&toml::Value::Integer(2)).is_err());
    }

    #[test]
    fn a_field_toml_cannot_hold_still_leaves_the_others_checked() {
        /// Mixed.
        #[derive(Default, serde::Deserialize, serde::Serialize, crate::Config)]
        struct Mixed {
            /// Keyed by number, which TOML cannot write.
            names: std::collections::HashMap<u32, String>,
            /// Checked.
            #[config(range = 1..=16)]
            limit: u32,
            /// Unset.
            #[config(range = 1..=4)]
            spare: Option<u8>,
            /// Beyond TOML's integers.
            #[config(range = 1..)]
            seed: u64,
        }
        let mut mixed = Mixed {
            names: [(1, "one".to_owned())].into(),
            limit: 99,
            seed: 1,
            ..Mixed::default()
        };
        assert!(mixed.validate().unwrap_err().to_string().contains("limit"));
        mixed.limit = 3;
        assert!(mixed.validate().is_ok());
        mixed.seed = u64::MAX;
        assert!(mixed.validate().unwrap_err().to_string().contains("seed"));
    }

    #[test]
    fn the_template_parses_back_whatever_the_names_and_docs() {
        /** Block doc,
        over two lines. */
        #[derive(
            Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, crate::Config,
        )]
        struct Odd {
            /** A raw name,
            documented in a block. */
            r#type: u32,
            #[doc = "First line\nsecond line"]
            size: u8,
        }
        let template = Odd::template();
        let parsed: Odd = toml::from_str(&template).unwrap();
        assert_eq!(parsed, Odd::default());
        assert!(template.contains("#        over two lines."));
        assert!(template.contains("#second line\nsize = 0"));
        assert!(Odd::schema().field("type").is_some());
        assert_eq!(super::__entry("größe", &0), "\"größe\" = 0\n\n");
    }

    #[test]
    fn types_without_join_values_write_none() {
        /// Plain.
        #[derive(Default, serde::Deserialize, serde::Serialize, crate::Config)]
        struct Plain {
            /// A value.
            value: u8,
        }
        let mut plain = Plain { value: 1 };
        assert_eq!(plain.synced(), None);
        assert!(plain.merge_synced("{ value = 2 }").is_ok());
        assert_eq!(plain.value, 1);
    }

    #[test]
    fn a_held_change_names_its_keys_and_never_a_secret_value() {
        /// Login.
        #[derive(Default, serde::Deserialize, serde::Serialize, crate::Config)]
        struct Login {
            /// The server's password.
            #[config(startup, secret)]
            password: String,
            /// Players at most.
            #[config(startup)]
            slots: u8,
        }
        let before = Login {
            password: "old".to_owned(),
            slots: 4,
        };
        let after = Login {
            password: "hunter2".to_owned(),
            slots: 4,
        };
        let before = before.values(super::Stage::Startup).unwrap_or_default();
        let after = after.values(super::Stage::Startup).unwrap_or_default();
        let line = super::changed_keys(&before, &after);
        assert_eq!(line, "password");
        assert!(!line.contains("hunter2"));
    }

    #[test]
    fn generated_names_leave_the_users_constants_alone() {
        #[expect(non_upper_case_globals, reason = "the names the derive binds")]
        const table: u8 = 0;
        #[expect(non_upper_case_globals, reason = "the names the derive binds")]
        const defaults: u8 = 0;
        /// Names.
        #[derive(Default, serde::Deserialize, serde::Serialize, crate::Config)]
        struct Names {
            /// A field named as a generated local.
            #[config(startup)]
            table: u32,
            /// Another.
            #[config(startup)]
            slots: u32,
        }
        let mut names = Names::default();
        assert!(
            names
                .merge_values(super::Stage::Startup, "{ table = 7, slots = 3 }")
                .is_ok()
        );
        assert_eq!((names.table, names.slots, table, defaults), (7, 3, 0, 0));
    }
}