animsmith 0.1.0

A linter for skeletal animation clips: game-engine-friendliness checks for glTF/GLB and FBX animations
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
use animsmith_core::glam::Quat;
use animsmith_core::model::*;
use animsmith_gltf::fix::{FixSession, Repair as GltfRepair};
use animsmith_testkit::{quats_from_angles, scaled_quat, two_bone_rotation_doc};
use serde_json::{Value, json};
use std::path::PathBuf;
use std::process::{Command, Output};

fn animsmith() -> Command {
    Command::new(env!("CARGO_BIN_EXE_animsmith"))
}

fn fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("testdata")
        .join(name)
}

fn unique_temp_dir(name: &str) -> tempfile::TempDir {
    tempfile::Builder::new()
        .prefix(&format!("animsmith-cli-{name}-"))
        .tempdir()
        .expect("creates temp dir")
}

/// Analytic rotation sequence: consecutive y-rotations 0.4 rad apart,
/// so every adjacent pair has a positive dot product — the clean form
/// is exactly the un-negated sequence.
fn sway_quats(flipped: bool) -> Vec<Quat> {
    let mut quats = quats_from_angles(&[0.0, 0.4, 0.8, 1.2, 1.6]);
    if flipped {
        quats[1] = -quats[1];
        quats[3] = -quats[3];
    }
    quats
}

fn sway_doc_with_quats(quats: Vec<Quat>) -> Document {
    two_bone_rotation_doc("sway", quats, false)
}

fn sway_doc(flipped: bool) -> Document {
    sway_doc_with_quats(sway_quats(flipped))
}

fn sway_doc_with_distinct_repairs() -> Document {
    let mut quats = sway_quats(true);
    quats[1] = scaled_quat(quats[1], 1.2);
    sway_doc_with_quats(quats)
}

fn write_flipped_glb(path: &std::path::Path) {
    animsmith_gltf::write::write(&sway_doc(true), path).expect("writes flipped fixture");
}

fn write_distinct_repair_glb(path: &std::path::Path) {
    animsmith_gltf::write::write(&sway_doc_with_distinct_repairs(), path)
        .expect("writes distinct repair fixture");
}

fn write_clean_glb(path: &std::path::Path) {
    animsmith_gltf::write::write(&sway_doc(false), path).expect("writes clean fixture");
}

fn write_json(path: &std::path::Path, value: &Value) {
    std::fs::write(
        path,
        serde_json::to_vec_pretty(value).expect("serializes JSON fixture"),
    )
    .expect("writes JSON fixture");
}

fn measurement_report(duration_s: f64) -> Value {
    json!({
        "schema_version": 1,
        "files": [{
            "path": "fixture.gltf",
            "rig": { "profile": "unknown" },
            "measurements": {
                "walk": {
                    "duration_s": duration_s,
                    "frame_count": 31,
                    "animated_bones": [],
                    "bone_rotation_range_deg": {}
                }
            }
        }]
    })
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

const EMPTY_ANIMATION_GLTF: &str = r#"{
  "asset": { "version": "2.0" },
  "nodes": [{ "name": "root" }],
  "animations": [{ "name": "empty", "samplers": [], "channels": [] }],
  "scenes": [{ "nodes": [0] }],
  "scene": 0
}"#;

#[test]
fn transform_summary_reports_a_loaded_clip_omitted_from_the_artifact() {
    let dir = unique_temp_dir("transform-empty-animation");
    let input = dir.path().join("empty-animation.gltf");
    let output_path = dir.path().join("transformed.glb");
    std::fs::write(&input, EMPTY_ANIMATION_GLTF).expect("writes empty animation fixture");

    let output = animsmith()
        .arg("transform")
        .arg(&input)
        .arg("-o")
        .arg(&output_path)
        .output()
        .expect("runs transform");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr:\n{}",
        stderr(&output)
    );
    let written = animsmith_gltf::load(&output_path).expect("loads transformed output");
    assert!(written.clips.is_empty(), "empty animation is not emitted");
    assert_eq!(
        stdout(&output),
        format!(
            "wrote {} (1 node(s), 0 clip(s), 0 mesh(es) / 0 position(s), 0 material(s)); dropped 1 clip(s) with no writable tracks\n",
            output_path.display()
        )
    );
}

#[test]
fn fix_rejects_unknown_repair_ids() {
    // Nonexistent input on purpose: flag validation must produce exit 2
    // regardless of file state, so no fixture is needed.
    let output = animsmith()
        .args(["fix", "clip.glb", "--dry-run", "--repair", "no-such-repair"])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    assert!(
        stderr(&output).contains("quat-flip"),
        "stderr should list valid repair ids:\n{}",
        stderr(&output)
    );
    assert!(
        stderr(&output).contains("quat-norm"),
        "stderr should list valid repair ids:\n{}",
        stderr(&output)
    );
}

#[test]
fn fix_rejects_removed_group_flags() {
    // `--group` and `--list-repairs` were removed in the pre-publish
    // contract trim; wrapper scripts still passing them must fail
    // loudly, not silently change meaning.
    for removed in [&["--group", "default"][..], &["--list-repairs"][..]] {
        let output = animsmith()
            .args(["fix", "clip.glb"])
            .args(removed)
            .output()
            .expect("runs animsmith");

        assert_eq!(
            output.status.code(),
            Some(2),
            "{removed:?} must be rejected; stdout:\n{}",
            stdout(&output)
        );
        assert!(
            stderr(&output).contains("unexpected argument"),
            "stderr:\n{}",
            stderr(&output)
        );
    }
}

#[test]
fn fix_requires_an_explicit_write_target() {
    let output = animsmith()
        .args(["fix", "clip.glb"])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    assert!(
        stderr(&output).contains("fix requires --output <PATH> or --in-place"),
        "stderr:\n{}",
        stderr(&output)
    );
}

#[test]
fn fix_dry_run_reports_without_writing() {
    let dir = unique_temp_dir("fix-dry-run");
    let input = dir.path().join("dirty.glb");
    write_flipped_glb(&input);
    let before = std::fs::read(&input).expect("reads input");

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--dry-run",
            "--repair",
            "quat-flip",
        ])
        .output()
        .expect("runs animsmith");

    // Pending repairs are findings: dry run exits 1 (the check mode),
    // and the input is untouched.
    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    assert!(
        stdout(&output).contains("would be fixed"),
        "stdout:\n{}",
        stdout(&output)
    );
    assert_eq!(before, std::fs::read(&input).expect("reads input"));
}

#[test]
fn fix_dry_run_dedupes_duplicate_repairs() {
    let dir = unique_temp_dir("fix-dry-run-dedup");
    let input = dir.path().join("dirty.glb");
    write_flipped_glb(&input);

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--dry-run",
            "--repair",
            "quat-flip,quat-flip",
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    let out = stdout(&output);
    assert!(
        out.contains("2 key(s) would be fixed across 1 track(s)"),
        "stdout:\n{out}"
    );
    assert_eq!(
        out.matches("key(s) would be fixed across").count(),
        1,
        "duplicate repairs should be reported once:\n{out}"
    );
}

#[test]
fn fix_dry_run_dedupes_non_adjacent_distinct_repairs_without_writing() {
    let dir = unique_temp_dir("fix-dry-run-compose");
    let input = dir.path().join("dirty.glb");
    write_distinct_repair_glb(&input);
    let before = std::fs::read(&input).expect("reads input");

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--dry-run",
            "--repair",
            "quat-norm,quat-flip,quat-norm",
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    let out = stdout(&output);
    assert!(out.contains("would fix[quat-norm]"), "stdout:\n{out}");
    assert!(out.contains("would fix[quat-flip]"), "stdout:\n{out}");
    assert_eq!(
        out.matches("would fix[quat-norm]").count(),
        1,
        "non-adjacent duplicate repairs should be reported once:\n{out}"
    );
    assert_eq!(before, std::fs::read(&input).expect("reads input"));
    assert_eq!(
        FixSession::inspect(&input, GltfRepair::QuatNorm)
            .expect("inspects dirty input")
            .total_fixed(),
        1
    );
    assert_eq!(
        FixSession::inspect(&input, GltfRepair::QuatFlip)
            .expect("inspects dirty input")
            .total_fixed(),
        2
    );
}

#[test]
fn fix_dry_run_labels_each_repair_with_its_action() {
    // The distinct-repair fixture needs both a quat-norm (non-unit key)
    // and a quat-flip (hemisphere) repair on the same bone, so the report
    // prints one per-track line per repair. Each line must carry its own
    // action suffix; a swapped or stale Repair::action() would pair the
    // wrong verb with the id.
    let dir = unique_temp_dir("fix-action-labels");
    let input = dir.path().join("dirty.glb");
    write_distinct_repair_glb(&input);

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--dry-run",
            "--repair",
            "quat-norm,quat-flip",
        ])
        .output()
        .expect("runs animsmith");

    let out = stdout(&output);
    let norm_line = out
        .lines()
        .find(|l| l.contains("would fix[quat-norm]"))
        .unwrap_or_else(|| panic!("no quat-norm track line:\n{out}"));
    assert!(
        norm_line.contains("unit-normalized"),
        "quat-norm line must report unit-normalized: {norm_line}"
    );
    let flip_line = out
        .lines()
        .find(|l| l.contains("would fix[quat-flip]"))
        .unwrap_or_else(|| panic!("no quat-flip track line:\n{out}"));
    assert!(
        flip_line.contains("hemisphere-normalized"),
        "quat-flip line must report hemisphere-normalized: {flip_line}"
    );
}

#[test]
fn fix_dry_run_on_clean_input_exits_zero() {
    let dir = unique_temp_dir("fix-dry-run-clean");
    let input = dir.path().join("clean.glb");
    write_clean_glb(&input);

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--dry-run",
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    assert!(
        stdout(&output).contains("0 key(s) would be fixed"),
        "stdout:\n{}",
        stdout(&output)
    );
}

#[test]
fn fix_dry_run_skipped_tracks_do_not_fail_the_check() {
    // A .gltf written by the writer embeds its buffer as a data URI,
    // which fix cannot patch: the track is reported as skipped. The
    // dry-run exit code reflects repairs fix would PERFORM — skipped
    // tracks print loudly but exit 0; detection-only gating is lint's
    // job (the quat-flip check).
    let dir = unique_temp_dir("fix-dry-run-skip");
    let input = dir.path().join("dirty.gltf");
    animsmith_gltf::write::write(&sway_doc(true), &input).expect("writes gltf fixture");

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--dry-run",
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    assert!(
        stdout(&output).contains("skipped[quat-flip]"),
        "stdout:\n{}",
        stdout(&output)
    );
}

#[test]
fn fix_dry_run_conflicts_with_write_targets() {
    for write_flag in [&["-o", "out.glb"][..], &["--in-place"][..]] {
        let output = animsmith()
            .args(["fix", "clip.glb", "--dry-run"])
            .args(write_flag)
            .output()
            .expect("runs animsmith");

        assert_eq!(
            output.status.code(),
            Some(2),
            "--dry-run with {write_flag:?} must be rejected; stdout:\n{}",
            stdout(&output)
        );
        assert!(
            stderr(&output).contains("--dry-run"),
            "stderr:\n{}",
            stderr(&output)
        );
    }
}

#[test]
fn fix_default_repairs_write_output() {
    let dir = unique_temp_dir("fix-output");
    let input = dir.path().join("dirty.glb");
    let output_path = dir.path().join("fixed.glb");
    write_flipped_glb(&input);

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--output",
            output_path.to_str().expect("utf-8 output path"),
        ])
        .output()
        .expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    assert!(output_path.exists());

    // Analytic oracle: hemisphere normalization must restore exactly
    // the un-flipped source sequence (negation is a lossless bit flip).
    let fixed = animsmith_gltf::load(&output_path).expect("loads fixed output");
    let TrackValues::Quats(quats) = &fixed.clips[0].tracks[0].values else {
        panic!("rotation track expected");
    };
    let expected = sway_quats(false);
    for (got, want) in quats.iter().zip(&expected) {
        assert_eq!(got.to_array(), want.to_array());
    }
}

#[test]
fn fix_write_composes_distinct_repairs() {
    let dir = unique_temp_dir("fix-output-compose");
    let input = dir.path().join("dirty.glb");
    let output_path = dir.path().join("fixed.glb");
    write_distinct_repair_glb(&input);

    assert_eq!(
        FixSession::inspect(&input, GltfRepair::QuatNorm)
            .expect("inspects dirty input")
            .total_fixed(),
        1
    );
    assert_eq!(
        FixSession::inspect(&input, GltfRepair::QuatFlip)
            .expect("inspects dirty input")
            .total_fixed(),
        2
    );

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--output",
            output_path.to_str().expect("utf-8 output path"),
            "--repair",
            "quat-norm,quat-flip",
        ])
        .output()
        .expect("runs animsmith");

    assert!(
        output.status.success(),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    let out = stdout(&output);
    assert!(out.contains("fixed[quat-norm]"), "stdout:\n{out}");
    assert!(out.contains("fixed[quat-flip]"), "stdout:\n{out}");

    assert_eq!(
        FixSession::inspect(&output_path, GltfRepair::QuatNorm)
            .expect("inspects fixed output")
            .total_fixed(),
        0
    );
    assert_eq!(
        FixSession::inspect(&output_path, GltfRepair::QuatFlip)
            .expect("inspects fixed output")
            .total_fixed(),
        0
    );

    let fixed = animsmith_gltf::load(&output_path).expect("loads fixed output");
    let TrackValues::Quats(quats) = &fixed.clips[0].tracks[0].values else {
        panic!("rotation track expected");
    };
    for (got, want) in quats.iter().zip(sway_quats(false)) {
        assert!(
            got.dot(want).abs() > 1.0 - 1e-5,
            "composed repairs must preserve the represented rotation"
        );
    }
}

#[test]
fn fix_write_dedupes_duplicate_repairs() {
    let dir = unique_temp_dir("fix-output-dedup");
    let input = dir.path().join("dirty.glb");
    let output_path = dir.path().join("fixed.glb");
    write_flipped_glb(&input);

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--output",
            output_path.to_str().expect("utf-8 output path"),
            "--repair",
            "quat-flip,quat-flip",
        ])
        .output()
        .expect("runs animsmith");

    assert!(
        output.status.success(),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    let out = stdout(&output);
    assert_eq!(
        out.matches("key(s) fixed across").count(),
        1,
        "duplicate repairs should be reported once:\n{out}"
    );
    assert_eq!(
        FixSession::inspect(&output_path, GltfRepair::QuatFlip)
            .expect("inspects fixed output")
            .total_fixed(),
        0
    );
}

#[test]
fn fix_in_place_writes_selected_repair() {
    let dir = unique_temp_dir("fix-in-place");
    let input = dir.path().join("dirty.glb");
    write_flipped_glb(&input);
    assert_eq!(
        FixSession::inspect(&input, GltfRepair::QuatFlip)
            .expect("inspects dirty input")
            .total_fixed(),
        2
    );

    let output = animsmith()
        .args([
            "fix",
            input.to_str().expect("utf-8 input path"),
            "--in-place",
            "--repair",
            "quat-flip",
        ])
        .output()
        .expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    assert_eq!(
        FixSession::inspect(&input, GltfRepair::QuatFlip)
            .expect("inspects fixed input")
            .total_fixed(),
        0
    );
}

#[test]
fn help_matches_compiled_feature_set() {
    let output = animsmith().arg("--help").output().expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    let out = stdout(&output);
    assert!(out.contains("inspect"));
    assert!(out.contains("measure"));
    assert!(out.contains("lint"));
    assert!(out.contains("transform"));
    assert!(out.contains("fix"));
    assert!(out.contains("diff"));

    // One-line summaries come from the doc comments (clap derives
    // `about` from the first line); pin them so description drift is
    // visible.
    assert!(out.contains("Repair safe mechanical glTF/GLB defects"));
    assert!(out.contains("Apply mechanical clip transforms"));
    assert!(out.contains("Compare animation measurements"));

    assert_eq!(out.contains("\n  convert "), cfg!(feature = "fbx"), "{out}");
    assert_eq!(
        out.contains("\n  report "),
        cfg!(feature = "report"),
        "{out}"
    );
}

#[test]
fn fix_help_lists_repair_possible_values() {
    let output = animsmith()
        .args(["fix", "--help"])
        .output()
        .expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    let out = stdout(&output);
    assert!(
        out.contains("[possible values: quat-norm, quat-flip]"),
        "stdout:\n{out}"
    );
}

#[test]
fn version_starts_with_manifest_version() {
    let output = animsmith()
        .arg("--version")
        .output()
        .expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    let out = stdout(&output);
    assert!(
        out.starts_with(concat!("animsmith ", env!("CARGO_PKG_VERSION"))),
        "{out}"
    );
}

#[test]
fn measure_json_uses_versioned_envelope() {
    let output = animsmith()
        .args([
            "measure",
            fixture("rig.gltf").to_str().expect("utf-8 fixture path"),
            "--format",
            "json",
        ])
        .output()
        .expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
    assert_eq!(json["schema_version"], 1);
    assert_eq!(json["tool"]["name"], "animsmith");
    assert!(
        json["tool"]["version"]
            .as_str()
            .is_some_and(|s| s.starts_with(env!("CARGO_PKG_VERSION"))),
        "{json:#}"
    );
    assert_eq!(json["command"], "measure");
    assert_eq!(json["summary"]["files"], 1);
    assert_eq!(json["summary"]["findings"]["error"], 0);
    assert!(
        json["schema"]
            .as_str()
            .is_some_and(|s| s.ends_with("output-v1.schema.json"))
    );

    let files = json["files"].as_array().expect("files array");
    assert_eq!(files.len(), 1);
    assert_eq!(files[0]["rig"]["profile"], "unknown");
    assert!(files[0]["findings"].is_null());
    assert!(files[0]["measurements"]["walk"]["duration_s"].is_number());
}

#[test]
fn lint_json_uses_versioned_envelope() {
    let output = animsmith()
        .args([
            "lint",
            fixture("rig.gltf").to_str().expect("utf-8 fixture path"),
            "--format",
            "json",
        ])
        .output()
        .expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
    assert_eq!(json["schema_version"], 1);
    assert!(
        json["schema"]
            .as_str()
            .is_some_and(|s| s.ends_with("output-v1.schema.json"))
    );
    assert_eq!(json["tool"]["name"], "animsmith");
    assert!(
        json["tool"]["version"]
            .as_str()
            .is_some_and(|s| s.starts_with(env!("CARGO_PKG_VERSION")))
    );
    assert_eq!(json["command"], "lint");
    assert_eq!(json["summary"]["files"], 1);
    assert!(json["files"][0]["findings"].is_array());
    assert!(json["files"][0]["measurements"]["walk"]["duration_s"].is_number());
}

#[test]
fn diff_json_uses_versioned_envelope() {
    let path = fixture("rig.gltf");
    let output = animsmith()
        .args([
            "diff",
            path.to_str().expect("utf-8 fixture path"),
            path.to_str().expect("utf-8 fixture path"),
            "--format",
            "json",
        ])
        .output()
        .expect("runs animsmith");

    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
    assert_eq!(json["schema_version"], 1);
    assert!(
        json["schema"]
            .as_str()
            .is_some_and(|s| s.ends_with("output-v1.schema.json"))
    );
    assert_eq!(json["tool"]["name"], "animsmith");
    assert!(
        json["tool"]["version"]
            .as_str()
            .is_some_and(|s| s.starts_with(env!("CARGO_PKG_VERSION")))
    );
    assert_eq!(json["command"], "diff");
    assert_eq!(json["summary"]["deltas"], 0);
    assert_eq!(json["deltas"].as_array().expect("deltas array").len(), 0);
    assert!(json["inputs"]["before"].is_string());
    assert!(json["inputs"]["after"].is_string());
}

#[test]
fn diff_accepts_single_file_measure_report_round_trip() {
    let dir = unique_temp_dir("diff-round-trip");
    let asset = fixture("rig.gltf");
    let report_path = dir.path().join("measure.json");

    let measured = animsmith()
        .args([
            "measure",
            asset.to_str().expect("utf-8 fixture path"),
            "--format",
            "json",
        ])
        .output()
        .expect("runs animsmith");
    assert!(measured.status.success(), "stderr:\n{}", stderr(&measured));
    std::fs::write(&report_path, &measured.stdout).expect("writes report");

    // A report diffed against the asset it was measured from is clean.
    let output = animsmith()
        .args([
            "diff",
            report_path.to_str().expect("utf-8 report path"),
            asset.to_str().expect("utf-8 fixture path"),
        ])
        .output()
        .expect("runs animsmith");
    // Clean == exit 0; the "no significant movement" prose is not the
    // contract (that's the exit code) and is left unpinned.
    assert_eq!(
        output.status.code(),
        Some(0),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
}

#[test]
fn diff_accepts_measurement_json_and_exits_one_for_deltas() {
    let dir = unique_temp_dir("diff-json-deltas");
    let before = dir.path().join("before.json");
    let after = dir.path().join("after.json");
    write_json(&before, &measurement_report(1.0));
    write_json(&after, &measurement_report(1.1));

    let output = animsmith()
        .args([
            "diff",
            before.to_str().expect("utf-8 before path"),
            after.to_str().expect("utf-8 after path"),
            "--format",
            "json",
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    // The CLI contract is the envelope shape + exit code: one delta,
    // routed to its clip. The metric/note strings are the unit suite's
    // job (diff.rs), so they are not re-pinned here.
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
    assert_eq!(json["summary"]["deltas"].as_u64(), Some(1));
    assert_eq!(json["deltas"][0]["clip"], "walk");
}

#[test]
fn diff_accepts_measurement_json_and_exits_zero_without_deltas() {
    let dir = unique_temp_dir("diff-json-clean");
    let before = dir.path().join("before.json");
    let after = dir.path().join("after.json");
    let report = measurement_report(1.0);
    write_json(&before, &report);
    write_json(&after, &report);

    let output = animsmith()
        .args([
            "diff",
            before.to_str().expect("utf-8 before path"),
            after.to_str().expect("utf-8 after path"),
        ])
        .output()
        .expect("runs animsmith");

    // Identical reports in, exit 0 out — the exit code is the contract,
    // not the human-format prose.
    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
}

#[test]
fn diff_text_format_renders_deltas_and_clean_summary() {
    // The default (human) format has its own render branch that the JSON
    // contract tests never exercise. This is the one test that owns that
    // branch: a dirty diff must name the moved clip and print a change
    // summary; a clean diff must print its clean line. (The envelope /
    // exit-code contract tests deliberately do NOT string-match this
    // prose — pinning the renderer is this test's job, not theirs.)
    let dir = unique_temp_dir("diff-text-format");
    let before = dir.path().join("before.json");
    let after = dir.path().join("after.json");
    write_json(&before, &measurement_report(1.0));
    write_json(&after, &measurement_report(1.1));

    let dirty = animsmith()
        .args([
            "diff",
            before.to_str().expect("utf-8 before path"),
            after.to_str().expect("utf-8 after path"),
        ])
        .output()
        .expect("runs animsmith");
    assert_eq!(dirty.status.code(), Some(1), "stderr:\n{}", stderr(&dirty));
    let out = stdout(&dirty);
    assert!(
        out.contains("walk"),
        "dirty Text output names the clip:\n{out}"
    );
    assert!(
        out.contains("significant change"),
        "dirty Text output summarizes the change count:\n{out}"
    );

    let clean = animsmith()
        .args([
            "diff",
            before.to_str().expect("utf-8 before path"),
            before.to_str().expect("utf-8 before path"),
        ])
        .output()
        .expect("runs animsmith");
    assert_eq!(clean.status.code(), Some(0), "stderr:\n{}", stderr(&clean));
    assert!(
        stdout(&clean).contains("no significant movement"),
        "clean Text output states no movement:\n{}",
        stdout(&clean)
    );
}

#[test]
fn diff_rejects_json_without_schema_version() {
    let dir = unique_temp_dir("diff-bare-map");
    let bare = dir.path().join("bare.json");
    // A bare measurement map (a pre-publish development shape) has no
    // schema_version and must be rejected with regenerate guidance.
    std::fs::write(&bare, r#"{"walk": {"duration_s": 1.0}}"#).expect("writes bare map");

    let output = animsmith()
        .args([
            "diff",
            bare.to_str().expect("utf-8 path"),
            fixture("rig.gltf").to_str().expect("utf-8 fixture path"),
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    assert!(
        stderr(&output).contains("not an animsmith report envelope"),
        "stderr:\n{}",
        stderr(&output)
    );
    assert!(
        stderr(&output).contains("regenerate it with"),
        "stderr:\n{}",
        stderr(&output)
    );
}

#[test]
fn diff_rejects_unsupported_schema_versions() {
    let dir = unique_temp_dir("diff-future-schema");
    let future = dir.path().join("future.json");
    std::fs::write(
        &future,
        r#"{"schema_version": 99, "files": [{"measurements": {}}]}"#,
    )
    .expect("writes future report");

    let output = animsmith()
        .args([
            "diff",
            future.to_str().expect("utf-8 path"),
            fixture("rig.gltf").to_str().expect("utf-8 fixture path"),
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    assert!(
        stderr(&output).contains("schema_version 99"),
        "stderr:\n{}",
        stderr(&output)
    );
}

#[test]
fn diff_rejects_envelope_without_files() {
    let dir = unique_temp_dir("diff-no-files");
    let report = dir.path().join("no-files.json");
    std::fs::write(&report, r#"{"schema_version": 1}"#).expect("writes report");

    let output = animsmith()
        .args([
            "diff",
            report.to_str().expect("utf-8 path"),
            fixture("rig.gltf").to_str().expect("utf-8 fixture path"),
        ])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    assert!(
        stderr(&output).contains("no `files` array"),
        "stderr:\n{}",
        stderr(&output)
    );
}

#[test]
fn lint_counts_severities_in_summary_and_text() {
    let dir = unique_temp_dir("lint-severity-counts");
    let input = dir.path().join("dirty.glb");
    write_flipped_glb(&input);

    // JSON: the flipped fixture produces exactly one quat-flip warning;
    // the summary must bucket it as a warning, not a note or error.
    let output = animsmith()
        .args([
            "lint",
            input.to_str().expect("utf-8 input path"),
            "--format",
            "json",
            "--select",
            "quat-flip",
        ])
        .output()
        .expect("runs animsmith");
    assert!(output.status.success(), "stderr:\n{}", stderr(&output));
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
    assert_eq!(json["summary"]["findings"]["warning"], 1, "{json:#}");
    assert_eq!(json["summary"]["findings"]["error"], 0, "{json:#}");
    assert_eq!(json["summary"]["findings"]["note"], 0, "{json:#}");
    assert_eq!(json["files"][0]["findings"][0]["severity"], "warning");

    // Text mode counts through the same severity match.
    let output = animsmith()
        .args([
            "lint",
            input.to_str().expect("utf-8 input path"),
            "--select",
            "quat-flip",
        ])
        .output()
        .expect("runs animsmith");
    assert!(
        stdout(&output).contains("1 warning(s)"),
        "stdout:\n{}",
        stdout(&output)
    );
}

#[test]
fn fix_reports_unreadable_input_as_operator_error() {
    let output = animsmith()
        .args(["fix", "missing.glb", "--dry-run"])
        .output()
        .expect("runs animsmith");

    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    assert!(
        stderr(&output).contains("failed to read"),
        "stderr:\n{}",
        stderr(&output)
    );
}

/// 3 keyframe times but 2 output values — structurally malformed.
const COUNT_MISMATCH_GLTF: &str = r#"{
  "asset": { "version": "2.0" },
  "buffers": [{ "uri": "data:application/octet-stream;base64,AAAAAAAAAD8AAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8=", "byteLength": 44 }],
  "bufferViews": [
    { "buffer": 0, "byteOffset": 0, "byteLength": 12 },
    { "buffer": 0, "byteOffset": 12, "byteLength": 32 }
  ],
  "accessors": [
    { "bufferView": 0, "componentType": 5126, "count": 3, "type": "SCALAR", "min": [0], "max": [1] },
    { "bufferView": 1, "componentType": 5126, "count": 2, "type": "VEC4" }
  ],
  "nodes": [{ "name": "root" }],
  "animations": [{
    "name": "bad",
    "samplers": [{ "input": 0, "output": 1, "interpolation": "LINEAR" }],
    "channels": [{ "sampler": 0, "target": { "node": 0, "path": "rotation" } }]
  }],
  "scenes": [{ "nodes": [0] }],
  "scene": 0
}"#;

/// First keyframe time is NaN; values are valid identity quats.
const NAN_TIME_GLTF: &str = r#"{
  "asset": { "version": "2.0" },
  "buffers": [{ "uri": "data:application/octet-stream;base64,AADAfwAAAD8AAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/", "byteLength": 60 }],
  "bufferViews": [
    { "buffer": 0, "byteOffset": 0, "byteLength": 12 },
    { "buffer": 0, "byteOffset": 12, "byteLength": 48 }
  ],
  "accessors": [
    { "bufferView": 0, "componentType": 5126, "count": 3, "type": "SCALAR", "min": [0], "max": [1] },
    { "bufferView": 1, "componentType": 5126, "count": 3, "type": "VEC4" }
  ],
  "nodes": [{ "name": "root" }],
  "animations": [{
    "name": "poisoned",
    "samplers": [{ "input": 0, "output": 1, "interpolation": "LINEAR" }],
    "channels": [{ "sampler": 0, "target": { "node": 0, "path": "rotation" } }]
  }],
  "scenes": [{ "nodes": [0] }],
  "scene": 0
}"#;

#[test]
fn malformed_track_counts_are_operator_errors_everywhere() {
    let dir = unique_temp_dir("count-mismatch-cli");
    let input = dir.path().join("bad.gltf");
    std::fs::write(&input, COUNT_MISMATCH_GLTF).expect("writes fixture");
    let out = dir.path().join("out.glb");

    let commands: [&[&str]; 3] = [
        &["measure", input.to_str().expect("utf-8 path")],
        &["lint", input.to_str().expect("utf-8 path")],
        &[
            "transform",
            input.to_str().expect("utf-8 path"),
            "-o",
            out.to_str().expect("utf-8 path"),
        ],
    ];
    for args in commands {
        let output = animsmith().args(args).output().expect("runs animsmith");
        assert_eq!(
            output.status.code(),
            Some(2),
            "{args:?}: stdout:\n{}\nstderr:\n{}",
            stdout(&output),
            stderr(&output)
        );
        assert!(
            stderr(&output).contains("malformed animation data"),
            "{args:?}: stderr:\n{}",
            stderr(&output)
        );
    }
}

#[test]
fn nan_key_times_lint_as_errors_and_never_crash() {
    let dir = unique_temp_dir("nan-time-cli");
    let input = dir.path().join("nan.gltf");
    std::fs::write(&input, NAN_TIME_GLTF).expect("writes fixture");

    // measure survives (exit 0): NaN is a semantic defect for lint to
    // judge, not a crash.
    let output = animsmith()
        .args(["measure", input.to_str().expect("utf-8 path")])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );

    // lint reports the nan error finding and exits 1.
    let output = animsmith()
        .args(["lint", input.to_str().expect("utf-8 path")])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    assert!(
        stdout(&output).contains("error[nan]") && stdout(&output).contains("non-finite key time"),
        "stdout:\n{}",
        stdout(&output)
    );
}

// --- #30: exit-code, config-path, and inspect contract ---

fn write_config(dir: &std::path::Path, name: &str, toml: &str) -> PathBuf {
    let path = dir.join(name);
    std::fs::write(&path, toml).expect("writes config");
    path
}

fn example_config() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/character.animsmith.toml")
}

#[test]
fn lint_clean_file_exits_zero() {
    let output = animsmith()
        .args(["lint", fixture("rig.gltf").to_str().expect("utf-8 path")])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr:\n{}",
        stderr(&output)
    );
    assert!(
        stdout(&output).contains("clean"),
        "stdout:\n{}",
        stdout(&output)
    );
}

#[test]
fn lint_markdown_renders_findings_for_failing_asset() {
    let dir = unique_temp_dir("markdown-findings");
    let input = dir.path().join("dirty.glb");
    write_distinct_repair_glb(&input); // quat-norm error + quat-flip warning
    let path = input.to_str().expect("utf-8 path");

    let output = animsmith()
        .args(["lint", path, "--format", "markdown"])
        .output()
        .expect("runs animsmith");
    // A failing asset exits 1 in markdown mode just like text/json — the
    // renderer must not swallow the content-failure status.
    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
    let out = stdout(&output);

    // Presentation surface: a heading, the per-clip table header, the
    // collapsible section, and both findings' check ids and severities.
    assert!(out.contains("## animsmith lint"), "stdout:\n{out}");
    assert!(
        out.contains("| Severity | Check | Location | Measured | Expected | Message |"),
        "stdout:\n{out}"
    );
    assert!(out.contains("<details"), "stdout:\n{out}");
    assert!(out.contains("#### clip `sway`"), "stdout:\n{out}");
    assert!(out.contains("`quat-norm`"), "stdout:\n{out}");
    assert!(out.contains("`quat-flip`"), "stdout:\n{out}");
    // End-to-end smoke check that the summary footer reaches stdout;
    // per-branch tallies/grouping/escaping are pinned by the render unit
    // tests in the binary crate. Anchor on the footer's `**N file**`
    // prefix so this matches the aggregate line, not the per-file header.
    assert!(
        out.contains("**1 file** — ❌ 1 error(s) · ⚠️ 1 warning(s)"),
        "stdout:\n{out}"
    );
}

#[test]
fn lint_markdown_summarizes_clean_asset() {
    let dir = unique_temp_dir("markdown-clean");
    let input = dir.path().join("clean.glb");
    write_clean_glb(&input);
    let path = input.to_str().expect("utf-8 path");

    let output = animsmith()
        .args(["lint", path, "--format", "markdown"])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr:\n{}",
        stderr(&output)
    );
    let out = stdout(&output);
    assert!(out.contains("✅ Clean — no findings."), "stdout:\n{out}");
    // A clean asset produces no findings table to collapse.
    assert!(!out.contains("<details"), "stdout:\n{out}");
}

#[test]
fn lint_warnings_pass_but_deny_warnings_fails() {
    let dir = unique_temp_dir("deny-warnings");
    let input = dir.path().join("flipped.glb");
    write_flipped_glb(&input); // quat-flip → warning
    let path = input.to_str().expect("utf-8 path");

    // Warnings alone are exit 0.
    let output = animsmith().args(["lint", path]).output().expect("runs");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr:\n{}",
        stderr(&output)
    );
    assert!(
        stdout(&output).contains("quat-flip"),
        "stdout:\n{}",
        stdout(&output)
    );

    // --deny-warnings promotes the exit to 1.
    let output = animsmith()
        .args(["lint", path, "--deny-warnings"])
        .output()
        .expect("runs");
    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout:\n{}\nstderr:\n{}",
        stdout(&output),
        stderr(&output)
    );
}

#[test]
fn lint_allow_suppresses_a_check() {
    let dir = unique_temp_dir("allow");
    let input = dir.path().join("flipped.glb");
    write_flipped_glb(&input);
    let path = input.to_str().expect("utf-8 path");

    // Positive control: quat-flip fires on this fixture without --allow.
    let baseline = animsmith().args(["lint", path]).output().expect("runs");
    assert!(
        stdout(&baseline).contains("quat-flip"),
        "fixture no longer produces quat-flip; suppression test would be vacuous:\n{}",
        stdout(&baseline)
    );

    // With --allow, the same finding is gone.
    let output = animsmith()
        .args(["lint", path, "--allow", "quat-flip"])
        .output()
        .expect("runs");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr:\n{}",
        stderr(&output)
    );
    assert!(
        !stdout(&output).contains("quat-flip"),
        "allowed check still reported:\n{}",
        stdout(&output)
    );
}

#[test]
fn lint_unknown_select_is_operator_error() {
    let output = animsmith()
        .args([
            "lint",
            fixture("rig.gltf").to_str().expect("utf-8 path"),
            "--select",
            "no-such-check",
        ])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    let err = stderr(&output);
    assert!(
        err.contains("unknown check 'no-such-check'"),
        "stderr:\n{err}"
    );
    // The error also lists the known check ids so the user can correct
    // the typo without reading the docs.
    assert!(
        err.contains("known:") && err.contains("quat-flip"),
        "error should list known check ids:\n{err}"
    );
}

#[test]
fn lint_missing_file_is_operator_error() {
    let output = animsmith()
        .args(["lint", "/no/such/file.glb"])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    // Exit 2 is the catch-all; pin that it failed at load (the right
    // cause) rather than arg parsing or config. The loader reads the file
    // itself now, so a missing file is an I/O error, not a parse error.
    // The OS "file not found" text differs across platforms, so anchor on
    // the stable prefix.
    assert!(
        stderr(&output).contains("failed to read"),
        "stderr:\n{}",
        stderr(&output)
    );
}

#[test]
fn lint_bad_config_is_operator_error() {
    let dir = unique_temp_dir("bad-config");
    let config = write_config(dir.path(), "bad.toml", "not valid = = toml [[[\n");
    let output = animsmith()
        .args([
            "--config",
            config.to_str().expect("utf-8 path"),
            "lint",
            fixture("rig.gltf").to_str().expect("utf-8 path"),
        ])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(2),
        "stdout:\n{}",
        stdout(&output)
    );
    assert!(
        stderr(&output).contains("bad config"),
        "stderr:\n{}",
        stderr(&output)
    );
}

/// The `--config` TOML path is otherwise only reached through the CLI:
/// a config that disables `quat-flip` must suppress it on a flipped
/// clip, proving `toml::from_str` → `Config` → severity handling works
/// end to end.
#[test]
fn config_toml_path_drives_check_behaviour() {
    let dir = unique_temp_dir("config-toml");
    let input = dir.path().join("flipped.glb");
    write_flipped_glb(&input);
    let path = input.to_str().expect("utf-8 path");
    let config = write_config(
        dir.path(),
        "animsmith.toml",
        "[checks.quat-flip]\nseverity = \"off\"\n",
    );

    // Positive control: without the config, quat-flip fires.
    let baseline = animsmith().args(["lint", path]).output().expect("runs");
    assert!(
        stdout(&baseline).contains("quat-flip"),
        "fixture no longer produces quat-flip; the config test would be vacuous:\n{}",
        stdout(&baseline)
    );

    // The TOML config turns it off end to end.
    let output = animsmith()
        .args([
            "--config",
            config.to_str().expect("utf-8 path"),
            "lint",
            path,
        ])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr:\n{}",
        stderr(&output)
    );
    assert!(
        !stdout(&output).contains("quat-flip"),
        "off check still reported via TOML config:\n{}",
        stdout(&output)
    );
}

/// The shipped example config must parse verbatim — otherwise it drifts
/// from the schema and fails users at runtime while CI stays green.
#[test]
fn example_config_parses_verbatim() {
    let config = example_config();
    assert!(config.exists(), "example config missing at {config:?}");
    let output = animsmith()
        .args([
            "--config",
            config.to_str().expect("utf-8 path"),
            "inspect",
            fixture("rig.gltf").to_str().expect("utf-8 path"),
        ])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(0),
        "example config did not parse:\nstderr:\n{}",
        stderr(&output)
    );
}

#[test]
fn inspect_reports_clip_and_profile() {
    let output = animsmith()
        .args(["inspect", fixture("rig.gltf").to_str().expect("utf-8 path")])
        .output()
        .expect("runs animsmith");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr:\n{}",
        stderr(&output)
    );
    let out = stdout(&output);
    // Distinctive clip detail: the fixture's one clip, its duration and
    // track/key counts — pins that inspect actually read the file, not
    // just that it printed a static template.
    assert!(
        out.contains("walk: 1.000s, 2 tracks, 3 keys max"),
        "clip summary missing/changed:\n{out}"
    );
    assert!(out.contains("rig profile:"), "no profile line:\n{out}");
    assert!(
        out.contains("skeleton: 3 bones"),
        "no skeleton line:\n{out}"
    );
}