nord-cli 0.6.0

Your Nord from the terminal: inspect, edit and move the sounds in Nord files and on a connected instrument
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
//! `nord` — a thin CLI over [`nord_format`] and `nord_usb` to interact with
//! your Clavia / Nord projects and files.
//!
//! > This is an unofficial, community project: **not affiliated with, endorsed
//! > by, or supported by Clavia DMI AB**. "Nord" and the instrument names are
//! > Clavia's trademarks, used here only to identify which files this crate
//! > reads.
//!
//! The nouns are the protocol's object classes: `nord program`, `nord sample`,
//! `nord piano`, `nord setlist` and `nord live` are [`slot_action`] with the class
//! fixed, `nord settings` carries the subset its singleton can answer (`get`,
//! `info`, `edit`), and the hidden `nord raw --class N` is [`slot_action`] with the
//! class given as a number.
//! `inspect`/`verify`/`edit` dispatch on the format rather than on a class, so they
//! sit at the top level — `edit` is how the formats with no noun of their own (the
//! Stage bodies, the Sample Editor project) are edited.
//!
//! ⚠️ `raw` is hidden but supported: it is the only way to reach a class with no noun of
//! its own.

mod device;
mod edit;
mod editors;
mod file;
mod file_edit;
mod piano;
mod sample;
mod slot;
mod summary;
mod ui;
mod wav;

use clap::{Args, Parser, Subcommand};
use nord_usb::ObjectClass;
use std::path::PathBuf;
use std::process::ExitCode;

use ui::{ColorChoice, Ui};

#[derive(Parser)]
#[command(name = "nord", about = "Inspect Clavia / Nord keyboard files", version)]
struct Cli {
    /// When to color output. `auto` means "stdout is a terminal"; `NO_COLOR` in the
    /// environment forces it off.
    #[arg(long, global = true, value_name = "WHEN", value_enum, default_value_t)]
    color: ColorChoice,

    /// Mirror every frame exchanged with the instrument into a replay script at PATH.
    ///
    /// The script is what `--replay` and the protocol tests read back. An operation that
    /// transfers a body writes that body into it in full.
    ///
    /// Bulk traffic only: `device info` reads endpoint 0, which never reaches the script.
    #[arg(long, global = true, value_name = "PATH")]
    record: Option<PathBuf>,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Parse Nord file(s) and print a summary of the decoded contents.
    Inspect {
        /// Files to read (.ne5p program, .ne5l live slot, .ne5t song, .ne5s
        /// settings, .npno piano, .nsmp sample, or a ZIP backup bundle).
        #[arg(required = true)]
        files: Vec<PathBuf>,

        /// Dump the full `Debug` representation instead of the summary.
        #[arg(long)]
        raw: bool,
    },

    /// Re-encode file(s) and check the result is byte-identical to the input.
    ///
    /// Checks `nord-format`'s central invariant: decoded values are read-only views over
    /// a verbatim body, so a parse followed by a re-emit cannot drift.
    Verify {
        /// Files to round-trip. Bundles are archives, not re-emittable entities.
        #[arg(required = true)]
        files: Vec<PathBuf>,
    },

    /// Change fields inside any editable file, whatever format it holds.
    ///
    /// The file twin of the noun edits: where those speak to the Electro 5's
    /// object classes, this dispatches on the file itself, so the formats with
    /// no noun — Stage programs and presets, Sample Editor projects — are
    /// editable too. `--fields` lists what the file offers.
    Edit(file_edit::FileEditArgs),

    /// The attached instrument itself: what is on the bus, and what it holds.
    Device {
        #[command(subcommand)]
        action: DeviceAction,
    },

    /// Programs on the instrument (object class 4). Slots are `BANK:SLOT`, as the
    /// instrument displays them; the read-only verbs and `edit` take a file instead.
    Program {
        #[command(subcommand)]
        action: ProgramAction,
    },

    /// Set lists on the instrument (object class 5). Same verbs as `nord program`.
    Setlist {
        #[command(subcommand)]
        action: SetlistAction,
    },

    /// The live buffer — the panel as it stands (object class 6), in slots 1:1 to 1:3.
    Live {
        #[command(subcommand)]
        action: LiveAction,
    },

    /// The global settings singleton (object class 7): the System, MIDI and Sound
    /// menus, plus the panel state the instrument restores at power-up.
    Settings {
        #[command(subcommand)]
        action: SettingsAction,
    },

    /// Sample instruments — the library on the instrument (object class 3), or
    /// `.nsmp` files.
    Sample {
        #[command(subcommand)]
        action: SampleAction,
    },

    /// Piano libraries — the library on the instrument (object class 1), or
    /// `.npno` files.
    Piano {
        #[command(subcommand)]
        action: PianoAction,
    },

    /// The class-generic primitives, addressed by object-class number.
    ///
    /// Every typed noun above is this with the class fixed. Use it for a class with no
    /// noun of its own, or to address a class by number.
    #[command(hide = true)]
    Raw {
        #[arg(long, global = true, value_name = "N", default_value_t = 4, help = class_help())]
        class: u32,

        #[command(subcommand)]
        action: SlotAction,
    },
}

#[derive(Subcommand)]
enum DeviceAction {
    /// Sweep the vendor control requests on endpoint 0 and print what answers. For RE.
    ///
    /// Endpoint 0 is outside the bulk protocol: these are reads that cannot open,
    /// desync, or wedge a session, and an unrecognised request stalls the endpoint
    /// rather than doing anything. Reported externally to carry the model, firmware
    /// version, build and maximum transfer size.
    Controls {
        /// Lowest bRequest to try.
        #[arg(long, default_value_t = 0)]
        from: u8,

        /// Highest bRequest to try, inclusive.
        #[arg(long, default_value_t = 15)]
        to: u8,

        /// Bytes to ask each request for. A control transfer's wLength is 16 bits.
        #[arg(long, default_value_t = 64)]
        len: u16,

        /// Address the interface rather than the device.
        #[arg(long)]
        interface: bool,

        /// wValue sent with each request.
        #[arg(long, default_value_t = 0)]
        value: u16,

        /// wIndex sent with each request. For --interface this is the interface number.
        #[arg(long, default_value_t = 0)]
        index: u16,
    },

    /// Report what is stored on the instrument, per object class.
    ///
    /// Read-only: this sends one query per class and reads counters back. Nothing
    /// on the instrument is modified.
    Status {
        /// Replay a recorded exchange instead of opening a device. Useful for
        /// demos and for exercising the whole path without hardware.
        #[arg(long, value_name = "SCRIPT")]
        replay: Option<PathBuf>,

        /// Emit JSON instead of a table.
        #[arg(long)]
        json: bool,
    },

    /// Identify the attached instrument, from its USB descriptors. Read-only, and opens
    /// no transaction — the first thing to run when nothing else answers.
    Info,

    /// Clear a session an interrupted run left open on the instrument.
    ///
    /// Two faults look like a broken instrument and each is one frame to cure: an
    /// abandoned UI session makes every slot read as empty — a wrong answer that looks
    /// right — and an abandoned class session makes operations fail with status 0x12.
    /// Safe to run on a healthy instrument.
    Recover,

    /// Report the instrument's storage layout: partitions, banks and slot capacity.
    ///
    /// Read from the device rather than assumed, so it is correct for models this tool
    /// has never seen. Partition indices are the object class numbers.
    Geometry,

    /// Deliberately wedge the instrument by abandoning a session. Test tool.
    ///
    /// Reproduces the abandoned session on purpose, so recovery can be tested against a
    /// known wedge. Nothing stored is harmed, but every slot then reads as empty —
    /// successfully, which is worse than an error — until `nord device recover` clears it.
    #[cfg(feature = "wedge")]
    #[command(hide = true)]
    Wedge {
        /// Object class to open the doomed session on.
        #[arg(long, value_name = "N", default_value_t = 4)]
        class: u32,

        /// Confirm. Without this nothing is sent.
        #[arg(long)]
        yes: bool,
    },
}

/// `nord program`: every class-generic verb, plus the one that only programs have.
#[derive(Subcommand)]
enum ProgramAction {
    #[command(flatten)]
    Slot(SlotAction),

    /// Change fields inside a program, in a file or in a slot.
    ///
    /// Field paths are `nord-format`'s own — `center_panel.transpose`,
    /// `effects_panel.fx1_rate`. `--fields` lists them.
    ///
    /// With no target the program is a fresh default one, so `--fields` needs nothing to
    /// read and `-o` writes a blank `.ne5p` to start from.
    Edit(EditArgs),
}

/// `nord setlist`: every class-generic verb, plus the one that changes the four
/// program slots a set list points at.
#[derive(Subcommand)]
enum SetlistAction {
    #[command(flatten)]
    Slot(SlotAction),

    /// Change the programs a set list plays, in a file or in a slot.
    ///
    /// The four slots are `slot1` to `slot4`, each taking a program address as
    /// the instrument shows it: `--set slot1=2:5`. `--fields` lists them. With
    /// no target the set list is a fresh default one, so `-o` writes a blank
    /// `.ne5t` to start from.
    Edit(EditArgs),
}

/// `nord sample`: every class-generic verb, plus the one that edits files.
#[derive(Subcommand)]
enum SampleAction {
    #[command(flatten)]
    Slot(SlotAction),

    /// Change fields inside a sample instrument, in a file or in a slot.
    ///
    /// A sample is mostly encoded audio; what is settable is what the format can
    /// patch in place — the name, each zone's root key and top note, and its low
    /// note on the generations that store one. `--fields` lists them.
    Edit(sample::EditArgs),

    /// Decode an instrument's audio to WAV, one file per zone, from a file or a slot.
    ///
    /// The audio comes out on its own lattice — about 35 kHz — because the rate the
    /// instrument plays it back at is a property of its interpolator, which is not
    /// decoded. Anything the stream grammar cannot walk is reported as unsupported
    /// with a reason, and the run ends in a coverage count. A slot is only read, so
    /// this never needs `--yes`; its WAVs are named after the instrument.
    Decode(sample::DecodeArgs),

    /// Build a one-zone sample instrument from a 44.1 kHz mono or stereo 16-bit WAV.
    ///
    /// The v2 result is what Nord Sample Editor writes for the same input, byte for
    /// byte, apart from a float residue in the resampling kernel that leaves the odd
    /// audio field one count out and changes nothing the instrument plays; mono,
    /// stereo and looped v2 encodes play on an Electro 5. The wide generations
    /// reproduce the editor's renders but have never been played, so they need
    /// `--unverified`.
    Encode(sample::EncodeArgs),

    /// Build a sample instrument from a Nord Sample Editor project.
    ///
    /// The project supplies the zones, their root keys, top notes and trim points,
    /// and the WAVs they play — paths inside it resolve from the project's own
    /// directory. Unsupported layer, detune, velocity and enabled EQ settings are
    /// refused by name. Settings with no instrument representation are reported when
    /// ignored. The same fidelity and `--unverified` notes as `encode` apply.
    Build(sample::BuildArgs),

    /// Round-trip a sample instrument, in a file or a slot, and with `--deep` also
    /// walk its audio stream. Reading a slot is all this does to the instrument.
    Verify(sample::VerifyArgs),

    /// Sample Editor projects (`.nsmpproj`) — the save file the editor generates an
    /// instrument from. `nord edit` changes one; this builds one.
    Project {
        #[command(subcommand)]
        action: SampleProjectAction,
    },
}

/// `nord piano`: every class-generic verb, plus the ones that read and reshape a
/// library file.
///
/// A library is tens of megabytes, so the file verbs take a file and nothing else:
/// move one to or from the instrument with `get` and `put` first.
#[derive(Subcommand)]
enum PianoAction {
    #[command(flatten)]
    Slot(SlotAction),

    /// Report a library's directory: its roots, the layers each holds per bank, the
    /// keys it covers, its channels and its size. Read-only.
    Inspect(piano::InspectArgs),

    /// Decode one stroke to a WAV, at the rate the instrument plays it and with no
    /// gain applied.
    ///
    /// A stroke is one recording: a root note, a bank and a velocity layer. Name it
    /// by index with `--stroke`, or by the key it plays with `--key`, narrowing
    /// with `--bank` and `--layer` when a key selects more than one.
    Decode(piano::DecodeArgs),

    /// Change what a library says rather than what it holds: its name, a key's fine
    /// tune, and which root a key plays.
    ///
    /// Nothing here touches audio. A key can only be routed to a root the directory
    /// actually records.
    Edit(piano::EditArgs),

    /// Write a smaller library: without a bank, without the quieter velocity
    /// layers, or covering fewer keys.
    ///
    /// The strokes that survive move byte for byte, so a trim is a re-lay rather
    /// than a re-encode. Keys whose root loses every stroke are left playing
    /// nothing, and the count is reported. Dropping a bank or a layer is
    /// hardware-verified — the trimmed library loads and plays; narrowing the key
    /// range is not.
    Trim(piano::TrimArgs),

    /// Cut a library in two at a key, writing both halves.
    Split(piano::SplitArgs),

    /// Build a piano library from a directory of WAVs.
    ///
    /// The WAVs name the root, bank and layer they are. Any rate resamples onto the
    /// lattice the instrument plays at.
    ///
    /// Everything the audio does not decide — the length marks, the decay
    /// coefficients, the per-note tables, the playback parameters and the stream
    /// version — comes from `--template`, out of its own stroke of the same bank and
    /// nearest root. Without a template the library states neutral playback instead:
    /// no decay applied over the recordings, each stroke trimmed by its own layer
    /// value, and the damper limit `--kind` implies.
    ///
    /// Every key up to one semitone above the highest root sounds, playing the
    /// nearest root at or above it; keys past that are left uncovered. A key sounds
    /// the largest layer value its root holds that is at most (127 − velocity)·31/127,
    /// and a root's `l00`, `l01`, … spread over 0..27 so that each layer answers to
    /// its own part of the velocity range.
    ///
    /// Hardware-verified: a library built this way loads and plays, mono and stereo,
    /// on every key it covers, and one written without a template sounds like the same
    /// audio built against one.
    Build(piano::BuildArgs),

    /// Code a library's audio again from the frames it decodes to, and report how each
    /// stroke's blocks came back.
    ///
    /// A library this coder wrote comes back byte for byte. One it did not comes back
    /// block for block apart from the attenuation each block declares, which is a
    /// statistic the file's own encoder measured and the decode never reads — coded
    /// again, such a library plays indistinguishably from the original. Each stroke
    /// keeps its own root, bank and layer value.
    Rebuild(piano::RebuildArgs),

    /// Rebuild each library from its parsed model and check the bytes come back
    /// identical; with `--deep` also decode every stroke it holds.
    ///
    /// The rebuild recomputes the per-root counts, every audio offset, the
    /// alignment gap and the container checksum, so an identical result says the
    /// model accounts for the whole file. `--deep` adds the codec's own checks:
    /// each block repeats the previous block's last frames bit-exactly, and the
    /// frames a stroke owns come to the count its record states.
    Verify(piano::VerifyArgs),
}

/// `nord sample project`: the editor's own save file, which no object class holds.
#[derive(Subcommand)]
enum SampleProjectAction {
    /// Build a project from WAV files, one zone per `--zone WAV=NOTE`.
    ///
    /// Key ranges, zone ids and loop points are derived the way the editor derives
    /// them for a fresh import. A WAV is stored by the path given, made relative to
    /// the project's own directory when it lies under it, and at whatever rate it
    /// carries — the frame counts a project holds are stated at 44.1 kHz regardless.
    New(sample::ProjectNewArgs),
}

/// `nord live`: the verbs that mean anything for the live buffer.
///
/// The live buffer is the panel as it stands, not a library — there is nothing to name,
/// nothing to delete, and `select` is what the *other* classes do to it. What is left is
/// the read-only subset, spelled exactly as [`SlotAction`] spells it, plus `edit`.
#[derive(Subcommand)]
enum LiveAction {
    #[command(flatten)]
    Slot(LiveSlotAction),

    /// Change fields inside a live slot, in a `.ne5l` file or in a slot.
    ///
    /// The live buffer is the program body under another tag, so the fields are exactly
    /// `nord program edit`'s. Slots are 1:1 to 1:3, and the instrument overwrites one in
    /// place, so nothing is deleted to make room.
    Edit(EditArgs),
}

/// `nord settings`: read or edit the singleton at 1:1.
#[derive(Subcommand)]
enum SettingsAction {
    #[command(flatten)]
    Slot(SettingsSlotAction),

    /// Change fields inside the global settings, in a `.ne5s` file or on the instrument.
    ///
    /// Fields are the menu settings plus the `startup_*` state the instrument restores
    /// at power-up; `--fields` lists them. The singleton is addressed as slot `1:1`, and
    /// the instrument overwrites it in place.
    ///
    /// ⚠️ A settings write reloads the selected program, losing panel state that has
    /// not been stored.
    Edit(EditArgs),
}

/// Read-only actions for the settings singleton.
#[derive(Subcommand)]
enum SettingsSlotAction {
    /// Read the settings off the instrument, or a `.ne5s` file. Read-only.
    ///
    /// Prints a summary by default; with `--out` writes the file instead.
    Get {
        /// The singleton, addressed as 1:1 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,

        /// Write the object to this file instead of printing a summary. With `--sweep`,
        /// the directory every capture lands in.
        #[arg(short, long, value_name = "FILE|DIR")]
        out: Option<PathBuf>,

        /// Save the wire body verbatim instead of wrapping it in a CBIN header.
        /// Needs `--out`.
        #[arg(long)]
        body: bool,

        /// Read the singleton over and over, once per prompt, into the `--out`
        /// directory.
        ///
        /// Change one menu setting on the instrument, say what you changed, and that
        /// capture is filed under your answer; repeat until a blank line.
        #[arg(long, requires = "out")]
        sweep: bool,
    },

    /// Report everything the instrument knows about the settings singleton, or a
    /// `.ne5s` file's header. Read-only.
    Info {
        /// The singleton, addressed as 1:1 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },
}

/// The [`SlotAction`] verbs the live buffer keeps, spelled identically.
#[derive(Subcommand)]
enum LiveSlotAction {
    /// Read a live slot off the instrument, or a `.ne5l` file. Read-only.
    ///
    /// Prints a summary by default; with `--out` writes the file instead.
    Get {
        /// Slot to read: 1:1, 1:2 or 1:3 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,

        /// Write the object to this file instead of printing a summary. With `--sweep`,
        /// the directory every capture lands in.
        #[arg(short, long, value_name = "FILE|DIR")]
        out: Option<PathBuf>,

        /// Save the wire body verbatim instead of wrapping it in a CBIN header.
        /// Needs `--out`.
        #[arg(long)]
        body: bool,

        /// Read the slot over and over, once per prompt, into the `--out` directory.
        ///
        /// The live slot is the panel itself, so this captures a change-one-knob corpus
        /// without saving a program between steps.
        #[arg(long, requires = "out")]
        sweep: bool,
    },

    /// Report everything the instrument knows about a live slot, or a `.ne5l` file's
    /// header. Read-only.
    Info {
        /// Slot to describe: 1:1, 1:2 or 1:3 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },

    /// List the piano/sample library objects the live panel depends on. Read-only.
    Deps {
        /// Slot to inspect: 1:1, 1:2 or 1:3 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },
}

/// The verb vocabulary, identical for every object class.
#[derive(Subcommand)]
enum SlotAction {
    /// Read an object off the instrument, or from a file. Read-only.
    ///
    /// Prints a summary by default; with `--out` writes the file instead.
    Get {
        /// Slot to read, e.g. 7:4, or a file to read with no instrument attached.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,

        /// Write the object to this file instead of printing a summary. With `--sweep`,
        /// the directory every capture lands in.
        #[arg(short, long, value_name = "FILE|DIR")]
        out: Option<PathBuf>,

        /// Save the wire body verbatim instead of wrapping it in a CBIN header. For
        /// classes whose header layout is not yet known, where wrapping it would
        /// fabricate a wrong file. On a file, strips the header instead. Needs `--out`.
        #[arg(long)]
        body: bool,

        /// Read the slot over and over, once per prompt, into the `--out` directory.
        ///
        /// Change one thing on the instrument, say what you changed, and that capture is
        /// filed under your answer; repeat until a blank line. For building the
        /// one-field-at-a-time corpus used to locate fields.
        #[arg(long, requires = "out")]
        sweep: bool,
    },

    /// Write a file into a slot, OVERWRITING it. Requires --yes.
    Put {
        /// The file to send.
        file: PathBuf,

        /// Destination slot, e.g. 7:4.
        #[arg(value_name = "BANK:SLOT")]
        at: String,

        /// Confirm the overwrite. Without this the command stops after reporting what
        /// currently occupies the slot.
        #[arg(long)]
        yes: bool,
    },

    /// Move an object between slots, SWAPPING with any occupant. Requires --yes.
    Move {
        /// Source slot, e.g. 8:13.
        #[arg(value_name = "FROM")]
        from: String,

        /// Destination slot, e.g. 7:16.
        #[arg(value_name = "TO")]
        to: String,

        #[arg(long)]
        yes: bool,
    },

    /// Rename the object in a slot. Requires --yes.
    Rename {
        /// Slot to rename, e.g. 6:13.
        #[arg(value_name = "BANK:SLOT")]
        at: String,

        /// The new name.
        name: String,

        #[arg(long)]
        yes: bool,
    },

    /// Duplicate an object into another slot (device-internal deep copy). Requires --yes.
    Duplicate {
        /// Source slot, e.g. 7:2.
        #[arg(value_name = "FROM")]
        from: String,

        /// Destination slot, e.g. 7:3.
        #[arg(value_name = "TO")]
        to: String,

        #[arg(long)]
        yes: bool,
    },

    /// Delete one or more slots. Requires --yes.
    Delete {
        /// Slots to delete, e.g. 7:50 (repeatable).
        #[arg(value_name = "BANK:SLOT", required = true)]
        slots: Vec<String>,

        #[arg(long)]
        yes: bool,
    },

    /// Load an object live on the instrument (double-click in NSM). Non-destructive.
    Select {
        /// Slot to load, e.g. 2:12.
        #[arg(value_name = "BANK:SLOT")]
        at: String,
    },

    /// Report everything the instrument knows about one slot, or a file's header.
    /// Read-only.
    ///
    /// Shows the fields the CBIN header carries but the wire never transmits — format
    /// tag, version, CRC-32 — plus the slot name, which no file stores at all.
    Info {
        /// Slot to describe, e.g. 7:4, or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },

    /// List the piano/sample library objects an entity depends on. Read-only.
    ///
    /// A file yields the stored ids alone; the slot form asks the instrument, which
    /// attaches the names.
    Deps {
        /// Slot to inspect, e.g. 7:3, or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },

    /// Report which object the panel currently has loaded in this class. Read-only.
    ///
    /// The read half of `select`: it answers what the player is looking at, rather than
    /// telling the instrument what to load.
    Focus,

    /// List everything the instrument holds in this class. Read-only.
    ///
    /// Walks the device's own slot cursor, so it reports what is actually stored rather
    /// than probing every address: occupied slots are sparse, and their indices run past
    /// the class's item count.
    List,

    /// Send a raw command code and print whatever the device answers. For RE only.
    ///
    /// Nothing about the reply is interpreted: the status word and payload are printed
    /// as-is, because on an unknown command an error status is the finding. A command
    /// the device ignores is reported as a timeout rather than hanging.
    ///
    /// DANGER: these are bytes no capture has shown the device being sent. Unknown
    /// commands can leave the instrument needing a power cycle, and anything
    /// write-shaped will destroy whatever object it reaches. Read-shaped codes only,
    /// and back up first.
    Probe {
        /// Command code, decimal or 0x-prefixed, e.g. 0x20.
        #[arg(value_name = "OP", value_parser = parse_u32)]
        op: u32,

        /// Argument words, appended in order as big-endian u32s: --arg 1 --arg 0.
        #[arg(long = "arg", value_name = "N", value_parser = parse_u32)]
        args: Vec<u32>,

        /// Seconds to wait for a reply before giving up.
        #[arg(long, default_value_t = 5)]
        wait: u64,

        /// Required. Probing is not a read-only operation in the sense the other
        /// read verbs are — the device's response to an unknown code is unknown.
        #[arg(long)]
        yes: bool,

        /// Send with no session around it: no HELLO, no session open, no close.
        ///
        /// The only way to reach a command when the session machinery itself is what
        /// is broken — a wedged instrument refuses to open one, so every ordinary
        /// probe fails before its command is sent.
        #[arg(long)]
        bare: bool,

        /// Service number. 12 is the object/file service, 6 the UI session.
        #[arg(long, default_value_t = 12)]
        service: u32,

        /// Subsystem number. 10 for service 12, 1 for service 6.
        #[arg(long, default_value_t = 10)]
        subsystem: u32,
    },
}

/// Accept `0x2a` as readily as `42`: command codes are quoted in hex everywhere in the
/// protocol notes, and retyping them in decimal invites transcription errors.
fn parse_u32(s: &str) -> Result<u32, String> {
    let s = s.trim();
    match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        Some(hex) => u32::from_str_radix(hex, 16),
        None => s.parse(),
    }
    .map_err(|e| format!("{s}: {e}"))
}

#[derive(Args)]
pub struct EditArgs {
    /// A file (`.ne5p` under `nord program`, `.ne5l` under `nord live`, `.ne5s` under
    /// `nord settings`), or a slot on the instrument (`7:4`). A slot makes this a
    /// read-modify-write over USB, so it is a mutation and obeys `--yes`. Omit it to
    /// start from a fresh default, which then needs `-o`.
    #[arg(
        value_name = "FILE|BANK:SLOT",
        required_unless_present_any = ["fields", "out"],
    )]
    pub target: Option<String>,

    #[command(flatten)]
    pub common: edit::SetArgs,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let ui = Ui::new(cli.color);
    device::set_recording(cli.record);

    let result = match cli.command {
        Command::Inspect { files, raw } => inspect(&ui, &files, raw),
        Command::Verify { files } => verify(&ui, &files),
        Command::Edit(args) => file_edit::run(&ui, args),
        Command::Device { action } => match action {
            DeviceAction::Status { replay, json } => {
                let source = match replay {
                    Some(path) => device::Source::Replay(path),
                    None => device::Source::Usb,
                };
                device::status(&ui, source, json)
            }
            DeviceAction::Info => device::info(&ui),
            DeviceAction::Recover => device::recover(&ui),
            DeviceAction::Geometry => device::geometry(&ui),
            #[cfg(feature = "wedge")]
            DeviceAction::Wedge { class, yes } => {
                device::wedge(&ui, ObjectClass::from_raw(class), yes)
            }
            DeviceAction::Controls {
                from,
                to,
                len,
                interface,
                value,
                index,
            } => device::controls(&ui, from, to, len, interface, value, index),
        },
        Command::Program { action } => match action {
            ProgramAction::Slot(action) => slot_action(&ui, action, ObjectClass::Program),
            ProgramAction::Edit(args) => edit::run(&ui, args, ObjectClass::Program),
        },
        Command::Sample { action } => match action {
            SampleAction::Slot(action) => slot_action(&ui, action, ObjectClass::Sample),
            SampleAction::Edit(args) => sample::run(&ui, args),
            SampleAction::Decode(args) => sample::decode(&ui, args),
            SampleAction::Encode(args) => sample::encode(&ui, args),
            SampleAction::Build(args) => sample::build(&ui, args),
            SampleAction::Verify(args) => sample::verify(&ui, args),
            SampleAction::Project { action } => match action {
                SampleProjectAction::New(args) => sample::project_new(&ui, args),
            },
        },
        Command::Piano { action } => match action {
            PianoAction::Slot(action) => slot_action(&ui, action, ObjectClass::Piano),
            PianoAction::Inspect(args) => piano::inspect(&ui, args),
            PianoAction::Decode(args) => piano::decode(&ui, args),
            PianoAction::Edit(args) => piano::edit(&ui, args),
            PianoAction::Trim(args) => piano::trim(&ui, args),
            PianoAction::Split(args) => piano::split(&ui, args),
            PianoAction::Build(args) => piano::build(&ui, args),
            PianoAction::Rebuild(args) => piano::rebuild(&ui, args),
            PianoAction::Verify(args) => piano::verify(&ui, args),
        },
        Command::Setlist { action } => match action {
            SetlistAction::Slot(action) => slot_action(&ui, action, ObjectClass::SetList),
            SetlistAction::Edit(args) => edit::run(&ui, args, ObjectClass::SetList),
        },
        Command::Live { action } => match action {
            LiveAction::Slot(action) => slot_action(&ui, action.into(), ObjectClass::Live),
            LiveAction::Edit(args) => edit::run(&ui, args, ObjectClass::Live),
        },
        Command::Settings { action } => match action {
            SettingsAction::Slot(action) => slot_action(&ui, action.into(), ObjectClass::Settings),
            SettingsAction::Edit(args) => edit::run(&ui, args, ObjectClass::Settings),
        },
        Command::Raw { class, action } => slot_action(&ui, action, ObjectClass::from_raw(class)),
    };

    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            ui.note(format!("{}: {e}", ui.danger("error")));
            ExitCode::FAILURE
        }
    }
}

impl From<SettingsSlotAction> for SlotAction {
    fn from(action: SettingsSlotAction) -> SlotAction {
        match action {
            SettingsSlotAction::Get {
                at,
                out,
                body,
                sweep,
            } => SlotAction::Get {
                at,
                out,
                body,
                sweep,
            },
            SettingsSlotAction::Info { at } => SlotAction::Info { at },
        }
    }
}

impl From<LiveSlotAction> for SlotAction {
    fn from(action: LiveSlotAction) -> SlotAction {
        match action {
            LiveSlotAction::Get {
                at,
                out,
                body,
                sweep,
            } => SlotAction::Get {
                at,
                out,
                body,
                sweep,
            },
            LiveSlotAction::Info { at } => SlotAction::Info { at },
            LiveSlotAction::Deps { at } => SlotAction::Deps { at },
        }
    }
}

/// `nord raw --class` help, naming every class [`ObjectClass::from_raw`] recognises.
fn class_help() -> String {
    // Every class `from_raw` names has a one-byte code.
    let named: Vec<String> = (0..=u8::MAX.into())
        .map(ObjectClass::from_raw)
        .filter(|class| !matches!(class, ObjectClass::Unknown(_)))
        .map(|class| format!("{} {}", class.to_raw(), class.label()))
        .collect();
    format!("Object class: {}", named.join(", "))
}

/// Dispatch one verb against a fixed object class, whichever noun asked for it.
///
/// The read-only verbs take a file as well as a slot ([`slot::Target`]); the rest name
/// device storage, which no file stands in for.
fn slot_action(ui: &Ui, action: SlotAction, class: ObjectClass) -> Result<(), String> {
    match action {
        SlotAction::Get {
            at,
            out,
            body,
            sweep,
        } => match slot::target(&at)? {
            slot::Target::File(path) if sweep => Err(format!(
                "--sweep re-reads the instrument as the panel changes; {} has only one state",
                path.display()
            )),
            slot::Target::File(path) => file::get(ui, &path, out, class, body),
            slot::Target::Slot(at) => match (sweep, out) {
                (true, Some(dir)) => device::sweep(ui, at, dir, class, body),
                (true, None) => Err("--sweep fills a directory; give -o a path".into()),
                (false, out) => device::get(ui, at, out, class, body),
            },
        },
        SlotAction::Put { file, at, yes } => device::put(ui, file, slot::parse(&at)?, class, yes),
        SlotAction::Move { from, to, yes } => {
            device::move_object(ui, slot::parse(&from)?, slot::parse(&to)?, class, yes)
        }
        SlotAction::Rename { at, name, yes } => {
            device::rename(ui, slot::parse(&at)?, name, class, yes)
        }
        SlotAction::Duplicate { from, to, yes } => {
            device::duplicate(ui, slot::parse(&from)?, slot::parse(&to)?, class, yes)
        }
        SlotAction::Delete { slots, yes } => {
            device::delete(ui, &slot::parse_all(&slots)?, class, yes)
        }
        SlotAction::Select { at } => device::select(ui, slot::parse(&at)?, class),
        SlotAction::Info { at } => match slot::target(&at)? {
            slot::Target::File(path) => file::info(ui, &path, class),
            slot::Target::Slot(at) => device::slot_info(ui, at, class),
        },
        SlotAction::Deps { at } => match slot::target(&at)? {
            slot::Target::File(path) => file::deps(ui, &path, class),
            slot::Target::Slot(at) => device::deps(ui, at, class),
        },
        SlotAction::Focus => device::focus(ui, class),
        SlotAction::List => device::list(ui, class),
        SlotAction::Probe {
            op,
            args,
            wait,
            yes,
            bare,
            service,
            subsystem,
        } => device::probe(ui, class, op, &args, wait, yes, bare, service, subsystem),
    }
}

fn inspect(ui: &Ui, files: &[PathBuf], raw: bool) -> Result<(), String> {
    let mut failed = 0usize;
    for (i, path) in files.iter().enumerate() {
        if i > 0 {
            ui.out("");
        }
        ui.out(path.display());
        match nord_format::from_path(path) {
            Ok(entity) if raw => ui.out(format!("{entity:#?}")),
            Ok(entity) => summary::print(ui, &entity),
            Err(e) => {
                ui.note(format!("  error: {e}"));
                failed += 1;
            }
        }
    }
    match failed {
        0 => Ok(()),
        n => Err(format!("{n} of {} file(s) did not parse", files.len())),
    }
}

/// Parse each file and re-emit it, checking the bytes come back identical.
///
/// Reports the offset of the first difference, which in a bit-packed format is usually
/// enough to name the field on its own.
fn verify(ui: &Ui, files: &[PathBuf]) -> Result<(), String> {
    file::check_each(ui, files, "file(s) did not round-trip", |path| {
        let named = |e: &dyn std::fmt::Display| format!("error  {} ({e})", path.display());
        let original = std::fs::read(path).map_err(|e| named(&e))?;
        let reencoded = nord_format::from_path(path)
            .and_then(|entity| nord_format::to_bytes(&entity))
            .map_err(|e| named(&e))?;
        if reencoded == original {
            return Ok(format!(
                "ok     {} ({} bytes)",
                path.display(),
                original.len()
            ));
        }
        Err(format!(
            "DIFFER {} (in {} bytes, out {}; first difference at {})",
            path.display(),
            original.len(),
            reencoded.len(),
            file::first_difference(&reencoded, &original),
        ))
    })
}

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

    #[test]
    fn the_class_help_names_the_settings_singleton() {
        let help = class_help();
        assert!(help.contains("7 settings"), "{help}");
    }
}