rblhost 0.3.0

The rblhost application is a fast command-line utility providing McuBoot library used on the host computer to initiate communication and issue commands to the MCU bootloader.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
// Copyright 2025-2026 NXP
//
// SPDX-License-Identifier: BSD-3-Clause
#![allow(
    clippy::doc_markdown,
    clippy::missing_errors_doc,
    reason = "Docs here are not used by rustdoc, they are used by clap for CLI help"
)]

use std::{
    ffi::OsString,
    fmt::Write as FmtWrite,
    fs::File,
    io::{Read, Write},
};
mod batch;
mod image_parser;
mod parsers;
use std::path::Path;

use clap::{Arg, ArgGroup, CommandFactory, FromArgMatches, Parser, Subcommand};
use image_parser::ImageParser;
use log::{LevelFilter, debug, warn};
use mboot::{
    CommunicationError, EFUSE_LOCK_FLAG, GetPropertyResponse, KeyProvisioningResponse, McuBoot, ReadMemoryResponse,
    protocols::{Protocol, ProtocolOpen, i2c::I2CProtocol, uart::UARTProtocol, usb::USBProtocol},
    tags::{
        command::{KeyProvOperation, TrustProvOperation},
        property::PropertyTagDiscriminants,
        status::StatusCode,
    },
};
use pretty_hex::{HexConfig, PrettyHex};

fn main() -> anyhow::Result<()> {
    let args = std::env::args();
    // FIXME this probably isn't the best solution to ignore "--", but it's the best I've come up with to stay compatible with the python version
    let args = match parse_args_from(args.filter(|arg| arg != "--")) {
        Ok(args) => args,
        Err(error) => error.exit(),
    };
    env_logger::builder()
        .filter_level(match args.verbose {
            0 => LevelFilter::Warn,
            1 => LevelFilter::Info,
            2 => LevelFilter::Debug,
            _ => LevelFilter::Trace,
        })
        .format_timestamp_millis()
        .parse_default_env()
        .init();

    // `list-usb` does not operate on a specific device, so it is handled before the
    // device group (--port/--i2c/--usb) is required to be set.
    if let Commands::ListUsb { all } = args.command {
        return list_usb(all);
    }

    if args.device.port.is_some() {
        let mut blhost = Blhost::new_from_uart(args)?;
        run_blhost(&mut blhost)?;
    } else if args.device.i2c.is_some() {
        let mut blhost = Blhost::new_from_i2c(args)?;
        run_blhost(&mut blhost)?;
    } else if args.device.usb.is_some() {
        let mut blhost = Blhost::new_from_usb(args)?;
        run_blhost(&mut blhost)?;
    } else {
        anyhow::bail!(
            "No device specified. Use one of --port, --i2c, or --usb \
             (run 'rblhost list-usb' to see connected USB-HID devices)."
        );
    }
    Ok(())
}

fn parse_args_from<I, T>(args: I) -> Result<Args, clap::Error>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    let matches = cli_command().try_get_matches_from(args)?;
    Args::from_arg_matches(&matches)
}

fn cli_command() -> clap::Command {
    let mut command = Args::command();
    configure_help_flags(&mut command);
    command
}

pub(crate) fn configure_help_flags(command: &mut clap::Command) {
    for subcommand in command.get_subcommands_mut() {
        match subcommand.get_name() {
            "read-memory" | "fuse-read" | "read_key_store" => add_long_help_only(subcommand),
            _ => {}
        }
        configure_help_flags(subcommand);
    }
}

fn add_long_help_only(command: &mut clap::Command) {
    *command = command.clone().disable_help_flag(true).arg(
        Arg::new("help")
            .long("help")
            .action(clap::ArgAction::Help)
            .help("Print help"),
    );
}

/// Lists currently connected USB-HID devices (VID/PID, OS path, serial number).
///
/// By default, only devices with a known NXP vendor ID are shown. For each device, prints
/// a ready-to-use `-u/--usb` argument that can be copy-pasted directly, e.g. into
/// `rblhost -u "<value>" get-property 1`.
fn list_usb(all: bool) -> anyhow::Result<()> {
    let devices = USBProtocol::list_devices(all)?;
    if devices.is_empty() {
        if all {
            println!("No USB-HID devices found.");
        } else {
            println!("No NXP USB-HID devices found. Use 'list-usb --all' to see all connected HID devices.");
        }
    } else {
        for (index, device) in devices.iter().enumerate() {
            if index > 0 {
                println!();
            }
            println!("USB device #{}:", index + 1);
            println!("  VID/PID:  0x{:04X}:0x{:04X}", device.vid, device.pid);
            println!("  Path:     {}", device.path);
            if let Some(topology) = device.topology_path.as_deref() {
                println!("  Topology: {topology}");
            }
            println!(
                "  Serial:   {}",
                device
                    .serial_number
                    .as_deref()
                    .filter(|s| !s.is_empty())
                    .unwrap_or("N/A")
            );
            println!("  Product:  {}", device.product_string.as_deref().unwrap_or("N/A"));
            println!("  -u \"{}\"", device.usb_arg());
            if let Some(topology_arg) = device.usb_topology_arg() {
                println!("  -u \"{topology_arg}\"  (stable across reconnect/reset, recommended on Linux/macOS)");
            }
        }
    }
    Ok(())
}

fn run_blhost<T>(blhost: &mut Blhost<T>) -> anyhow::Result<()>
where
    T: Protocol,
{
    blhost.execute()?;
    Ok(())
}

// TODO the original blhost can just *recover* the board when the program crashes and doesn't send ACK? would be nice to have that here too

#[derive(clap::Args, Debug)]
#[group(multiple = false)]
struct Device {
    /// I2C device identifier in format /dev/i2c-X[:0xYY] where X is the bus number
    /// and YY is the optional slave address [default: 0x10]
    #[arg(long)]
    i2c: Option<String>,
    /// UART port identifier
    ///
    /// Baudrate can be optionally specified after a colon, e.g. "COM1,38400".
    /// Default baudrate is 57600.
    #[arg(long, short)]
    port: Option<String>,
    /// USB-HID device identifier in format "vid[,pid[,selector]]" (e.g., "0x1FC9,0x0135"),
    /// or a bare "<selector>" with no vid/pid at all
    ///
    /// <vid> and <pid> accept decimal or hex (0x-prefixed) numbers. If several devices
    /// share the same VID/PID (e.g. identical boards for parallel programming), add a
    /// third <selector> field: a case-insensitive substring of the device's OS path, its
    /// exact serial number, or its exact USB topology (port-chain) path (Linux/macOS), e.g.
    /// "0x1FC9,0x0135,6&7909BF&0&0000", "0x1FC9,0x0135,ABCD1234", or
    /// "0x1FC9,0x0135,1-1.4.3". Alternatively, if a plain path/serial/topology path is
    /// already unique on its own, it can be used directly without any vid/pid prefix, e.g.
    /// "6&7909BF&0&0000", "ABCD1234", or "1-1.4.3". On Linux and macOS, prefer the topology
    /// path over the OS path: the OS path (/dev/hidrawN, DevSrvsID:<id>) is only unique until
    /// the device is disconnected/reconnected or reset, while the topology path stays stable as long as
    /// the physical USB cabling/hub topology doesn't change. Use 'rblhost list-usb' to see
    /// connected devices and their paths/serial numbers/topology paths.
    #[arg(long, short)]
    usb: Option<String>,
}

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Args {
    #[command(flatten)]
    device: Device,

    /// Serial read timeout in milliseconds
    #[arg(short, long, default_value_t = 5000)]
    timeout: u64,

    /// Polling interval for reading in milliseconds
    #[arg(long, default_value_t = 1)]
    polling_interval: u64,

    /// Surpress status response and response words
    #[arg(short, long)]
    silent: bool,
    /// Verbosity level, use more for more verbosity
    ///
    /// -v means info, -vv means debug and -vvv and more is trace level. If RUST_LOG environment
    /// variable is set, it overrides this option. For more documentation about it, refer to
    /// env_logger crate.
    #[arg(short, long, action = clap::ArgAction::Count, default_value_t = 0)]
    verbose: u8,
    /// Command to send to device
    #[command(subcommand)]
    command: Commands,
    #[arg(long, hide = true)]
    secret: bool,
}

/// Lock option of `efuse-program-once`, matching blhost's `[nolock/lock]` argument.
#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum EfuseLock {
    /// Leave the efuse word unlocked
    Nolock,
    /// Permanently lock the efuse word
    Lock,
}

// this can't be CommandTag directly, some commands (like ReadMemory) provide additional options
#[derive(Subcommand, Debug, Clone)]
pub enum Commands {
    /// Execute commands from a file using one shared device connection.
    ///
    /// One command per line, with shell-style quoting and # comments. Global options
    /// apply to the entire batch. Stops at the first error without reconnecting.
    Batch {
        /// Path to the command file
        command_file: String,
    },

    /// Queries various bootloader properties and settings.
    GetProperty {
        /// Number or name representing the requested property
        ///
        /// Available properties:
        ///  1 or 'current-version'             Bootloader version
        ///  2 or 'available-peripherals'       Available peripherals
        ///  3 or 'flash-start-address'         Start of program flash, <index> is required
        ///  4 or 'flash-size'                  Size of program flash, <index> is required
        ///  5 or 'flash-sector-size'           Size of flash sector, <index> is required
        ///  6 or 'flash-block-count'           Blocks in flash array, <index> is required
        ///  7 or 'available-commands'          Available commands
        ///  8 or 'check-status'                Check Status, <status id> is required
        ///  9 or 'reserved'
        /// 10 or 'verify-writes'               Verify Writes flag
        /// 11 or 'max-packet-size'             Max supported packet size
        /// 12 or 'reserved-regions'            Reserved regions
        /// 13 or 'reserved'
        /// 14 or 'ram-start-address'           Start of RAM, <index> is required
        /// 15 or 'ram-size-in-bytes'           Size of RAM, <index> is required
        /// 16 or 'system-device-id'            System device identification
        /// 17 or 'security-state'              Flash security state
        /// 18 or 'unique-device-id'            Unique device identification
        /// 19 or 'flash-fac-support'           FAC support flag
        /// 20 or 'flash-access-segment-size'   FAC segment size
        /// 21 or 'flash-access-segment-count'  FAC segment count
        /// 22 or 'flash-read-margin'           Read margin level of program flash
        /// 23 or 'qspi/otfad-init-status'      QuadSpi initialization status
        /// 24 or 'target-version'              Target version
        /// 25 or 'external-memory-attributes'  External memory attributes, <memoryId> is required
        /// 26 or 'reliable-update-status'      Reliable update status
        /// 27 or 'flash-page-size'             Flash page size, <index> is required
        /// 28 or 'irq-notifier-pin'            Interrupt notifier pin
        /// 29 or 'pfr-keystore_update-opt'     PFR key store update option
        /// 30 or 'byte-write-timeout-ms'       Byte write timeout in ms
        /// 31 or 'fuse-locked-status'          Fuse Locked Status
        ///
        /// for kw45xx/k32w1xx devices:
        /// 10 or 'verify-erases'               Verify Erases flag
        /// 20 or 'boot status'                 Value of Boot Status Register
        /// 21 or 'loadable-fw-version'         LoadableFWVersion
        /// 22 or 'fuse-program-voltage'        Fuse Program Voltage
        ///
        /// for mcxa1xx devices:
        /// 17 or 'life-cycle'                  Life Cycle
        ///
        /// Note: Not all the properties are available for all devices.
        // a value parser from clap could be used here; however, it can't convert from repr
        #[arg(value_parser=PropertyTagDiscriminants::parse_property, verbatim_doc_comment)]
        property_tag: PropertyTagDiscriminants,
        /// ID of the memory
        #[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
        memory_index: u32,
    },
    /// Reset the device.
    ///
    /// Response packet is sent before the device resets.
    Reset,
    /// Jumps to code at the provided address.
    ///
    /// The system is returned to a reset state before the jump.
    Execute {
        /// Jump address.
        #[arg(value_parser=parsers::parse_number::<u32>)]
        start_address: u32,
        /// Function argument pointer passed to R0.
        #[arg(value_parser=parsers::parse_number::<u32>)]
        argument: u32,
        /// Stack pointer. If set to zero, the code being called should
        /// set the stack pointer before using the stack.
        #[arg(value_parser=parsers::parse_number::<u32>)]
        stackpointer: u32,
    },
    /// Invokes code at an address, passing an argument to it.
    ///
    Call {
        /// Jump address.
        #[arg(value_parser=parsers::parse_number::<u32>)]
        start_address: u32,
        /// Function argument pointer passed to R0.
        #[arg(value_parser=parsers::parse_number::<u32>)]
        argument: u32,
    },
    /// Perform an erase of the entire flash memory.
    ///
    /// Note: Protected regions are excluded.
    FlashEraseAll {
        /// ID of the memory to erase
        #[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
        memory_id: u32,
    },
    /// Fills the memory with a pattern.
    FillMemory {
        /// Starting address
        #[arg(value_parser=parsers::parse_number::<u32>)]
        start_address: u32,
        /// Number of bytes to fill
        #[arg(value_parser=parsers::parse_number::<u32>)]
        byte_count: u32,
        /// Pattern to fill
        #[arg(value_parser=parsers::parse_number::<u32>)]
        pattern: u32,
    },
    /// Reads the memory and writes it to a file or stdout.
    ReadMemory {
        /// Starting address
        #[arg(value_parser=parsers::parse_number::<u32>)]
        start_address: u32,
        /// Number of bytes to read
        #[arg(value_parser=parsers::parse_number::<u32>)]
        byte_count: u32,
        /// Store read bytes into <FILE>
        ///
        /// If you need to specify [MEMORY_ID], use '-' instead of filename to print to stdout.
        file: Option<String>,
        /// ID of the memory to read from
        #[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
        memory_id: u32,
        /// Use hexdump format
        #[arg(long = "use-hexdump", short = 'h', default_value_t = false)]
        use_hexdump: bool,
    },
    /// Changes properties and options in the bootloader.
    ///
    /// Accepts the same <PROPERTY_TAG> used with the get-property sub-command.
    SetProperty {
        /// Number or name representing the requested property
        ///
        /// Available properties to set:
        /// 10 or 'verify-writes'               Verify Writes flag
        /// 22 or 'flash-read-margin'           Read margin level of program flash
        /// 28 or 'irq-notify-pin'              Interrupt notifier pin
        /// 29 or 'pfr-keystore_update-opt'     PFR key store update option
        /// 30 or 'byte-write-timeout-ms'       Byte write timeout in ms
        ///
        /// for kw45xx/k32w1xx devices:
        /// 10 or 'verify-erases'               Verify Erases flag
        /// 22 or 'fuse-program-voltage'        Fuse Program Voltage
        ///
        /// Note: Not all properties can be set on all devices.
        #[arg(value_parser=PropertyTagDiscriminants::parse_property, verbatim_doc_comment)]
        property_tag: PropertyTagDiscriminants,
        /// Value to set <PROPERTY_TAG> to
        #[arg(value_parser=parsers::parse_number::<u32>)]
        value: u32,
    },
    /// Sets a config at internal memory to memory with ID.
    ///
    /// The specified configuration block must have been previously written to memory using the write-memory command.
    ConfigureMemory {
        /// ID of the memory
        #[arg(value_parser=parsers::parse_number::<u32>)]
        memory_id: u32,
        /// Starting address
        #[arg(value_parser=parsers::parse_number::<u32>)]
        address: u32,
    },
    /// Erase Complete Flash and Unlock.
    FlashEraseAllUnsecure,
    /// Erases one or more sectors of the flash memory.
    ///
    /// The start <ADDRESS> and <BYTE_COUNT> must be a multiple of the word size.
    /// The entire sector(s) containing the start and end address is erased.
    FlashEraseRegion {
        /// Starting address
        #[arg(value_parser=parsers::parse_number::<u32>)]
        start_address: u32,
        /// Number of bytes to erase
        #[arg(value_parser=parsers::parse_number::<u32>)]
        byte_count: u32,
        /// ID of the memory to erase
        #[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
        memory_id: u32,
    },
    /// Write memory from a file or CLI.
    ///
    /// Only one of <FILE> (with <LIMIT>) or <BYTES> must be specified.
    #[command(
        override_usage = concat!(color_print::cstr!("<bold>rblhost write-memory"), " <START_ADDRESS> FILE[,LIMIT] | {{HEX_DATA}} [MEMORY_ID]"),
        args=[
            Arg::new("FILE").help("write the content of this file"),
            Arg::new("LIMIT").help("If specified, load only first [LIMIT] bytes from FILE"),
            Arg::new("HEX_DATA").help("A string of hex values: {{112233}}, {{11 22 33}}"),
        ]
    )]
    WriteMemory {
        /// Starting address
        #[arg(value_parser=parsers::parse_number::<u32>, display_order=0)]
        start_address: u32,
        #[arg(value_parser=parsers::parse_hex_values, hide = true)]
        bytes: Box<[u8]>,
        /// ID of the memory to write
        #[arg(default_value_t = 0)]
        memory_id: u32,
    },
    /// Program fuse.
    ///
    /// Only one of <FILE> (with optional <BYTE_COUNT>) or <HEX_DATA> must be specified.
    #[command(
    override_usage = concat!(
        color_print::cstr!("<bold>rblhost fuse-program"),
        " <START_ADDRESS> FILE[,BYTE_COUNT] | {{HEX_DATA}} [MEMORY_ID]"
    ),
    group = ArgGroup::new("file_input").args(&["file", "byte_count"]),
    group = ArgGroup::new("hex_input").args(&["hex_data"]),
    group = ArgGroup::new("input")
        .args(&["file", "hex_data"])
        .required(true)
        .multiple(false)
)]
    FuseProgram {
        /// Start address.
        #[arg(value_parser = parsers::parse_number::<u32>, display_order = 0)]
        start_address: u32,

        /// Write the content of this file.
        file: Option<String>,

        /// If specified, load only first BYTE_COUNT number of bytes.
        #[arg(requires = "file")]
        byte_count: Option<u32>,

        /// A string of hex values: {{112233}}, {{11 22 33}}
        #[arg(value_parser = parsers::parse_hex_values)]
        hex_data: Option<Box<[u8]>>,

        /// ID of memory to read from (default: 0)
        #[arg(default_value_t = 0)]
        memory_id: u32,
    },
    /// Reads the fuse and writes it to the file or stdout.
    FuseRead {
        /// Start address.
        #[arg(value_parser=parsers::parse_number::<u32>)]
        start_address: u32,
        /// Number of bytes to read.
        #[arg(value_parser=parsers::parse_number::<u32>)]
        byte_count: u32,
        /// Store result into this file, if not specified use stdout.
        file: Option<String>,
        /// ID of memory to read from (default: 0)
        #[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
        memory_id: u32,
        /// Use hexdump format
        #[arg(long = "use-hexdump", short = 'h', default_value_t = false)]
        use_hexdump: bool,
    },
    /// Receives a file in a Secure Binary (SB) format.
    ReceiveSbFile {
        #[arg(value_parser=|s: &str| parsers::parse_file(s, None))]
        bytes: Box<[u8]>,
    },

    /// Read from MCU flash program once region (eFuse/OTP)
    FlashReadOnce {
        /// Start index of the eFuse/OTP region
        #[arg(value_parser=parsers::parse_number::<u32>)]
        index: u32,

        /// Number of bytes to read (must be 4 or 8, default: 4)
        #[arg(value_parser=parsers::parse_once_byte_count, default_value_t=4)]
        count: u32,
    },

    /// Returns the contents of a specific efuse word.
    ///
    /// Equivalent to `flash-read-once INDEX 4`, matching blhost's `efuse-read-once`.
    EfuseReadOnce {
        /// Address of the OTP word, not the shadowed memory address
        #[arg(value_parser=parsers::parse_number::<u32>)]
        address: u32,
    },

    /// Writes data to a specific efuse word.
    ///
    /// Each efuse bit can only be programmed once. Equivalent to `flash-program-once INDEX 4 DATA`,
    /// matching blhost's `efuse-program-once`.
    EfuseProgramOnce {
        /// Address of the OTP word, not the shadowed memory address
        #[arg(value_parser=parsers::parse_number::<u32>)]
        address: u32,

        /// Data to write, hex digits with or without '0x' prefix (as in blhost)
        #[arg(value_parser=parsers::parse_hex_number::<u32>)]
        data: u32,

        /// Lock the efuse word after programming
        #[arg(value_enum, default_value_t = EfuseLock::Nolock)]
        lock: EfuseLock,

        /// Verify that data were written correctly
        #[arg(long, short, default_value_t = false)]
        verify: bool,
    },

    /// Write into MCU program once region (eFuse/OTP)
    FlashProgramOnce {
        /// Start index of the eFuse/OTP region
        #[arg(value_parser=parsers::parse_number::<u32>)]
        index: u32,

        /// Number of bytes to write (must be 4 or 8)
        #[arg(value_parser=parsers::parse_once_byte_count)]
        count: u32,

        /// Value to write (up to 64-bit, only the low `count` bytes are sent)
        #[arg(value_parser=parsers::parse_number::<u64>)]
        data: u64,

        /// Verify that data were written correctly
        #[arg(long, default_value_t = false)]
        verify: bool,
    },

    /// Group of subcommands related to trust provisioning
    #[command(subcommand)]
    TrustProvisioning(TrustProvOperation),
    /// Group of subcommands related to key provisioning
    #[command(subcommand)]
    KeyProvisioning(KeyProvOperation),
    /// Sends a boot image file to the device.
    ///
    /// Only binary files are supported. The <FILE> must be a bootable
    /// image which contains the boot image header supported by the MCU
    /// bootloader.
    LoadImage {
        /// Boot file to load
        file: String,
    },

    /// Write a formatted image file to flash memory with optional erasing.
    ///
    /// Supports S-record, Intel HEX, Android SPARSE and binary files. The command parses the image file to extract
    /// memory segments and writes them using flash-erase-region and write-memory calls.
    FlashImage {
        /// Path to image file (S-record, Intel HEX, Android SPARSE or binary)
        file: String,

        /// Erase option: 'erase' to erase flash before writing, 'none' to skip erasing
        #[arg(default_value = "none")]
        erase: String,

        /// ID of memory to write to (default: 0)
        #[arg(value_parser=parsers::parse_number::<u32>, default_value_t = 0)]
        memory_id: u32,
        /// Add this offset to every address in the image
        #[arg(short = 'o', long, value_parser=parsers::parse_number::<u32>, default_value_t = 0)]
        base_offset: u32,
    },

    /// Generates a key blob from a DEK file and writes it to a file.
    GenerateKeyBlob {
        /// Binary file containing the DEK
        #[arg(value_parser = |s: &str| parsers::parse_file(s, None))]
        dek_file: Box<[u8]>,
        /// Output file for the generated binary key blob
        blob_file: String,
        /// BKEK selector: 0/1/2/3 or OPTMK/ZMK/CMK
        #[arg(value_parser = parsers::parse_key_sel, default_value = "0")]
        key_sel: u32,
    },

    /// Lists connected USB-HID devices (VID/PID, OS path, serial number).
    ///
    /// Does not require --port/--i2c/--usb to be specified. Useful to find the <path> or
    /// <serial> of a specific board when several identical devices (same VID/PID) are
    /// connected at once, for use with '-u/--usb <vid>,<pid>,<selector>'. By default, only
    /// devices with a known NXP vendor ID are shown; use --all to see every HID device.
    ListUsb {
        /// Show all HID devices on the system, not just known NXP vendor IDs
        #[arg(long)]
        all: bool,
    },
}

pub struct Blhost<T>
where
    T: Protocol,
{
    args: Args,
    boot: McuBoot<T>,
}

const DEFAULT_BAUDRATE: u32 = 57600;
impl Blhost<UARTProtocol> {
    fn new_from_uart(args: Args) -> Result<Self, CommunicationError> {
        let port_spec = args
            .device
            .port
            .as_ref()
            .expect("open_uart called without UART argument");
        // Parse port and optional baudrate
        let mut parts = port_spec.split(',');
        let port_name = parts.next().unwrap();
        let baudrate = parts
            .next()
            .map_or(DEFAULT_BAUDRATE, |v| v.parse().unwrap_or(DEFAULT_BAUDRATE));

        // Use UART protocol with specified baudrate and timeout
        let boot = McuBoot::new(UARTProtocol::open_with_options(
            port_name,
            baudrate,
            std::time::Duration::from_millis(args.timeout),
            std::time::Duration::from_millis(args.polling_interval),
        )?);
        Ok(Blhost { args, boot })
    }
}

impl Blhost<I2CProtocol> {
    fn new_from_i2c(args: Args) -> Result<Self, CommunicationError> {
        let i2c_device = args
            .device
            .i2c
            .as_ref()
            .expect("new_from_i2c called without I2C argument");
        let boot = McuBoot::new(I2CProtocol::open(i2c_device)?);
        Ok(Blhost { args, boot })
    }
}

impl Blhost<USBProtocol> {
    fn new_from_usb(args: Args) -> Result<Self, CommunicationError> {
        let usb_device = args
            .device
            .usb
            .as_ref()
            .expect("new_from_usb called without USB argument");
        let boot = McuBoot::new(USBProtocol::open_with_options(
            usb_device,
            0, // Baudrate not used for USB
            std::time::Duration::from_millis(args.timeout),
            std::time::Duration::from_millis(args.polling_interval),
        )?);
        Ok(Blhost { args, boot })
    }
}

impl<T> Blhost<T>
where
    T: Protocol,
{
    pub fn new(args: Args, device: T) -> Blhost<T> {
        Blhost {
            args,
            boot: McuBoot::new(device),
        }
    }

    pub fn execute(&mut self) -> anyhow::Result<()> {
        if let Commands::Batch { ref command_file } = self.args.command {
            let command_file = command_file.clone();
            self.execute_batch(&command_file)
        } else {
            self.execute_command()?;
            Ok(())
        }
    }

    #[allow(clippy::too_many_lines, reason = "match statement here will always be long")]
    fn execute_command(&mut self) -> Result<StatusCode, CommunicationError> {
        self.boot.progress_bar = !self.args.silent;

        let status = match self.args.command {
            Commands::GetProperty {
                property_tag,
                memory_index,
            } => {
                let response = &self.boot.get_property(property_tag, memory_index)?;
                self.display_property(response);
                response.status
            }
            Commands::Reset => {
                let status = self.boot.reset()?;
                self.display_status(status);
                status
            }
            Commands::Execute {
                start_address,
                argument,
                stackpointer,
            } => {
                let status = self.boot.execute(start_address, argument, stackpointer)?;
                self.display_status(status);
                status
            }
            Commands::Call {
                start_address,
                argument,
            } => {
                let status = self.boot.call(start_address, argument)?;
                self.display_status(status);
                status
            }
            Commands::FlashEraseAll { memory_id } => {
                let status = self.boot.flash_erase_all(memory_id)?;
                self.display_status(status);
                status
            }
            Commands::FillMemory {
                start_address,
                byte_count,
                pattern,
            } => {
                let status = self.boot.fill_memory(start_address, byte_count, pattern)?;
                self.display_status(status);
                status
            }
            Commands::ReadMemory {
                start_address,
                byte_count,
                ref file,
                memory_id,
                use_hexdump,
            } => match file.as_deref() {
                None | Some("-") => {
                    let response = self.boot.read_memory(start_address, byte_count, memory_id)?;
                    self.display_memory_bytes(&response, byte_count, use_hexdump);
                    response.status
                }
                Some(file_name) => {
                    let response = self.boot.read_memory(start_address, byte_count, memory_id)?;
                    let mut file = File::create(file_name).map_err(CommunicationError::FileError)?;
                    file.write_all(&response.bytes)?;
                    self.display_memory(&response, byte_count);
                    response.status
                }
            },
            Commands::SetProperty { property_tag, value } => {
                let status = self.boot.set_property(property_tag, value)?;
                self.display_status(status);
                status
            }
            Commands::ConfigureMemory { memory_id, address } => {
                let status = self.boot.configure_memory(memory_id, address)?;
                self.display_status(status);
                status
            }
            Commands::FlashEraseAllUnsecure => {
                let status = self.boot.flash_erase_all_unsecure()?;
                self.display_status(status);
                status
            }
            Commands::FlashEraseRegion {
                start_address,
                byte_count,
                memory_id,
            } => {
                let status = self.boot.flash_erase_region(start_address, byte_count, memory_id)?;
                self.display_status(status);
                status
            }
            Commands::WriteMemory {
                start_address,
                ref bytes,
                memory_id,
            } => {
                let status = self.boot.write_memory(start_address, memory_id, bytes)?;
                self.display_status(status);
                status
            }
            Commands::ReceiveSbFile { ref bytes } => {
                let status = self.boot.receive_sb_file(bytes)?;
                self.display_status(status);
                status
            }
            Commands::TrustProvisioning(ref operation) => {
                let (status, data) = self.boot.trust_provisioning(operation)?;
                self.display_status_words(status, &data);
                self.display_trust_prov(operation, &data);
                status
            }
            Commands::KeyProvisioning(ref operation) => match operation {
                KeyProvOperation::SetUserKey { key_type, key_data } => {
                    if !self.args.silent {
                        debug!(
                            "Setting user key of type {} with {} bytes of data",
                            key_type,
                            key_data.len()
                        );
                    }
                    let response = self.boot.key_provisioning(operation)?;
                    match response {
                        KeyProvisioningResponse::KeyStore { status, .. } | KeyProvisioningResponse::Status(status) => {
                            self.display_status(status);
                            status
                        }
                    }
                }
                KeyProvOperation::SetKey { key_type, key_size } => {
                    if !self.args.silent {
                        debug!("Generating intrinsic key of type {key_type} with size {key_size} bytes");
                    }
                    let response = self.boot.key_provisioning(operation)?;
                    match response {
                        KeyProvisioningResponse::KeyStore { status, .. } | KeyProvisioningResponse::Status(status) => {
                            self.display_status(status);
                            status
                        }
                    }
                }
                KeyProvOperation::ReadKeyStore { file, use_hexdump } => {
                    debug!("Reading key store from device");

                    // Execute the key provisioning command
                    let response = self.boot.key_provisioning(operation)?;

                    match response {
                        KeyProvisioningResponse::KeyStore {
                            status,
                            response_words,
                            bytes,
                        } => {
                            if status.is_success() {
                                // Write to file
                                let mut output_file = File::create(file).map_err(CommunicationError::FileError)?;
                                output_file.write_all(&bytes)?;

                                if !self.args.silent {
                                    println!("Successfully wrote {} bytes to file: {}", bytes.len(), file);

                                    if *use_hexdump {
                                        // Display the data in hexdump format
                                        let cfg = HexConfig {
                                            title: false,
                                            group: 8,
                                            width: 16,
                                            ascii: true,
                                            ..HexConfig::default()
                                        };
                                        println!("{:?}", bytes.hex_conf(cfg));
                                    }
                                }

                                self.display_status_words(status, &response_words);
                            } else {
                                self.display_status(status);
                            }
                            status
                        }
                        KeyProvisioningResponse::Status(status) => {
                            self.display_status(status);
                            status
                        }
                    }
                }
                _ => {
                    let response = self.boot.key_provisioning(operation)?;
                    match response {
                        KeyProvisioningResponse::KeyStore { status, .. } | KeyProvisioningResponse::Status(status) => {
                            self.display_status(status);
                            status
                        }
                    }
                }
            },
            Commands::FlashReadOnce { index, count } => {
                let bytes = self.boot.flash_read_once(index, count)?;
                if !self.args.silent {
                    // Mirror blhost's `flash-read-once` output, which decodes the full
                    // `count`-byte (4 or 8) payload as a single little-endian integer instead of
                    // truncating it to a 32-bit word.
                    let mut buf = [0u8; 8];
                    let len = bytes.len().min(buf.len());
                    buf[..len].copy_from_slice(&bytes[..len]);
                    let value = u64::from_le_bytes(buf);
                    println!("Read value: {value} (0x{value:X})");
                }
                StatusCode::Success
            }
            Commands::FlashProgramOnce {
                index,
                count,
                data,
                verify,
            } => {
                let status = self.boot.flash_program_once(index, count, data, verify)?;
                self.display_status(status);

                if status == StatusCode::OtpVerifyFail {
                    warn!("Verification failed - written value doesn't match read value");
                }
                status
            }
            Commands::EfuseReadOnce { address } => {
                let value = self.boot.efuse_read_once(address)?;
                self.display_status_words(StatusCode::Success, &[4, value]);
                StatusCode::Success
            }
            Commands::EfuseProgramOnce {
                address,
                data,
                lock,
                verify,
            } => {
                let index = match lock {
                    EfuseLock::Lock => address | EFUSE_LOCK_FLAG,
                    EfuseLock::Nolock => address,
                };
                let status = self.boot.efuse_program_once(index, data, verify)?;
                self.display_status(status);

                if status == StatusCode::OtpVerifyFail {
                    warn!("Verification failed - written value doesn't match read value");
                }
                status
            }
            Commands::FuseRead {
                start_address,
                byte_count,
                ref file,
                memory_id,
                use_hexdump,
            } => match file.as_deref() {
                None | Some("-") => {
                    let response = self.boot.fuse_read(start_address, byte_count, memory_id)?;
                    self.display_memory_bytes(&response, byte_count, use_hexdump);
                    response.status
                }
                Some(file_name) => {
                    let response = self.boot.fuse_read(start_address, byte_count, memory_id)?;
                    let mut file = File::create(file_name).map_err(CommunicationError::FileError)?;
                    file.write_all(&response.bytes)?;
                    self.display_memory(&response, byte_count);
                    response.status
                }
            },
            Commands::FuseProgram {
                start_address,
                ref file,
                byte_count,
                ref hex_data,
                memory_id,
            } => {
                let bytes: Vec<u8> = if let Some(hex) = hex_data {
                    hex.to_vec()
                } else if let Some(file_path) = file {
                    let mut file = File::open(file_path).map_err(CommunicationError::FileError)?;
                    let mut buffer = Vec::new();
                    match byte_count {
                        Some(limit) => {
                            buffer.resize(limit as usize, 0);
                            file.read_exact(&mut buffer).map_err(CommunicationError::FileError)?;
                        }
                        None => {
                            file.read_to_end(&mut buffer).map_err(CommunicationError::FileError)?;
                        }
                    }
                    buffer
                } else {
                    return Err(CommunicationError::InvalidData);
                };
                let status = self.boot.fuse_program(start_address, memory_id, &bytes)?;
                self.display_status(status);
                status
            }
            Commands::LoadImage { ref file } => {
                let mut file = File::open(file).map_err(CommunicationError::FileError)?;
                let mut buffer = Vec::new();
                file.read_to_end(&mut buffer).map_err(CommunicationError::FileError)?;
                let status = self.boot.load_image(&buffer)?;
                self.display_status(status);
                status
            }
            Commands::FlashImage {
                ref file,
                ref erase,
                memory_id,
                base_offset,
            } => {
                let file_path = file.clone();
                let erase_option = erase.clone();
                let status = self.flash_image(&file_path, &erase_option, memory_id, base_offset)?;
                self.display_status(status);
                status
            }
            Commands::GenerateKeyBlob {
                ref dek_file,
                ref blob_file,
                key_sel,
            } => {
                let key_blob = self.boot.generate_key_blob(dek_file, key_sel)?;
                let mut output_file = File::create(blob_file).map_err(CommunicationError::FileError)?;
                output_file.write_all(&key_blob)?;
                let blob_length = u32::try_from(key_blob.len()).map_err(|_| CommunicationError::InvalidData)?;
                self.display_status_words(StatusCode::Success, &[0, blob_length]);
                StatusCode::Success
            }
            Commands::Batch { .. } => unreachable!("Batch is handled in execute()"),
            Commands::ListUsb { .. } => {
                unreachable!("ListUsb is handled in main() before a device connection is opened")
            }
        };

        if self.args.secret {
            println!("congratulations! you found the secret 🍨");
        }

        Ok(status)
    }

    fn display_memory_bytes(&self, response: &ReadMemoryResponse, byte_count: u32, use_hexdump: bool) {
        let formatted = format_memory_bytes(&response.bytes, use_hexdump);
        if !formatted.is_empty() {
            println!("{formatted}");
        }
        self.display_memory(response, byte_count);
    }

    fn display_memory(&self, response: &ReadMemoryResponse, byte_count: u32) {
        self.display_status_words(response.status, &response.response_words);
        if !self.args.silent {
            println!("Read {} of {byte_count} bytes.", response.bytes.len());
        }
    }

    fn display_property(&self, response: &GetPropertyResponse) {
        self.display_status_words(response.status, &response.response_words);
        println!("{}", response.property);
    }

    fn display_status_words(&self, status: StatusCode, response_words: &[u32]) {
        self.display_status(status);
        self.display_words(response_words);
    }

    fn display_words(&self, response_words: &[u32]) {
        if !self.args.silent {
            for (i, word) in response_words.iter().enumerate() {
                let i = i + 1;
                println!("Response word {i} = {word} ({word:#x})");
            }
        }
    }

    fn display_status(&self, status: StatusCode) {
        if !self.args.silent {
            println!("Response status = {0} ({0:#x}) {1}.", u32::from(status), status);
        }
    }

    fn display_trust_prov(&self, operation: &TrustProvOperation, response: &[u32]) {
        if !self.args.silent {
            println!("Output data size/value(s) is (are):");
            match operation {
                TrustProvOperation::OemGenMasterShare { .. } => println!(
                    "\
                    \tOEM Share size: {0} ({0:#04X})\n\
                    \tOEM Master Share size: {1} ({1:#04X})\n\
                    \tCust Cert Puk size: {2} ({2:#04X})",
                    response[0], response[1], response[2]
                ),
                TrustProvOperation::OemSetMasterShare { .. } => {}
            }
        }
    }

    fn flash_image(
        &mut self,
        image_file_path: &str,
        erase: &str,
        memory_id: u32,
        base_offset: u32,
    ) -> Result<StatusCode, CommunicationError> {
        const ALIGNMENT: u32 = 1024;

        // Validate file exists
        if !Path::new(image_file_path).is_file() {
            if !self.args.silent {
                println!("Error: The image file does not exist: {image_file_path}");
            }
            return Err(CommunicationError::InvalidData);
        }

        // Validate erase parameter
        if erase != "erase" && erase != "none" {
            if !self.args.silent {
                println!("Error: Invalid erase option '{erase}'. Use 'erase' or 'none'");
            }
            return Err(CommunicationError::InvalidData);
        }

        // Load and parse the image file using the ImageParser
        let mut segments = ImageParser::parse_file(image_file_path)?;
        apply_base_offset(&mut segments, base_offset)?;

        if segments.is_empty() {
            if !self.args.silent {
                println!("Error: No data segments found in image file");
            }
            return Err(CommunicationError::InvalidData);
        }

        if !self.args.silent {
            println!("Loaded image file: {} ({} segments)", image_file_path, segments.len());

            // If it's an S-record file, show additional info
            if ImageParser::is_srec_format(image_file_path)
                && let Ok((_, info)) = ImageParser::parse_srec_with_info(image_file_path)
            {
                if let Some(header) = &info.header {
                    println!("  Header: {header}");
                }
                println!("  Data length: {}", info.data_length);
                println!("  Memory regions: {}", info.memory_regions);
            }

            for (i, segment) in segments.iter().enumerate() {
                println!(
                    "  Segment #{}: address=0x{:08X}, size={} bytes",
                    i + 1,
                    segment.address,
                    segment.data.len()
                );
            }
        }

        // Erase regions if requested
        if erase == "erase" {
            if !self.args.silent {
                println!("Erasing flash regions...");
            }

            for (i, segment) in segments.iter().enumerate() {
                let aligned_start = Self::align_down(segment.address, ALIGNMENT);
                let segment_length = u32::try_from(segment.data.len()).map_err(|_| CommunicationError::InvalidData)?;
                let segment_end = segment
                    .address
                    .checked_add(segment_length)
                    .ok_or(CommunicationError::InvalidData)?;
                let aligned_end = Self::align_up(segment_end, ALIGNMENT).ok_or(CommunicationError::InvalidData)?;
                let aligned_length = aligned_end - aligned_start;

                if !self.args.silent {
                    println!(
                        "Erasing segment #{}: address=0x{:08X}, length=0x{:08X}",
                        i + 1,
                        aligned_start,
                        aligned_length
                    );
                }

                let status = self.boot.flash_erase_region(aligned_start, aligned_length, memory_id)?;
                if !status.is_success() {
                    return Ok(status);
                }
            }
        }

        // Write segments
        for (i, segment) in segments.iter().enumerate() {
            if !self.args.silent {
                println!(
                    "Writing segment #{}: address=0x{:08X}, size={} bytes",
                    i + 1,
                    segment.address,
                    segment.data.len()
                );
            }

            let status = self.boot.write_memory(segment.address, memory_id, &segment.data)?;
            if !status.is_success() {
                return Ok(status);
            }
        }

        Ok(StatusCode::Success)
    }

    // Helper methods for alignment
    fn align_down(value: u32, alignment: u32) -> u32 {
        value & !(alignment - 1)
    }

    fn align_up(value: u32, alignment: u32) -> Option<u32> {
        value.checked_add(alignment - 1).map(|value| value & !(alignment - 1))
    }
}

fn format_memory_bytes(bytes: &[u8], use_hexdump: bool) -> String {
    if use_hexdump {
        let cfg = HexConfig {
            title: false,
            group: 8,
            width: 16,
            ascii: true,
            ..HexConfig::default()
        };
        format!("{:?}", bytes.hex_conf(cfg))
    } else {
        let mut formatted = String::with_capacity(bytes.len().saturating_mul(3));
        for (index, byte) in bytes.iter().enumerate() {
            if index > 0 && index % 16 == 0 {
                formatted.push('\n');
            }
            write!(formatted, "{byte:02x} ").expect("writing to a String cannot fail");
        }
        formatted
    }
}

fn apply_base_offset(segments: &mut [image_parser::ImageSegment], base_offset: u32) -> Result<(), CommunicationError> {
    for segment in segments {
        segment.address = segment
            .address
            .checked_add(base_offset)
            .ok_or(CommunicationError::InvalidData)?;
        let segment_length = u32::try_from(segment.data.len()).map_err(|_| CommunicationError::InvalidData)?;
        segment
            .address
            .checked_add(segment_length)
            .ok_or(CommunicationError::InvalidData)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{Args, Commands, EfuseLock, KeyProvOperation, apply_base_offset, format_memory_bytes, parse_args_from};
    use crate::image_parser::ImageSegment;
    use clap::Parser;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_flash_image_base_offset() {
        let mut segments = [
            ImageSegment {
                address: 0x1000,
                data: vec![1],
            },
            ImageSegment {
                address: 0x2000,
                data: vec![2],
            },
        ];
        apply_base_offset(&mut segments, 0x4000).unwrap();
        assert_eq!(segments[0].address, 0x5000);
        assert_eq!(segments[1].address, 0x6000);
    }

    #[test]
    fn test_flash_image_base_offset_rejects_overflow() {
        let mut segments = [ImageSegment {
            address: u32::MAX,
            data: vec![1],
        }];
        assert!(apply_base_offset(&mut segments, 1).is_err());
    }

    #[test]
    fn test_flash_image_accepts_base_offset() {
        let args = parse_args_from([
            "rblhost",
            "--port",
            "COM1",
            "flash-image",
            "image.srec",
            "--base-offset",
            "0x1000",
        ])
        .unwrap();
        assert!(matches!(
            args.command,
            Commands::FlashImage {
                base_offset: 0x1000,
                ..
            }
        ));
    }

    #[test]
    fn test_generate_key_blob_cli_arguments() {
        let mut dek_file = NamedTempFile::new().unwrap();
        dek_file.write_all(&[1, 2, 3]).unwrap();
        let args = parse_args_from([
            "rblhost",
            "--port",
            "COM1",
            "generate-key-blob",
            dek_file.path().to_str().unwrap(),
            "blob.bin",
            "ZMK",
        ])
        .unwrap();
        match args.command {
            Commands::GenerateKeyBlob {
                dek_file,
                blob_file,
                key_sel,
            } => {
                assert_eq!(&*dek_file, &[1, 2, 3]);
                assert_eq!(blob_file, "blob.bin");
                assert_eq!(key_sel, 2);
            }
            other => panic!("expected GenerateKeyBlob, got {other:?}"),
        }
    }

    #[test]
    fn test_read_memory_hexdump_short_option_matches_blhost() {
        let args = parse_args_from(["rblhost", "--port", "COM1", "read-memory", "0", "4", "-h"]).unwrap();
        assert!(matches!(args.command, Commands::ReadMemory { use_hexdump: true, .. }));
    }

    #[test]
    fn test_fuse_read_hexdump_short_option_matches_blhost() {
        let args = parse_args_from(["rblhost", "--port", "COM1", "fuse-read", "0", "4", "-h"]).unwrap();
        assert!(matches!(args.command, Commands::FuseRead { use_hexdump: true, .. }));
    }

    #[test]
    fn test_read_key_store_hexdump_short_option_matches_blhost() {
        let args = parse_args_from([
            "rblhost",
            "--port",
            "COM1",
            "key-provisioning",
            "read_key_store",
            "key-store.bin",
            "-h",
        ])
        .unwrap();
        assert!(matches!(
            args.command,
            Commands::KeyProvisioning(KeyProvOperation::ReadKeyStore { use_hexdump: true, .. })
        ));

        let args = parse_args_from([
            "rblhost",
            "--port",
            "COM1",
            "key-provisioning",
            "read_key_store",
            "key-store.bin",
            "--use-hexdump",
        ])
        .unwrap();
        assert!(matches!(
            args.command,
            Commands::KeyProvisioning(KeyProvOperation::ReadKeyStore { use_hexdump: true, .. })
        ));

        let args = parse_args_from([
            "rblhost",
            "--port",
            "COM1",
            "key-provisioning",
            "read_key_store",
            "key-store.bin",
            "--use_hexdump",
        ]);
        assert!(matches!(
            args.unwrap().command,
            Commands::KeyProvisioning(KeyProvOperation::ReadKeyStore { use_hexdump: true, .. })
        ));
    }

    #[test]
    fn test_hexdump_commands_keep_long_help() {
        let error = parse_args_from(["rblhost", "--port", "COM1", "read-memory", "--help"]).unwrap_err();
        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayHelp);
    }

    #[test]
    fn test_read_key_store_keeps_long_help() {
        let error = parse_args_from([
            "rblhost",
            "--port",
            "COM1",
            "key-provisioning",
            "read_key_store",
            "--help",
        ])
        .unwrap_err();
        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayHelp);
    }

    #[test]
    fn test_memory_bytes_are_formatted_in_lowercase() {
        assert_eq!(format_memory_bytes(&[0x00, 0xA1, 0xFF], false), "00 a1 ff ");
        let bytes = [0u8; 17];
        assert_eq!(
            format_memory_bytes(&bytes, false),
            format!("{} \n00 ", "00 ".repeat(16).trim_end())
        );
    }
    /// `flash-program-once` positional argument order must match blhost's
    /// `INDEX BYTE_COUNT DATA [ENDIANNESS]` (i.e. `INDEX COUNT DATA [--verify]`), not accidentally
    /// swap `count` and `data`.
    #[test]
    fn test_flash_program_once_arg_order_matches_blhost() {
        let args = parse_args_from(["rblhost", "--port", "COM1", "flash-program-once", "0x5", "8", "0x10"]).unwrap();
        match args.command {
            Commands::FlashProgramOnce {
                index,
                count,
                data,
                verify,
            } => {
                assert_eq!(index, 0x5);
                assert_eq!(count, 8);
                assert_eq!(data, 0x10);
                assert!(!verify);
            }
            other => panic!("expected FlashProgramOnce, got {other:?}"),
        }
    }

    #[test]
    fn test_flash_program_once_count_required() {
        // blhost's `byte_count` positional argument is required (no default), so rblhost should
        // behave the same way instead of silently defaulting to 4.
        let result = parse_args_from(["rblhost", "--port", "COM1", "flash-program-once", "0x5", "0x10"]);
        assert!(result.is_err(), "count argument should be required, matching blhost");
    }

    #[test]
    fn test_flash_program_once_count_must_be_4_or_8() {
        // blhost restricts byte_count to `click.Choice(["4", "8"])`; rblhost must reject any
        // other value instead of silently accepting it (e.g. reinterpreting a stale 3-arg
        // `INDEX DATA COUNT` invocation as `INDEX COUNT DATA`).
        for count in ["1", "0x12", "16"] {
            let result = parse_args_from(["rblhost", "--port", "COM1", "flash-program-once", "0x5", count, "0x10"]);
            assert!(
                result.is_err(),
                "count {count} should be rejected, only 4 or 8 are valid"
            );
        }
    }

    #[test]
    fn test_flash_program_once_accepts_64bit_data_for_count_8() {
        // count == 8 must allow a full 64-bit value, not just a 32-bit one.
        let args = parse_args_from([
            "rblhost",
            "--port",
            "COM1",
            "flash-program-once",
            "0x5",
            "8",
            "0x1122334455667788",
        ])
        .unwrap();
        match args.command {
            Commands::FlashProgramOnce { count, data, .. } => {
                assert_eq!(count, 8);
                assert_eq!(data, 0x1122_3344_5566_7788);
            }
            other => panic!("expected FlashProgramOnce, got {other:?}"),
        }
    }

    #[test]
    fn test_flash_read_once_count_must_be_4_or_8() {
        for count in ["1", "0x12", "16"] {
            let result = parse_args_from(["rblhost", "--port", "COM1", "flash-read-once", "0x5", count]);
            assert!(
                result.is_err(),
                "count {count} should be rejected, only 4 or 8 are valid"
            );
        }
    }

    /// `efuse-program-once` must accept blhost's `ADDRESS DATA [nolock/lock]` form, parsing
    /// `DATA` as hex even without a `0x` prefix so that blhost scripts burn the same value.
    #[test]
    fn test_efuse_program_once_matches_blhost() {
        let args = Args::parse_from(["rblhost", "--port", "COM1", "efuse-program-once", "0x60", "12"]);
        match args.command {
            Commands::EfuseProgramOnce {
                address,
                data,
                lock,
                verify,
            } => {
                assert_eq!(address, 0x60);
                assert_eq!(data, 0x12);
                assert_eq!(lock, EfuseLock::Nolock);
                assert!(!verify);
            }
            other => panic!("expected EfuseProgramOnce, got {other:?}"),
        }

        let args = Args::parse_from([
            "rblhost",
            "--port",
            "COM1",
            "efuse-program-once",
            "96",
            "0xDEADBEEF",
            "lock",
            "--verify",
        ]);
        match args.command {
            Commands::EfuseProgramOnce {
                address,
                data,
                lock,
                verify,
            } => {
                assert_eq!(address, 96);
                assert_eq!(data, 0xDEAD_BEEF);
                assert_eq!(lock, EfuseLock::Lock);
                assert!(verify);
            }
            other => panic!("expected EfuseProgramOnce, got {other:?}"),
        }
    }

    #[test]
    fn test_efuse_program_once_rejects_invalid_input() {
        for extra in [
            &["0x60", "1FFFFFFFF"][..],
            &["0x60", "zz"],
            &["0x60", "12", "maybe"],
            &["0x60"],
        ] {
            let mut argv = vec!["rblhost", "--port", "COM1", "efuse-program-once"];
            argv.extend_from_slice(extra);
            assert!(Args::try_parse_from(argv).is_err(), "{extra:?} should be rejected");
        }
    }

    #[test]
    fn test_efuse_read_once() {
        let args = Args::parse_from(["rblhost", "--port", "COM1", "efuse-read-once", "0x60"]);
        match args.command {
            Commands::EfuseReadOnce { address } => assert_eq!(address, 0x60),
            other => panic!("expected EfuseReadOnce, got {other:?}"),
        }
        assert!(Args::try_parse_from(["rblhost", "--port", "COM1", "efuse-read-once"]).is_err());
    }
}