tomlini 0.1.0

SAX TOML/INI parser and editor. Zero-dependency, no footguns.
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
//! Tests for the batch editor.

use tomlini::{EditError, editor::BringAlong, editor::Editor, parse};

// ============================================================
// Read accessors
// ============================================================

#[test]
fn test_has_existing_key() {
    let mut doc = parse("port = 8080\n").unwrap();
    assert!(doc.has("port"));
}

#[test]
fn test_has_missing_key() {
    let mut doc = parse("port = 8080\n").unwrap();
    assert!(!doc.has("nonexistent"));
}

#[test]
fn test_has_in_table() {
    let mut doc = parse("[server]\nport = 8080\n").unwrap();
    assert!(doc.has("server.port"));
}

#[test]
fn test_get_value() {
    let mut doc = parse("count = 42\n").unwrap();
    assert_eq!(doc.get("count"), Some("42"));
}

#[test]
fn test_get_quoted_value() {
    let mut doc = parse("name = \"hello\"\n").unwrap();
    assert_eq!(doc.get("name"), Some("\"hello\""));
}

// ============================================================
// Set operations
// ============================================================

#[test]
fn editor_set_value() {
    let mut doc = parse("port = 8080\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.set("port", "9090").commit(&mut doc).unwrap();
    assert_eq!(doc.to_string(), "port = 9090\n");
}

#[test]
fn editor_set_value_in_table() {
    let mut doc = parse("[server]\nport = 8080\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.set("server.port", "9090").commit(&mut doc).unwrap();
    assert!(doc.to_string().contains("port = 9090"));
}

#[test]
fn test_set_creates_valid_output() {
    let mut doc = parse("key = \"old\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.set("key", "\"new\"").commit(&mut doc).unwrap();
    // The output should parse successfully.
    let reparsed = parse(&doc.to_string());
    assert!(
        reparsed.is_ok(),
        "set output should be valid TOML: {:?}",
        reparsed.err()
    );
}

#[test]
fn test_set_nonexistent_key() {
    let mut doc = parse("a = 1\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.set("missing", "2");
    let result = editor.commit(&mut doc);
    assert!(matches!(result, Err(EditError::NotFound)));
}

// ============================================================
// Insert operations
// ============================================================

#[test]
fn editor_insert_key() {
    let mut doc = parse("name = \"hello\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .insert("", "version", "1.0")
        .commit(&mut doc)
        .unwrap();
    assert!(doc.to_string().contains("version = 1.0"));
}

#[test]
fn test_insert_into_empty_doc() {
    let mut doc = tomlini::FlatDoc::new();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .insert("", "key", "\"val\"")
        .commit(&mut doc)
        .unwrap();
    assert!(doc.to_string().contains("key = \"val\""));
}

#[test]
fn test_insert_multiple() {
    // Batch-insert several keys into a document that already has content.
    // The insert ops all resolve to the end of the root table in one pass.
    let mut doc = parse("z = 999\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.insert("", "a", "1");
    editor.insert("", "b", "2");
    editor.insert("", "c", "3");
    editor.commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("a = 1"));
    assert!(out.contains("b = 2"));
    assert!(out.contains("c = 3"));
    assert!(out.contains("z = 999"));
}

#[test]
fn editor_insert_with_comment() {
    let mut doc = parse("name = \"hello\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .insert("", "version", "1.0")
        .with_above_comment("The app version");
    editor.commit(&mut doc).unwrap();
    assert!(doc.to_string().contains("# The app version"));
}

#[test]
fn test_insert_with_block_comment() {
    let mut doc = parse("name = \"hello\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .insert("", "version", "1.0")
        .with_block_comment(&["Copyright 2024", "All rights reserved"]);
    editor.commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("# Copyright 2024"));
    assert!(out.contains("# All rights reserved"));
}

#[test]
fn test_insert_nonexistent_table() {
    let mut doc = parse("[real]\na = 1\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.insert("nonexistent", "key", "val");
    let result = editor.commit(&mut doc);
    assert!(matches!(result, Err(EditError::NotFound)));
}

// ============================================================
// Remove operations
// ============================================================

#[test]
fn editor_remove_key() {
    let mut doc = parse("name = \"hello\"\nversion = \"1.0\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.remove("version").commit(&mut doc).unwrap();
    assert!(!doc.to_string().contains("version"));
}

#[test]
fn test_remove_last_key() {
    let mut doc = parse("only = \"me\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.remove("only").commit(&mut doc).unwrap();
    // The entire line is removed. The document may be empty.
    assert!(!doc.to_string().contains("only"));
}

#[test]
fn test_remove_nonexistent_key() {
    let mut doc = parse("a = 1\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.remove("missing");
    let result = editor.commit(&mut doc);
    assert!(matches!(result, Err(EditError::NotFound)));
}

#[test]
fn test_remove_from_nonexistent_table() {
    let mut doc = parse("[real]\na = 1\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.remove("fake.key");
    let result = editor.commit(&mut doc);
    assert!(matches!(result, Err(EditError::NotFound)));
}

// ============================================================
// Chained operations
// ============================================================

#[test]
fn editor_chained_ops() {
    let mut doc = parse("[server]\nhost = \"localhost\"\nport = 8080\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .set("server.port", "9090")
        .insert("server", "timeout", "30")
        .with_above_comment("Connection timeout")
        .remove("server.host");
    editor.commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("port = 9090"));
    assert!(out.contains("timeout = 30"));
    assert!(out.contains("# Connection timeout"));
    assert!(!out.contains("host"));
}

#[test]
fn test_chain_set_and_remove_same_key() {
    // Both set and remove targeting the same key in one commit:
    // remove wins because it removes the entire line.
    let mut doc = parse("x = 1\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.set("x", "2").remove("x");
    editor.commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(!out.contains("x"), "key should be removed, but got: {out}");
}

#[test]
fn test_chain_ten_ops() {
    let mut doc = tomlini::FlatDoc::new();
    let mut editor = tomlini::editor::Editor::new();
    for i in 0..10 {
        let key = format!("k{i}");
        let val = format!("{i}");
        editor.insert("", &key, &val);
    }
    editor.commit(&mut doc).unwrap();
    let out = doc.to_string();
    for i in 0..10 {
        assert!(out.contains(&format!("k{i} = {i}")));
    }
}

// ============================================================
// Empty operations
// ============================================================

#[test]
fn test_empty_commit() {
    let mut doc = parse("key = 1\n").unwrap();
    let original = doc.to_string();
    let mut editor = tomlini::editor::Editor::new();
    editor.commit(&mut doc).unwrap();
    assert_eq!(doc.to_string(), original);
}

#[test]
fn test_document_new_is_empty() {
    let doc = tomlini::FlatDoc::new();
    assert!(doc.to_string().is_empty());
}

// ============================================================
// Formatting preservation
// ============================================================

#[test]
fn editor_set_preserves_comment() {
    let mut doc = parse("port = 8080 # default\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.set("port", "9090").commit(&mut doc).unwrap();
    assert!(doc.to_string().contains("# default"));
}

#[test]
fn test_set_preserves_comment_before_key() {
    let mut doc = parse("# the port number\nport = 8080\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.set("port", "9090").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("# the port number"),
        "comment above key must survive: {out}"
    );
    assert!(out.contains("port = 9090"));
}

#[test]
fn test_insert_copies_neighbor_indent() {
    let mut doc = parse("[server]\n  host = \"localhost\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .insert("server", "port", "8080")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    // The inserted line should copy the 2-space indent.
    assert!(
        out.contains("  port = 8080"),
        "expected 2-space indent on new key: {out}"
    );
}

#[test]
fn test_remove_preserves_adjacent_formatting() {
    let mut doc = parse("key1 = \"a\"\nkey2 = \"b\"\nkey3 = \"c\"\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.remove("key2").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("key1 = \"a\""));
    assert!(!out.contains("key2"));
    assert!(out.contains("key3 = \"c\""));
}

#[test]
fn get_decoded_basic_string() {
    let mut doc = parse(r#"key = "hello\nworld""#).unwrap();
    let decoded = doc.get_decoded("key").unwrap();
    assert_eq!(decoded, "hello\nworld");
}

#[test]
fn get_decoded_literal_string() {
    let mut doc = parse(r"key = 'hello\nworld'").unwrap();
    let decoded = doc.get_decoded("key").unwrap();
    assert_eq!(decoded, r"hello\nworld");
}

#[test]
fn get_decoded_integer_returns_raw() {
    let mut doc = parse("key = 42").unwrap();
    let decoded = doc.get_decoded("key").unwrap();
    assert_eq!(decoded, "42");
}

#[test]
fn doc_keys_root() {
    let mut doc = parse("name = \"app\"\nversion = \"1.0\"\n[server]\nport = 8080\n").unwrap();
    let keys = doc.keys();
    assert!(keys.contains(&"name".to_string()));
    assert!(keys.contains(&"version".to_string()));
    assert!(keys.contains(&"server".to_string()));
}

#[test]
fn doc_is_table_true() {
    let mut doc = parse("[server]\nport = 8080\n").unwrap();
    assert!(doc.is_table("server"));
}

#[test]
fn doc_is_table_false_for_scalar() {
    let mut doc = parse("port = 8080\n").unwrap();
    assert!(!doc.is_table("port"));
}

#[test]
fn doc_is_table_inline() {
    let mut doc = parse("colors = { red = \"#ff0000\" }\n").unwrap();
    assert!(doc.is_table("colors"));
}

// ============================================================
// Array insert / remove
// ============================================================

#[test]
fn test_array_insert() {
    let mut doc = parse("arr = [1, 2, 3]\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .array_insert("arr", 1, "99")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("99"), "inserted value not found in: {out}");
    assert!(out.contains("1"));
    assert!(out.contains("2"));
    assert!(out.contains("3"));
}

#[test]
fn test_array_insert_at_end() {
    let mut doc = parse("arr = [1, 2, 3]\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.array_insert("arr", 3, "4").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("4"));
    assert!(out.contains("3"));
}

#[test]
fn test_array_insert_into_empty() {
    let mut doc = parse("arr = []\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.array_insert("arr", 0, "1").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("1"));
}

#[test]
fn test_array_remove() {
    let mut doc = parse("arr = [1, 2, 3]\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.array_remove("arr", 1).commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("1"));
    assert!(!out.contains("2"));
    assert!(out.contains("3"));
}

#[test]
fn test_array_remove_first() {
    let mut doc = parse("arr = [1, 2, 3]\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.array_remove("arr", 0).commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(!out.contains('1'));
    assert!(out.contains('2'));
    assert!(out.contains('3'));
}

#[test]
fn test_array_remove_last() {
    let mut doc = parse("arr = [1, 2, 3]\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.array_remove("arr", 2).commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("1"));
    assert!(out.contains("2"));
    assert!(!out.contains('3'));
}

// ============================================================
// Section operations
// ============================================================

#[test]
fn test_replace_section() {
    let mut doc = parse("[server]\nhost = \"old\"\nport = 80\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .replace_section("server", &[("host", "\"new\""), ("timeout", "30")])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("[server]"), "header must survive: {out}");
    assert!(out.contains("host = \"new\""), "new host not found: {out}");
    assert!(out.contains("timeout = 30"), "new key not found: {out}");
    assert!(!out.contains("\"old\""), "old host should be gone: {out}");
    assert!(!out.contains("port"), "port should be gone: {out}");
}

#[test]
fn test_replace_section_new_section() {
    let mut doc = parse("root_key = 1\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .replace_section("new_sec", &[("key", "\"val\"")])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("[new_sec]"),
        "new section header missing: {out}"
    );
    assert!(out.contains("key = \"val\""), "new key missing: {out}");
}

#[test]
fn test_clear_section() {
    let mut doc = parse("[server]\nhost = \"x\"\nport = 80\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.clear_section("server").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("[server]"), "header must survive: {out}");
    assert!(!out.contains("host"), "host should be removed: {out}");
    assert!(!out.contains("port"), "port should be removed: {out}");
}

#[test]
fn test_rename_section() {
    let mut doc = parse("[old]\nkey = 1\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .rename_section("old", "new")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("[new]"), "new name missing: {out}");
    assert!(!out.contains("[old]"), "old name should be gone: {out}");
    assert!(out.contains("key = 1"), "content should survive: {out}");
}

#[test]
fn test_rename_section_conflict() {
    let mut doc = parse("[a]\nk = 1\n[b]\nk = 2\n").unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.rename_section("a", "b");
    let result = editor.commit(&mut doc);
    assert!(matches!(result, Err(EditError::SectionExists)));
}

// ============================================================
// AOT operations
// ============================================================

#[test]
fn test_aot_set() {
    let input =
        "[[products]]\nname = \"apple\"\nprice = 5\n\n[[products]]\nname = \"banana\"\nprice = 3\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .aot_set("products", 0, "price", "10")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    // First product's price should be 10, second should remain 3
    assert!(out.contains("price = 10"), "first price not updated: {out}");
    assert!(
        out.contains("price = 3"),
        "second price should remain: {out}"
    );
    assert!(out.contains("name = \"apple\""));
    assert!(out.contains("name = \"banana\""));
}

#[test]
fn test_aot_set_second_entry() {
    let input =
        "[[products]]\nname = \"apple\"\nprice = 5\n\n[[products]]\nname = \"banana\"\nprice = 3\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .aot_set("products", 1, "name", "\"cherry\"")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("name = \"apple\""),
        "first name should survive: {out}"
    );
    assert!(
        out.contains("name = \"cherry\""),
        "second name not updated: {out}"
    );
    assert!(!out.contains("\"banana\""));
}

#[test]
fn test_aot_set_nonexistent_key() {
    let input = "[[products]]\nname = \"apple\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.aot_set("products", 0, "missing", "99");
    let result = editor.commit(&mut doc);
    assert!(matches!(result, Err(EditError::NotFound)));
}

#[test]
fn test_aot_set_bad_index() {
    let input = "[[products]]\nname = \"apple\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.aot_set("products", 5, "name", "\"x\"");
    let result = editor.commit(&mut doc);
    assert!(matches!(result, Err(EditError::InvalidPath)));
}

// ============================================================
// Inline table operations
// ============================================================

#[test]
fn test_inline_insert() {
    let input = "key = {a = 1, b = 2}\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .inline_insert("key", "c", "3")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("key = {a = 1, b = 2, c = 3}"),
        "unexpected output: {out}"
    );
}

#[test]
fn test_inline_insert_empty() {
    let input = "key = {}\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .inline_insert("key", "a", "1")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("key = {a = 1}"), "unexpected output: {out}");
}

#[test]
fn test_inline_remove() {
    let input = "key = {a = 1, b = 2, c = 3}\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.inline_remove("key", "b").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("key = {a = 1,c = 3}"),
        "unexpected output: {out}"
    );
}

#[test]
fn test_inline_remove_last() {
    let input = "key = {a = 1}\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.inline_remove("key", "a").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("{}"), "unexpected output: {out}");
}

// ============================================================
// promote_key
// ============================================================

#[test]
fn test_promote_key_simple() {
    let input = "[meta]\nname = \"Test\"\nbase = \"my-base\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.promote_key("meta.base").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("base = \"my-base\""),
        "promoted key missing: {out}"
    );
    assert!(
        !out.contains("meta.base"),
        "dotted path still present: {out}"
    );
}

#[test]
fn test_promote_key_preserves_formatting() {
    let input = "[meta]\n# above comment\nbase = \"val\"  # inline\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.promote_key("meta.base").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("# above comment"), "above comment lost: {out}");
    assert!(out.contains("# inline"), "inline comment lost: {out}");
}

#[test]
fn test_promote_key_last_in_table() {
    // When the promoted key is the last in the table, the table may become empty
    let input = "[meta]\nbase = \"my-base\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.promote_key("meta.base").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("base = \"my-base\""),
        "promoted key missing: {out}"
    );
}

#[test]
fn test_promote_key_with_fluent_handle() {
    let input = "[meta]\nbase = \"my-base\"\n";
    let mut doc = parse(input).unwrap();
    doc.edit().promote_key("meta.base").commit().unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("base = \"my-base\""),
        "promoted key missing: {out}"
    );
}

#[test]
fn test_promote_key_from_deep_table() {
    let input = "[a.b.c]\nkey = 42\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.promote_key("a.b.c.key").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("key = 42"), "promoted key missing: {out}");
}

// ============================================================
// move_key_create
// ============================================================

#[test]
fn test_move_key_create_new_section() {
    let input = "[meta]\nname = \"Test\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .move_key_create("meta.name", "game.name")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("[game]"), "new section header missing: {out}");
    assert!(out.contains("name = \"Test\""), "moved key missing: {out}");
}

#[test]
fn test_move_key_create_existing_section() {
    // When destination exists, behaves like regular move_key
    let input = "[meta]\nname = \"Test\"\n[game]\nversion = 1\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .move_key_create("meta.name", "game.name")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("[game]"), "section missing: {out}");
    assert!(out.contains("name = \"Test\""), "moved key missing: {out}");
    assert!(out.contains("version = 1"), "existing key lost: {out}");
}

#[test]
fn test_move_key_create_to_root() {
    let input = "[meta]\nname = \"Test\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .move_key_create("meta.name", "name")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("name = \"Test\""), "moved key missing: {out}");
}

#[test]
fn test_move_key_create_preserves_formatting() {
    let input = "[meta]\n# comment\nname = \"Test\"  # inline\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .move_key_create("meta.name", "game.name")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("# comment"), "above comment lost: {out}");
    assert!(out.contains("# inline"), "inline comment lost: {out}");
}

#[test]
fn test_move_key_create_with_fluent_handle() {
    let input = "[meta]\nname = \"Test\"\n";
    let mut doc = parse(input).unwrap();
    doc.edit()
        .move_key_create("meta.name", "game.name")
        .commit()
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("[game]"), "new section header missing: {out}");
    assert!(out.contains("name = \"Test\""), "moved key missing: {out}");
}

// ============================================================
// reorder_root
// ============================================================

#[test]
fn test_reorder_root_scalars_before_tables() {
    // Scalars MUST come before tables in valid TOML
    let input =
        "root = 1\nbase = \"my-base\"\nprofiles = [\"a\", \"b\"]\n[meta]\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .reorder_root(&["meta", "base", "profiles", "root"])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let meta_pos = out.find("[meta]").unwrap();
    let base_pos = out.find("base =").unwrap();
    let prof_pos = out.find("profiles =").unwrap();
    assert!(meta_pos < base_pos, "[meta] should be before base: {out}");
    assert!(base_pos < prof_pos, "base should be before profiles: {out}");
}

#[test]
fn test_reorder_root_preserves_comments() {
    let input = "# top comment\nbase = \"my-base\"\n[meta]\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .reorder_root(&["meta", "base"])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("# top comment"), "top comment lost: {out}");
}

#[test]
fn test_reorder_root_noop() {
    let input = "base = \"my-base\"\n[mypackage]\nname = \"mypackage\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    // Already in this order — should be a no-op
    editor
        .reorder_root(&["base", "mypackage"])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("base = \"my-base\""));
    assert!(out.contains("[mypackage]"));
}

#[test]
fn test_reorder_root_fluent() {
    let input = "base = \"my-base\"\n[meta]\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    doc.edit().reorder_root(&["meta", "base"]).commit().unwrap();
    let out = doc.to_string();
    let meta_pos = out.find("[meta]").unwrap();
    let base_pos = out.find("base =").unwrap();
    assert!(meta_pos < base_pos, "[meta] should be before base: {out}");
}

// ── reorder_root edge cases ───────────────────────────────────

#[test]
fn test_reorder_root_empty_document() {
    let mut doc = tomlini::FlatDoc::new();
    let mut editor = tomlini::editor::Editor::new();
    editor.reorder_root(&["anything"]).commit(&mut doc).unwrap();
    assert_eq!(doc.to_string(), "");
}

#[test]
fn test_reorder_root_entry_not_in_doc_is_skipped() {
    let input = "base = \"my-base\"\n[meta]\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    // "ghost" is not in the document — silently skipped. Listed entries keep.
    editor
        .reorder_root(&["ghost", "base", "meta"])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let base_pos = out.find("base =").unwrap();
    let meta_pos = out.find("[meta]").unwrap();
    assert!(base_pos < meta_pos, "base should be before [meta]: {out}");
}

#[test]
fn test_reorder_root_entry_in_doc_not_in_order_is_dropped() {
    let input = "a = 1\nb = 2\nc = 3\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    // Only list "c" and "a" — "b" is omitted and should disappear
    editor.reorder_root(&["c", "a"]).commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        !out.contains("b ="),
        "\"b\" should be dropped when not in order list: {out}"
    );
    assert!(out.contains("c ="), "\"c\" should be present: {out}");
    assert!(out.contains("a ="), "\"a\" should be present: {out}");
}

#[test]
fn test_reorder_root_table_only_document() {
    let input = "[z]\nk = 1\n[a]\nk = 2\n[m]\nk = 3\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .reorder_root(&["a", "m", "z"])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let a_pos = out.find("[a]").unwrap();
    let m_pos = out.find("[m]").unwrap();
    let z_pos = out.find("[z]").unwrap();
    assert!(a_pos < m_pos, "[a] before [m]: {out}");
    assert!(m_pos < z_pos, "[m] before [z]: {out}");
}

#[test]
fn test_reorder_root_single_entry_is_noop() {
    let input = "[only]\nk = 1\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.reorder_root(&["only"]).commit(&mut doc).unwrap();
    assert!(doc.to_string().contains("[only]"));
}

#[test]
fn test_reorder_root_preserves_inter_entry_comments() {
    // Comments BETWEEN root entries must survive reorder_root
    let input = "base = \"my-base\"\n# comment before meta\n[meta]\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .reorder_root(&["meta", "base"])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("# comment before meta"),
        "comment between entries was dropped during reorder_root: {out}"
    );
}

#[test]
fn test_reorder_root_following_anchor_moves_comment_with_section() {
    // Comment preceding a section header moves with the section in Following mode
    let input = "base = \"my-base\"\n# comment for meta\n[meta]\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .reorder_root_bring(
            &["meta", "base"],
            tomlini::editor::BringAlong::COMMENTS_ABOVE,
        )
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let comment_pos = out.find("# comment for meta").unwrap();
    let meta_pos = out.find("[meta]").unwrap();
    assert!(
        comment_pos < meta_pos,
        "comment should precede [meta] with Following anchor: {out}"
    );
}

// ============================================================
#[test]
fn test_pont_pipeline_reorder_tables() {
    // Simulates the pont fmt pipeline: parse a profile-style TOML config,
    // reorder root-level entries so that [base] comes first, then [meta],
    // then [profiles].
    let input = "\
# My project profiles
[profiles.dev]
env = { FOO = \"dev\" }
build = \"cargo build\"

[meta]
name = \"my-project\"

[base]
extends = []
build = \"echo hi\"
";
    let mut doc = parse(input).unwrap();

    // Step 1: compute desired order from doc.keys() + policy
    // Verify root entries before reordering
    let _keys = doc.keys(); // verify index is populated
    assert_eq!(_keys.len(), 3, "expected 3 root entries: {_keys:?}");
    // Policy: [base], [meta], [profiles]
    let order = &["base", "meta", "profiles"];

    // Step 2: reorder
    doc.edit().reorder_root(order).commit().unwrap();

    // Step 3: verify
    let out = doc.to_string();
    let base_pos = out.find("[base]").unwrap();
    let meta_pos = out.find("[meta]").unwrap();
    // Dotted headers keep their full name as written
    let profiles_pos = out.find("[profiles.dev]").unwrap();
    assert!(base_pos < meta_pos, "[base] before [meta]: {out}");
    assert!(
        meta_pos < profiles_pos,
        "[meta] before [profiles.dev]: {out}"
    );
    assert!(out.contains("name = \"my-project\""));
    assert!(out.contains("FOO = \"dev\""));
    assert!(
        out.contains("# My project profiles"),
        "top comment lost: {out}"
    );
}

#[test]
fn test_pont_pipeline_promote_then_reorder() {
    // Simulates the pont fmt pipeline when scalars have been absorbed
    // into [meta] (TOML spec footgun).  Promote them back to root,
    // then reorder scalars before tables.
    let input = "\
# project config
[meta]
name = \"my-project\"

[meta]
base = \"my-base\"
kind = \"leaf\"
";
    let mut doc = parse(input).unwrap();

    // Step 1: promote absorbed scalars to root
    // (base and kind were absorbed into the second [meta] per TOML spec)
    let _keys = doc.keys(); // verify index
    doc.edit()
        .promote_key("meta.base")
        .promote_key("meta.kind")
        .commit()
        .unwrap();

    // Step 2: verify promoted keys are at root
    assert!(doc.has("base"), "base should be at root after promote");
    assert!(doc.has("kind"), "kind should be at root after promote");

    // Step 3: reorder — scalars before tables, alphabetically
    doc.edit()
        .reorder_root(&["base", "kind", "meta"])
        .commit()
        .unwrap();

    // Step 4: verify order
    let out = doc.to_string();
    let base_pos = out.find("base =").unwrap();
    let kind_pos = out.find("kind =").unwrap();
    let meta_pos = out.find("[meta]").unwrap();
    assert!(base_pos < kind_pos, "base before kind: {out}");
    assert!(kind_pos < meta_pos, "kind before [meta]: {out}");

    // Step 5: content and comments preserved
    assert!(out.contains("name = \"my-project\""));
    assert!(out.contains("# project config"));
}

// ============================================================
// move_key
// ============================================================

#[test]
fn test_move_key_cross_table() {
    let input = "[a]\nkey = 1\n[b]\nother = 2\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.move_key("a.key", "b.key").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("[b]"), "target section missing: {out}");
    assert!(out.contains("key = 1"), "moved key missing from [b]: {out}");
    assert!(out.contains("other = 2"), "existing key lost: {out}");
}

#[test]
fn test_move_key_to_root() {
    let input = "[server]\nport = 8080\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .move_key("server.port", "port")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("port = 8080"), "moved key missing: {out}");
}

#[test]
fn test_move_key_preserves_formatting() {
    let input = "[a]\n# above\nkey = \"val\"  # inline\n[b]\nother = 2\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.move_key("a.key", "b.key").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("# above"), "above comment lost: {out}");
    assert!(out.contains("# inline"), "inline comment lost: {out}");
}

// ============================================================
// rename_key
// ============================================================

#[test]
fn test_rename_key_simple() {
    let input = "old_name = 42\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .rename_key("old_name", "new_name")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(!out.contains("old_name"), "old key still present: {out}");
    assert!(out.contains("new_name"), "new key missing: {out}");
    assert!(out.contains("42"), "value lost: {out}");
}

#[test]
fn test_rename_key_in_table() {
    let input = "[server]\nhostname = \"old\"\nport = 8080\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .rename_key("server.hostname", "server.host")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(!out.contains("hostname"), "old key still present: {out}");
    assert!(out.contains("host"), "new key missing: {out}");
    assert!(out.contains("port = 8080"), "sibling key lost: {out}");
}

#[test]
fn test_rename_key_preserves_value_formatting() {
    let input = "old_name = \"val\" # inline\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .rename_key("old_name", "new_name")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("# inline"), "inline comment lost: {out}");
}

#[test]
fn test_rename_key_fluent() {
    let input = "old_name = 42\n";
    let mut doc = parse(input).unwrap();
    doc.edit()
        .rename_key("old_name", "new_name")
        .commit()
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("new_name"), "new key missing: {out}");
}

// ============================================================
// insert_section
// ============================================================

#[test]
fn test_insert_section_creates_header() {
    let input = "root = 1\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.insert_section("mysection").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("[mysection]"), "section header missing: {out}");
    assert!(out.contains("root = 1"), "existing key lost: {out}");
}

#[test]
fn test_insert_section_idempotent() {
    let input = "[mysection]\nkey = 1\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.insert_section("mysection").commit(&mut doc).unwrap();
    // Should be a no-op — section already exists
    let out = doc.to_string();
    assert_eq!(
        out.matches("[mysection]").count(),
        1,
        "duplicate header: {out}"
    );
}

#[test]
fn test_insert_section_into_empty() {
    let mut doc = tomlini::FlatDoc::new();
    let mut editor = tomlini::editor::Editor::new();
    editor.insert_section("mysection").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert_eq!(out, "[mysection]\n");
}

// ============================================================
// array_push multiline
// ============================================================

#[test]
fn test_array_push_multiline() {
    let input = "hosts = [\n  \"a\",\n  \"b\",\n]\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .array_push("hosts", "\"c\"")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("\"c\""), "new element missing: {out}");
    assert!(out.contains("\"a\""), "existing element lost: {out}");
    assert!(out.contains("\"b\""), "existing element lost: {out}");
}

// ============================================================
// array_set
// ============================================================

#[test]
fn test_array_set_first_element() {
    let input = "ports = [80, 443, 8080]\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.array_set("ports", 0, "22").commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(out.contains("22"), "new value missing: {out}");
    assert!(!out.contains("80,"), "old value '80,' still present: {out}");
}

#[test]
fn test_array_set_last_element() {
    let input = "ports = [80, 443, 8080]\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .array_set("ports", 2, "9090")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("9090"), "new value missing: {out}");
}
// ============================================================
// aot_push
// ============================================================

#[test]
fn test_aot_push_adds_entry() {
    let input = "[[server]]\nhost = \"a\"\nport = 1\n[[server]]\nhost = \"b\"\nport = 2\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .aot_push("server", &[("host", "\"c\""), ("port", "3")])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("host = \"c\""),
        "new entry host missing: {out}"
    );
    assert!(out.contains("port = 3"), "new entry port missing: {out}");
}

#[test]
fn test_aot_push_first_entry() {
    let input = "[[server]]\nhost = \"a\"\nport = 1\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .aot_push("server", &[("host", "\"b\""), ("port", "2")])
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let count = out.matches("[[server]]").count();
    assert_eq!(
        count, 2,
        "expected 2 [[server]] entries, got {count}: {out}"
    );
}

// ============================================================
// aot_set
// ============================================================

#[test]
fn test_aot_set_modifies_entry() {
    let input = "[[server]]\nhost = \"a\"\nport = 1\n[[server]]\nhost = \"b\"\nport = 2\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .aot_set("server", 0, "port", "9000")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("port = 9000"), "modified value missing: {out}");
    assert!(out.contains("port = 2"), "second entry lost: {out}");
}

// ============================================================
// ── aot_remove ───────────────────────────────────────────────

#[test]
fn test_aot_remove_first_entry() {
    let input = "[[server]]\nhost = \"a\"\nport = 1\n[[server]]\nhost = \"b\"\nport = 2\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.aot_remove("server", 0).commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        !out.contains("host = \"a\""),
        "removed entry 'a' still present: {out}"
    );
    assert!(
        out.contains("host = \"b\""),
        "remaining entry 'b' lost: {out}"
    );
    assert_eq!(
        out.matches("[[server]]").count(),
        1,
        "should have 1 [[server]] entry left: {out}"
    );
}

#[test]
fn test_aot_remove_last_entry() {
    let input = "[[server]]\nhost = \"a\"\nport = 1\n[[server]]\nhost = \"b\"\nport = 2\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.aot_remove("server", 1).commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("host = \"a\""),
        "remaining entry 'a' lost: {out}"
    );
    assert!(
        !out.contains("host = \"b\""),
        "removed entry 'b' still present: {out}"
    );
}

#[test]
fn test_aot_remove_only_entry() {
    let input = "[[server]]\nhost = \"a\"\nport = 1\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor.aot_remove("server", 0).commit(&mut doc).unwrap();
    let out = doc.to_string();
    assert!(
        !out.contains("[[server]]"),
        "removed entry still present: {out}"
    );
}

#[test]
fn test_aot_remove_out_of_bounds() {
    let input = "[[server]]\nhost = \"a\"\n";
    let mut doc = parse(input).unwrap();
    let mut e = tomlini::editor::Editor::new();
    e.aot_remove("server", 99);
    assert!(matches!(
        e.commit(&mut doc).unwrap_err(),
        EditError::InvalidPath
    ));
}

#[test]
fn test_aot_remove_nonexistent() {
    let input = "x = 1\n";
    let mut doc = parse(input).unwrap();
    let mut e = tomlini::editor::Editor::new();
    e.aot_remove("nonexistent", 0);
    assert!(matches!(
        e.commit(&mut doc).unwrap_err(),
        EditError::InvalidPath
    ));
}

#[test]
fn test_aot_remove_fluent() {
    let input = "[[server]]\nhost = \"a\"\n[[server]]\nhost = \"b\"\n";
    let mut doc = parse(input).unwrap();
    doc.edit().aot_remove("server", 1).commit().unwrap();
    let out = doc.to_string();
    assert_eq!(out.matches("[[server]]").count(), 1);
}

// ============================================================
#[test]
fn test_chain_set_remove_insert_rename() {
    let input = "[package]\nname = \"old\"\nversion = \"1.0\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = tomlini::editor::Editor::new();
    editor
        .set("package.version", "\"2.0\"")
        .remove("package.name")
        .insert("package", "license", "\"MIT\"")
        .rename_key("package.version", "package.ver")
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(!out.contains("version"), "renamed key still present: {out}");
    assert!(
        out.contains("ver = \"2.0\""),
        "renamed+set value wrong: {out}"
    );
    assert!(
        out.contains("license = \"MIT\""),
        "inserted key missing: {out}"
    );
}

#[test]
fn test_chain_promote_then_reorder() {
    let input = "[meta]\nbase = \"my-base\"\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    // Verify promote_key actually moves base to root
    doc.edit().promote_key("meta.base").commit().unwrap();
    let promoted = doc.to_string();
    assert!(
        doc.has("base"),
        "promote_key failed: base not at root. Doc: {promoted}"
    );
    assert!(
        !doc.has("meta.base"),
        "promote_key failed: meta.base still exists. Doc: {promoted}"
    );
    // Then reorder
    doc.edit().reorder_root(&["base", "meta"]).commit().unwrap();
    let out = doc.to_string();
    let base_pos = out.find("base =").unwrap();
    let meta_pos = out.find("[meta]").unwrap();
    assert!(base_pos < meta_pos, "base should be before [meta]: {out}");
}

// ── build_index coverage: dotted table headers ───────────────

#[test]
fn test_index_dotted_table_header() {
    // Exercise build_index's Dot handling for [a.b.c] headers.
    let input = "[profiles.dev]\nenv = \"dev\"\nport = 8000\n";
    let mut doc = parse(input).unwrap();
    // After parse: index is None. Trigger build via accessor.
    assert!(doc.has("profiles.dev.env"), "should find profiles.dev.env");
    assert!(
        doc.has("profiles.dev.port"),
        "should find profiles.dev.port"
    );
    assert!(!doc.has("profiles.env"), "should not find wrong path");
    // is_table on the first segment
    assert!(doc.is_table("profiles"), "profiles should be a table");
}

#[test]
fn test_index_aot_and_dotted_mixed() {
    // Exercise ArrayTableClose + Dot in build_index.
    let input = "[[server]]\nhost = \"a\"\nport = 1\n[server.http]\nenabled = true\n";
    let mut doc = parse(input).unwrap();
    // AOT key is server (first segment), and sub-keys exist
    let keys = doc.keys();
    assert!(
        keys.contains(&"server".to_string()),
        "server should be in keys: {keys:?}"
    );
    assert!(
        doc.has("server.http.enabled"),
        "server.http.enabled should exist"
    );
    assert!(doc.is_table("server"), "server should be a table");
}

// ============================================================
// BringAlong coverage — each flag x each _bring method
// ============================================================

// ── move_key_bring ──────────────────────────────────────────

#[test]
fn test_move_key_bring_comments_above() {
    // Comment above the key moves with the key to the new table.
    let input = "[a]\n# this describes k\nk = 1\nx = 2\n[b]\ny = 3\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    editor
        .move_key_bring("a.k", "b.k", BringAlong::COMMENTS_ABOVE)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let comment_pos = out.find("# this describes k").unwrap();
    let b_start = out.find("[b]").unwrap();
    assert!(
        b_start < comment_pos,
        "comment should be inside [b] section after move: {out}"
    );
}

#[test]
fn test_move_key_bring_comments_below() {
    let input = "[a]\nk = 1\n# comment after k\nx = 2\n[b]\ny = 3\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    editor
        .move_key_bring("a.k", "b.k", BringAlong::COMMENTS_BELOW)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let comment_pos = out.find("# comment after k").unwrap();
    let b_start = out.find("[b]").unwrap();
    assert!(
        b_start < comment_pos,
        "comment below key should move to [b]: {out}"
    );
}

#[test]
fn test_move_key_bring_everything_above() {
    // Everything above the key (including blank lines) moves.
    let input = "[a]\nx = 2\n\n# comment for k\nk = 1\n[b]\ny = 3\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    editor
        .move_key_bring("a.k", "b.k", BringAlong::EVERYTHING_ABOVE)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("# comment for k"), "comment lost: {out}");
    // The blank line above the comment should also have moved — verify the comment is in [b]
    let comment_pos = out.find("# comment for k").unwrap();
    let b_pos = out.find("[b]").unwrap();
    assert!(
        b_pos < comment_pos,
        "everything above should be in [b] section: {out}"
    );
}

#[test]
fn test_move_key_bring_combo_above_and_below() {
    let input = "[a]\nx = 2\n# above k\nk = 1\n# below k\ny = 3\n[b]\nz = 4\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    let bring = BringAlong::COMMENTS_ABOVE | BringAlong::COMMENTS_BELOW;
    editor
        .move_key_bring("a.k", "b.k", bring)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    let above_pos = out.find("# above k").unwrap();
    let below_pos = out.find("# below k").unwrap();
    let b_pos = out.find("[b]").unwrap();
    assert!(b_pos < above_pos, "# above k should be in [b]: {out}");
    assert!(b_pos < below_pos, "# below k should be in [b]: {out}");
}

// ── promote_key_bring ───────────────────────────────────────

#[test]
fn test_promote_key_bring_comments_above() {
    let input = "[meta]\nname = \"proj\"\n# base configuration\nbase = \"my-base\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    editor
        .promote_key_bring("meta.base", BringAlong::COMMENTS_ABOVE)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(
        out.contains("base = \"my-base\""),
        "promoted key missing: {out}"
    );
    assert!(out.contains("# base configuration"), "comment lost: {out}");
    // Comment should be at root level, near base
    let comment_pos = out.find("# base configuration").unwrap();
    let base_pos = out.find("base =").unwrap();
    assert!(
        comment_pos < base_pos,
        "comment should precede base at root: {out}"
    );
}

#[test]
fn test_promote_key_bring_comments_below() {
    let input = "[meta]\nname = \"proj\"\nbase = \"my-base\"\n# note about base\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    editor
        .promote_key_bring("meta.base", BringAlong::COMMENTS_BELOW)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("# note about base"), "comment lost: {out}");
    let comment_pos = out.find("# note about base").unwrap();
    let base_pos = out.find("base =").unwrap();
    assert!(
        base_pos < comment_pos,
        "comment should follow base at root: {out}"
    );
}

// ── move_key_create_bring ───────────────────────────────────

#[test]
fn test_move_key_create_bring_comments_above() {
    let input = "[a]\n# license info\nk = \"MIT\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    editor
        .move_key_create_bring("a.k", "game.k", BringAlong::COMMENTS_ABOVE)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("[game]"), "new section not created: {out}");
    assert!(out.contains("# license info"), "comment lost: {out}");
    let comment_pos = out.find("# license info").unwrap();
    let game_pos = out.find("[game]").unwrap();
    assert!(
        game_pos < comment_pos,
        "comment should be inside [game]: {out}"
    );
}

// ── reorder_root_bring combinations ─────────────────────────

#[test]
fn test_reorder_root_bring_combo() {
    let input = "base = \"my-base\"\n# comment for meta\n[meta]\nkind = \"leaf\"\n";
    let mut doc = parse(input).unwrap();
    let mut editor = Editor::new();
    let bring = BringAlong::COMMENTS_ABOVE | BringAlong::COMMENTS_BELOW;
    editor
        .reorder_root_bring(&["meta", "base"], bring)
        .commit(&mut doc)
        .unwrap();
    let out = doc.to_string();
    assert!(out.contains("# comment for meta"), "comment lost: {out}");
    let comment_pos = out.find("# comment for meta").unwrap();
    let meta_pos = out.find("[meta]").unwrap();
    assert!(
        comment_pos < meta_pos,
        "comment should precede [meta]: {out}"
    );
}