ch32rv 0.12.2

Flashing and debugging tool for WCH CH32 RISC-V microcontrollers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
//! en: `flash`, `erase`, `reset`, and `recover` (docs/cli.ja.md §4.1). These write to the
//! target. `flash` erases (per policy), programs via the flash loader stub, verifies by
//! readback, resets to run, and (with `--confirm-run`) checks the target is actually running.
//! `recover --method power-off|nrst` is the "Clear All Code Flash" recovery for a target whose
//! debug pins were repurposed.
//! ja: `flash` / `erase` / `reset` / `recover`。target へ書き込む。flash は消去→stub 経由で
//! 書き込み→readback verify→reset run→(--confirm-run で)走行確認。recover は debug ピンを
//! 他用途に使った target の「Clear All Code Flash」復旧。

use std::process::ExitCode;
use std::time::Duration;

use ch32rv_contract::event::Event;
use ch32rv_contract::policy::{
    ConfirmRunMode, EraseMode, MonitorSource, RecoverMethod, ResetPolicy, VerifyMode,
};
use ch32rv_contract::progress::ProgressSink;
use ch32rv_contract::{ErrorKind, ResultEnvelope, Warning};
use ch32rv_flash::{CODE_FLASH_START, Image, Segment, params_for_family};

use std::path::Path;

use crate::args::{Cli, FlashArgs, RecoverArgs, SwitchState};
use crate::cmd_probe::{confirm_destructive, fail, mode_str, select_entry};
use crate::parse;
use crate::session::Session;

/// en: Parse an image, treating a magic-less `.bin`/extensionless file as raw bin under
/// `--format auto` (ELF/HEX/UF2 are still detected by magic; anything else still errors).
/// ja: `--format auto` で magic の無い `.bin`/拡張子無しは raw bin 扱いにする。
pub(crate) fn parse_image(
    bytes: &[u8],
    format: ch32rv_contract::policy::ImageFormat,
    path: &Path,
    bin_offset: Option<u32>,
    code_flash_start: u32,
) -> Result<Image, ch32rv_flash::ImageError> {
    use ch32rv_contract::policy::ImageFormat;
    match Image::parse(bytes, format, bin_offset, code_flash_start) {
        Err(ch32rv_flash::ImageError::UnknownFormat) if format == ImageFormat::Auto => {
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .map(str::to_ascii_lowercase);
            if matches!(ext.as_deref(), Some("bin") | None) {
                Image::parse(bytes, ImageFormat::Bin, bin_offset, code_flash_start)
            } else {
                Err(ch32rv_flash::ImageError::UnknownFormat)
            }
        }
        other => other,
    }
}

/// en: Read `expected.len()` bytes at `addr` for verification. Uses the fast WCH-Link bulk read,
/// but when that disagrees with `expected` (or errors) it re-reads via the authoritative DMI path
/// and returns that instead. The fast read can return stale/garbage right after stub execution on
/// some probes - observed on the CH549 Link (fw 2.12): a false verify-mismatch even though the write
/// landed (capture: the readback was a `00 01 02 ..` ramp, not flash). DMI word reads (progbuf) are
/// the source of truth, so this makes verify robust without paying the DMI cost on the common match.
/// The hart must already be halted.
/// ja: verify 用に `addr` から `expected.len()` byte 読む。まず fast bulk read、`expected` と食い違う
/// (またはエラー)なら権威ある DMI 読みで読み直して返す。fast read は stub 実行直後に一部 probe
/// (CH549 Link fw2.12 で実測)で stale/ゴミを返し false verify-mismatch を起こす。DMI が真実。/// en: How a family gets programmed. Most families upload WCH's flash loader stub to the probe,
/// which then streams the image; the V00x line has no stub, so its own FLASH controller is driven
/// directly over DMI instead (what minichlink calls "direct mode" - the only route WCH's tooling
/// uses for these parts either).
/// ja: family ごとの書込経路。多くは probe へ WCH の flash loader stub を載せて流すが、V00x 系は
/// stub が無いので target の FLASH controller を DMI で直接叩く(minichlink の "direct mode")。
enum Programmer {
    /// The probe runs WCH's loader stub in target RAM.
    Stub(Box<ch32rv_wchlink::FlashParams>),
    /// The host drives the target's FLASH controller over DMI, page by page.
    Controller(ch32rv_flash::FlashCtrlProfile),
}

fn verify_read(session: &mut Session, addr: u32, expected: &[u8]) -> Result<Vec<u8>, String> {
    let len = expected.len() as u32;
    match session.link().read_mem(addr, len) {
        Ok(d) if d == expected => Ok(d),
        // Mismatch or transport error: re-read via the authoritative DMI path (progbuf word reads),
        // which goes through the real bus and reflects the just-programmed flash. The fast bulk read
        // is only an optimization, so silently preferring the authoritative source on disagreement is
        // correct - a real mismatch is still caught (DMI confirms it), a stale one is corrected.
        _ => session.dm().read_mem(addr, len).map_err(|e| e.to_string()),
    }
}

/// en: The set of flash pages (page-aligned start addresses) that the given `(addr, len)`
/// segments touch, for a `page`-byte page size. `--erase sector` erases exactly these pages, so
/// it never wipes flash outside the image. A segment that starts mid-page pulls in its whole
/// page; segments that share a page collapse to one entry.
/// ja: `(addr, len)` セグメント群が触れる flash page(page 境界の開始番地)の集合。`--erase sector`
/// はこの page だけを消すので image 外の flash を消さない。page 途中開始はその page 全体を含む。
/// en: What the chosen programmer will actually write, for a given image. Both the erase plan and
/// the program step go through this, so the pages that get erased are exactly the pages that get
/// programmed. The stub path must hand the probe ONE contiguous region ([`Image::program_span`] -
/// only the first `write_flash` of a session takes effect); the FLASH-controller path drives whole
/// pages itself and takes the image's natural blocks, gaps and all. Either way a linked ELF's
/// `.data` initialiser - its own segment, starting right behind `.text` - stops being a write the
/// programmer cannot start (the stub would drop it silently, the controller would re-program a page
/// it had already written).
/// ja: 選ばれた programmer が実際に書く単位。消去計画も書込も同じこれを通すので、**消される page と
/// 焼かれる page が一致する**。stub 経路は 1 つの連続 region を渡さなければならない
/// ([`Image::program_span`]。1 セッションで効くのは最初の `write_flash` だけ)。controller 経路は
/// page 単位で自分で駆動するので image 本来の block のままでよい。どちらでも、link 済み ELF の
/// `.data` 初期値(`.text` 直後から始まる独立 segment)が「programmer が書き始められない write」で
/// なくなる(stub は黙って捨て、controller は書いた page を二度焼きしていた)。
fn planned_writes(programmer: &Programmer, image: &Image) -> Vec<Segment> {
    match programmer {
        // The stub programs one data packet at a time; that packet is the family's flash page.
        Programmer::Stub(fp) => image
            .program_span(fp.data_packet_size as u32)
            .into_iter()
            .collect(),
        Programmer::Controller(profile) => image.program_blocks(profile.page_size),
    }
}

pub(crate) fn covered_pages(
    segments: impl IntoIterator<Item = (u32, u32)>,
    page: u32,
) -> std::collections::BTreeSet<u32> {
    let mut pages = std::collections::BTreeSet::new();
    for (addr, len) in segments {
        let first = addr - (addr % page);
        let end = addr.saturating_add(len); // exclusive
        let mut p = first;
        while p < end {
            pages.insert(p);
            p = p.saturating_add(page);
        }
    }
    pages
}

/// en: Resolve the effective erase scope. `auto` becomes `chip` for a program loaded from the
/// flash base (a full flash - one fast whole-chip erase) and `sector` for a partial/offset image
/// (never wipe outside it); `--restore-unwritten` forces `sector` since it needs a page-granular
/// erase. Every other mode passes through unchanged.
/// ja: 実効 erase scope を決める。`auto` は flash 先頭から始まる program(=フル)なら `chip`、
/// 部分/offset image なら `sector`。`--restore-unwritten` は page 単位 erase が要るので `sector` に
/// 倒す。他のモードはそのまま。
fn resolve_erase(
    requested: EraseMode,
    base_addr: Option<u32>,
    code_flash_start: u32,
    restore_unwritten: bool,
) -> EraseMode {
    match requested {
        EraseMode::Auto => {
            if base_addr == Some(code_flash_start) && !restore_unwritten {
                EraseMode::Chip
            } else {
                EraseMode::Sector
            }
        }
        other => other,
    }
}

/// en: Overlay `segments` onto one page's pre-read `content` (the page starts at `page_addr` and
/// is `content.len()` bytes): bytes a segment covers take the segment's value, the rest keep their
/// original `content`. Used by `--restore-unwritten` so a page can be re-programmed whole without
/// losing bytes the image does not touch.
/// ja: `content`(page 先頭 `page_addr`、長さ=page サイズ)に `segments` を上書き合成する。segment
/// が覆う byte はその値、他は元の `content` のまま。`--restore-unwritten` で page 全体を再 program
/// するのに使う。
pub(crate) fn overlay_page(page_addr: u32, content: &mut [u8], segments: &[Segment]) {
    ch32rv_flash::overlay(page_addr, content, segments);
}

pub fn flash(cli: &Cli, args: &FlashArgs) -> ExitCode {
    if args.repeat {
        flash_repeat(cli, args)
    } else {
        flash_once(cli, args)
    }
}

/// en: `--repeat` (production): program the current target, then wait for the operator to remove it
/// and insert the next one, and program that too - looping until interrupted (Ctrl-C). A failed
/// board is reported and the loop moves on to the next, matching a production line's flow.
/// ja: `--repeat`(量産): 今の target を焼き、operator が外して次を挿すのを待って焼く、を Ctrl-C まで
/// 繰り返す。失敗 board は報告して次へ進む(産線の流れに合わせる)。
fn flash_repeat(cli: &Cli, args: &FlashArgs) -> ExitCode {
    let mut count = 0u32;
    loop {
        count += 1;
        eprintln!("repeat: programming target #{count} (Ctrl-C to stop)");
        let _ = flash_once(cli, args);
        eprintln!("repeat: remove the programmed target ...");
        wait_for_chip(cli, false);
        eprintln!("repeat: insert the next target ...");
        wait_for_chip(cli, true);
    }
}

/// en: Poll the selected probe until a target chip is present (`want == true`) or absent
/// (`want == false`). The probe (WCH-Link) stays enumerated across a target swap, so this attaches
/// to the chip through it; only Ctrl-C (process signal) breaks the wait.
/// ja: 選択 probe に target chip が有る(want=true)/無い(want=false)になるまで poll。probe 自体は
/// target 交換で再列挙されないので、それ越しに chip へ attach を試す。抜けるのは Ctrl-C のみ。
fn wait_for_chip(cli: &Cli, want: bool) {
    loop {
        if chip_present(cli) == want {
            return;
        }
        std::thread::sleep(Duration::from_millis(300));
    }
}

/// Whether a target chip currently answers AttachChip on the selected probe.
fn chip_present(cli: &Cli) -> bool {
    let Ok(entry) = select_entry(cli, "flash") else {
        return false;
    };
    let Ok(mut link) = ch32rv_wchlink::WchLink::open(&entry.dev) else {
        return false;
    };
    let _ = link.probe_info();
    let present = link.attach_chip().is_ok();
    let _ = link.detach_chip();
    present
}

fn flash_once(cli: &Cli, args: &FlashArgs) -> ExitCode {
    const CMD: &str = "flash";
    let bytes = match std::fs::read(&args.file) {
        Ok(d) => d,
        Err(e) => {
            return fail(
                cli,
                CMD,
                ErrorKind::Usage,
                format!("read {}: {e}", args.file.display()),
                None,
            );
        }
    };

    // An OEP probe (`tcp:`, `oep://`, a serial port no WCH-Link owns) takes the OEP path. A
    // WCH-Link whose broker runs (an open monitor) is borrowed from it for the direct path below -
    // WCH's stub stays - and handed back when this returns.
    let _lend = match crate::oep::addr(cli, CMD) {
        Ok(Some(crate::oep::OepAddr::Wch(t))) => match crate::broker::lend(&t) {
            Ok(l) => Some(crate::broker::LendScope::new(l)),
            Err(m) => return fail(cli, CMD, ErrorKind::DeviceBusy, m, None),
        },
        Ok(Some(a)) => return crate::oep::flash(cli, args, &bytes, &a),
        Ok(None) => None,
        Err(c) => return c,
    };

    let entry = match select_entry(cli, CMD) {
        Ok(e) => e,
        Err(c) => return c,
    };
    if entry.mode != ch32rv_contract::ProbeMode::Riscv {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            format!(
                "probe is in {} mode; flashing requires RISC-V mode",
                mode_str(entry.mode)
            ),
            None,
        );
    }
    let (speed, mut warnings) = match parse::speed(&cli.speed) {
        Ok(v) => v,
        Err(m) => return fail(cli, CMD, ErrorKind::Usage, m, None),
    };
    let timeout = Duration::from_millis(cli.timeout.map(|s| s * 1000).unwrap_or(3000));
    let mut session = match Session::attach(
        &entry,
        speed,
        timeout,
        Duration::from_secs(cli.lock_timeout),
        cli.chip.as_deref(),
        cli.db.as_deref(),
        &mut warnings,
    ) {
        Ok(s) => s,
        Err(e) => return crate::cmd_probe::session_error(cli, CMD, e),
    };

    if args.programmer == crate::args::ProgrammerChoice::Loader {
        return flash_via_loader(cli, args, &bytes, session, warnings);
    }

    let family = session.attach.family_byte;
    let programmer = match params_for_family(family) {
        Some(fp) => Programmer::Stub(Box::new(fp)),
        None => match ch32rv_flash::flash_controller_profile(family) {
            Some(profile) => Programmer::Controller(profile),
            None => {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::CapabilityUnsupported,
                    format!(
                        "flashing family 0x{family:02x} ({}) is not supported yet (no flash stub and no FLASH-controller profile)",
                        session.family()
                    ),
                    Some("`capabilities` lists what this probe/target pair can do"),
                );
            }
        },
    };

    // Parse the input into flash segments (ELF / Intel HEX / UF2 / raw bin).
    let bin_offset = match &args.at {
        Some(s) => match parse::u32_addr(s) {
            Ok(a) => Some(a),
            Err(m) => return fail(cli, CMD, ErrorKind::Usage, m, None),
        },
        None => None,
    };
    let image = match parse_image(
        &bytes,
        args.format,
        &args.file,
        bin_offset,
        CODE_FLASH_START,
    ) {
        Ok(i) => i,
        Err(e) => return fail(cli, CMD, ErrorKind::Usage, e.to_string(), None),
    };
    // The probe reports flash size; use it to reject out-of-range segments.
    let flash_size = session.chip.as_ref().map(|c| c.flash_bytes).unwrap_or(0);
    if flash_size > 0
        && let Err(e) = image.check_within_flash(CODE_FLASH_START, flash_size)
    {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            e.to_string(),
            Some("wrong --chip or --offset?"),
        );
    }
    let total = image.total_len() as u64;

    let sink = crate::progress::sink(cli);

    // --preverify: if the target already holds this exact image, skip erase+program entirely (saves
    // a flash cycle and its wear). Read the image region and compare before doing anything
    // destructive; on a mismatch, reset the link state and fall through to a normal flash.
    if args.preverify {
        sink.event(&Event::Phase {
            name: "preverify".into(),
            total: Some(total),
        });
        let already_matches = {
            if let Err(e) = session.dm().halt() {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::AttachFailed,
                    format!("halt for preverify failed: {e}"),
                    None,
                );
            }
            let mut all = true;
            for seg in &image.segments {
                // Fast bulk read via the WCH-Link; fall back to DMI word reads on error.
                let readback = match session.link().read_mem(seg.addr, seg.data.len() as u32) {
                    Ok(d) => d,
                    Err(_) => match session.dm().read_mem(seg.addr, seg.data.len() as u32) {
                        Ok(d) => d,
                        Err(e) => {
                            return fail(
                                cli,
                                CMD,
                                ErrorKind::TransferFailed,
                                format!("preverify read failed at {:#010x}: {e}", seg.addr),
                                None,
                            );
                        }
                    },
                };
                if readback != seg.data {
                    all = false;
                    break;
                }
            }
            all
        };
        // We halted the core to read; reset the link/target state before whatever comes next.
        session.link().detach_chip().ok();
        let _ = session.link().attach_chip();
        if already_matches {
            return finish_flash(
                cli,
                CMD,
                session,
                total,
                "none",
                true,
                Some(true),
                warnings,
                args.reset,
                args.confirm_run,
                args.sdi,
                args.monitor,
            );
        }
    }

    // Erase per policy.
    //   chip   - one fast whole-chip erase (~100x faster per area than page erase).
    //   sector - erase only the flash pages the image covers, via the direct FLASH controller, so
    //            nothing outside the image is touched (a bootloader / calibration data in high
    //            flash survives). `sector` was previously a silent alias for chip erase - a
    //            data-loss footgun - and now erases surgically.
    //   auto   - chip for a program loaded from the flash base (a full flash, so the one fast
    //            erase is right), sector for a partial/offset image (never wipe outside it).
    //   none   - skip erase.
    // The chosen scope is reported (JSON `erase`, and a line of normal output) so `auto` is never
    // a mystery.
    let erase = resolve_erase(
        args.erase,
        image.base_addr(),
        CODE_FLASH_START,
        args.restore_unwritten,
    );
    let erase_scope = match erase {
        EraseMode::None => "none",
        EraseMode::Chip => "chip",
        EraseMode::Sector => "sector",
        EraseMode::Auto => unreachable!("auto resolved above"),
    };
    // `--restore-unwritten` re-programs whole pages, so it needs a page-granular (sector) erase.
    if args.restore_unwritten && erase != EraseMode::Sector {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            format!("--restore-unwritten needs page-granular erase, but --erase is {erase_scope}"),
            Some("use --erase sector (or --erase auto with a partial/offset image)"),
        );
    }
    // Full pages to program instead of the sparse image, populated only under --restore-unwritten
    // (each covered page read pre-erase, with the image overlaid, so unwritten bytes survive).
    let mut restored: Option<Vec<Segment>> = None;
    match erase {
        EraseMode::Auto => unreachable!("auto resolved above"),
        EraseMode::None => {}
        EraseMode::Chip => {
            sink.event(&Event::Phase {
                name: "erase".into(),
                total: None,
            });
            if let Err(e) = session.link().erase_flash() {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::TransferFailed,
                    format!("erase failed: {e}"),
                    None,
                );
            }
        }
        EraseMode::Sector => {
            // Sector erase needs a verified FLASH-controller profile (page size + mechanism).
            let Some(cprofile) = ch32rv_flash::flash_controller_profile(family) else {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::CapabilityUnsupported,
                    format!(
                        "--erase sector is not supported for {} (0x{family:02x}) yet",
                        session.family()
                    ),
                    Some("use --erase chip to erase the whole chip"),
                );
            };
            // restore-unwritten needs a true 0xff readback for erased cells, so a blank byte in a
            // page is not confused with real data and re-programmed as a placeholder.
            if args.restore_unwritten && !cprofile.erased_reads_ff {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::CapabilityUnsupported,
                    format!(
                        "--restore-unwritten is not supported on {} (erased cells do not read back as 0xff)",
                        session.family()
                    ),
                    Some("omit --restore-unwritten; sector erase clears whole covered pages"),
                );
            }
            let page = cprofile.page_size;
            // Every flash page any segment touches (dedup + sorted, page-aligned). Erase them all
            // before programming so segments that share a page never wipe each other.
            // The planned writes, not the raw segments: the stub path programs one contiguous
            // region, so any gap inside it has to be erased too - otherwise it would program
            // unerased pages. `--restore-unwritten` puts their previous content back below.
            let planned = planned_writes(&programmer, &image);
            let pages = covered_pages(planned.iter().map(|s| (s.addr, s.data.len() as u32)), page);
            let total_pages = pages.len() as u64;
            sink.event(&Event::Phase {
                name: "erase".into(),
                total: Some(total_pages),
            });
            if let Err(e) = session.dm().halt() {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::AttachFailed,
                    format!("halt for sector erase failed: {e}"),
                    None,
                );
            }
            // restore-unwritten: capture each page's current content (before erasing) and overlay
            // the image on it, so the program step rewrites whole pages and unwritten bytes survive.
            if args.restore_unwritten {
                let mut dm = session.dm();
                let mut merged = Vec::with_capacity(pages.len());
                for &pg in &pages {
                    let mut buf = match dm.read_mem(pg, page) {
                        Ok(b) => b,
                        Err(e) => {
                            return fail(
                                cli,
                                CMD,
                                ErrorKind::TransferFailed,
                                format!("restore-unwritten read of page 0x{pg:08x} failed: {e}"),
                                None,
                            );
                        }
                    };
                    buf.resize(page as usize, 0xff);
                    overlay_page(pg, &mut buf, &image.segments);
                    merged.push(Segment {
                        addr: pg,
                        data: buf,
                    });
                }
                restored = Some(merged);
            }
            {
                let mode = cprofile.mode;
                let mut dm = session.dm();
                for (i, pg) in pages.iter().enumerate() {
                    if let Err(e) = dm.flash_page_erase(*pg, mode) {
                        return fail(
                            cli,
                            CMD,
                            ErrorKind::TransferFailed,
                            format!("sector erase failed at 0x{pg:08x}: {e}"),
                            None,
                        );
                    }
                    sink.event(&Event::Progress {
                        phase: "erase".into(),
                        done: (i + 1) as u64,
                        total: Some(total_pages),
                    });
                }
            }
            // Reset the link/target debug state so the stub loader programs from a clean slate
            // (mirrors the detach/reattach the verify step does below; verified to program
            // correctly into page-erased - not chip-erased - flash). The controller path keeps
            // driving the same halted core, so re-attaching there would only undo the halt.
            if matches!(programmer, Programmer::Stub(_)) {
                session.link().detach_chip().ok();
                let _ = session.link().attach_chip();
            }
        }
    }

    // Program each segment. Under --restore-unwritten we program the merged whole pages instead of
    // the sparse image (so unwritten bytes in a partially-filled page keep their original values).
    // Either way what goes out is `planned_writes`, not the raw segments.
    let source_image = match &restored {
        Some(segs) => Image {
            segments: segs.clone(),
        },
        None => image.clone(),
    };
    let program_segments = planned_writes(&programmer, &source_image);
    let program_segments: &[Segment] = &program_segments;
    let program_total: u64 = program_segments.iter().map(|s| s.data.len() as u64).sum();
    sink.event(&Event::Phase {
        name: "program".into(),
        total: Some(program_total),
    });
    match &programmer {
        Programmer::Stub(fp) => {
            let s = &sink;
            let mut base = 0u64;
            for seg in program_segments {
                let seg_len = seg.data.len() as u64;
                if let Err(e) = session.link().write_flash(seg.addr, &seg.data, fp, |done| {
                    s.event(&Event::Progress {
                        phase: "program".into(),
                        done: base + done,
                        total: Some(program_total),
                    });
                }) {
                    return fail(
                        cli,
                        CMD,
                        ErrorKind::TransferFailed,
                        format!("program failed at {:#010x}: {e}", seg.addr),
                        None,
                    );
                }
                base += seg_len;
            }
        }
        // No stub for this family: drive the target's own FLASH controller over DMI, page by page.
        // Uncovered bytes of a partially-filled page go out as 0xff, which is what the page holds
        // after the erase step - the same result the stub path produces. `--restore-unwritten` has
        // already merged the old content into `program_segments` when the caller asked for it.
        Programmer::Controller(profile) => {
            if let Err(e) = session.dm().halt() {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::AttachFailed,
                    format!("halt for controller programming failed: {e}"),
                    None,
                );
            }
            let page = profile.page_size;
            let mode = profile.mode;
            let mut dm = session.dm();
            let mut done = 0u64;
            for seg in program_segments {
                let one = std::slice::from_ref(seg);
                for pg in covered_pages([(seg.addr, seg.data.len() as u32)], page) {
                    let mut buf = vec![0xffu8; page as usize];
                    overlay_page(pg, &mut buf, one);
                    if let Err(e) = dm.flash_program_page(pg, &buf, mode) {
                        return fail(
                            cli,
                            CMD,
                            ErrorKind::TransferFailed,
                            format!("program failed at page {pg:#010x}: {e}"),
                            None,
                        );
                    }
                    done = (done + u64::from(page)).min(program_total);
                    sink.event(&Event::Progress {
                        phase: "program".into(),
                        done,
                        total: Some(program_total),
                    });
                }
            }
        }
    }

    // Verify (readback), unless disabled.
    let mut verified = None;
    if !matches!(args.verify, VerifyMode::None) {
        sink.event(&Event::Phase {
            name: "verify".into(),
            total: Some(total),
        });
        session.link().detach_chip().ok();
        let _ = session.link().attach_chip();
        if let Err(e) = session.dm().halt() {
            return fail(
                cli,
                CMD,
                ErrorKind::AttachFailed,
                format!("halt for verify failed: {e}"),
                None,
            );
        }
        for seg in &image.segments {
            // Fast bulk readback, re-checked via the authoritative DMI read on mismatch/error
            // (fast read can return stale data right after stub execution on the CH549 Link).
            let readback = match verify_read(&mut session, seg.addr, &seg.data) {
                Ok(d) => d,
                Err(e) => {
                    return fail(
                        cli,
                        CMD,
                        ErrorKind::TransferFailed,
                        format!("readback failed: {e}"),
                        None,
                    );
                }
            };
            if readback != seg.data {
                let at = readback
                    .iter()
                    .zip(&seg.data)
                    .position(|(a, b)| a != b)
                    .unwrap_or(0);
                return fail(
                    cli,
                    CMD,
                    ErrorKind::VerifyMismatch,
                    format!("verify mismatch at {:#010x}", seg.addr as usize + at),
                    None,
                );
            }
        }
        verified = Some(true);
    }

    finish_flash(
        cli,
        CMD,
        session,
        total,
        erase_scope,
        false,
        verified,
        warnings,
        args.reset,
        args.confirm_run,
        args.sdi,
        args.monitor,
    )
}

/// en: Apply the reset policy (run/halt/none, with `--confirm-run`), optionally set the SDI print
/// state (`--sdi`) and hand off to a monitor session (`--monitor`), then print/emit the result.
/// Shared by the normal end of `flash` and the `--preverify` "already matches" skip path. Takes the
/// session by value so it can be dropped (releasing the probe's USB handle) before a monitor
/// session re-opens the probe.
/// ja: reset 方針を適用し、必要なら SDI print 状態を設定(`--sdi`)して monitor へ移行(`--monitor`)、
/// 結果を出す。`flash` の通常終了と `--preverify` スキップ経路で共有。monitor が probe を開き直せる
/// よう session を値で受け、drop で USB を解放してから渡す。
#[allow(clippy::too_many_arguments)]
fn finish_flash(
    cli: &Cli,
    cmd: &str,
    mut session: Session,
    total: u64,
    erase_scope: &str,
    skipped: bool,
    verified: Option<bool>,
    warnings: Vec<Warning>,
    reset: ResetPolicy,
    confirm: Option<ConfirmRunMode>,
    sdi: Option<SwitchState>,
    monitor: Option<MonitorSource>,
) -> ExitCode {
    let mut running = None;
    // en: A Link borrowed from its broker (a monitor is open) is handed back with the reset: the
    // broker reopens its consoles first, so the firmware's first output is polled.
    // ja: ブローカーから借りた Link は reset ごと返す(ブローカーが console を開き直してから reset
    // するので、firmware の最初の出力を汲める)。
    if reset == ResetPolicy::Run && crate::broker::lend_active() {
        let family = session.family();
        drop(session);
        running = crate::broker::hand_back_with_reset();
        if confirm.is_some() && running != Some(true) {
            return finish_lent(
                cli,
                cmd,
                &family,
                total,
                erase_scope,
                skipped,
                verified,
                running,
                warnings,
            );
        }
        return finish_lent_ok(
            cli,
            cmd,
            &family,
            total,
            erase_scope,
            skipped,
            verified,
            running,
            warnings,
            monitor,
        );
    }
    match reset {
        ResetPolicy::Run => {
            if let Err(msg) = soft_reset_and_run(&mut session) {
                return fail(cli, cmd, ErrorKind::TransferFailed, msg, None);
            }
            if let Some(mode) = confirm {
                std::thread::sleep(Duration::from_millis(200));
                running = Some(confirm_run(&mut session, mode));
                if running == Some(false) {
                    return finish(
                        cli,
                        cmd,
                        &session.family(),
                        total,
                        erase_scope,
                        skipped,
                        verified,
                        running,
                        warnings,
                        Some((
                            ErrorKind::NotRunningAfterWrite,
                            "programmed and verified, but the target is not running after reset"
                                .to_owned(),
                        )),
                    );
                }
            }
        }
        ResetPolicy::Halt => {
            let mut dm = session.dm();
            let _ = dm.halt();
        }
        ResetPolicy::None => {}
    }

    // --sdi: set the probe's SDI-print forwarding after the target is (re)started. A failure here
    // must not fail the flash (programming already succeeded) - surface it as a warning.
    if let Some(state) = sdi {
        let on = matches!(state, SwitchState::On);
        if let Err(e) = session.link().set_sdi_print_enabled(on) {
            eprintln!(
                "warning[sdi]: could not set SDI print {}: {e}",
                if on { "on" } else { "off" }
            );
        }
    }

    let exit = finish(
        cli,
        cmd,
        &session.family(),
        total,
        erase_scope,
        skipped,
        verified,
        running,
        warnings,
        None,
    );

    // --monitor: hand off to a monitor session (runs until Ctrl-C). Drop the flash session first so
    // its USB handle is released and the monitor backend can open the probe / its CDC port.
    if let Some(source) = monitor {
        drop(session);
        let margs = crate::args::MonitorArgs {
            cmd: None,
            source,
            port: None,
            baud: 115_200,
        };
        return crate::cmd_monitor::monitor(cli, &margs);
    }
    exit
}

/// The flash's result after a reset the broker did, failing (exit 50) when it was not seen running.
#[allow(clippy::too_many_arguments)]
fn finish_lent(
    cli: &Cli,
    cmd: &str,
    family: &str,
    total: u64,
    erase_scope: &str,
    skipped: bool,
    verified: Option<bool>,
    running: Option<bool>,
    warnings: Vec<Warning>,
) -> ExitCode {
    finish(
        cli,
        cmd,
        family,
        total,
        erase_scope,
        skipped,
        verified,
        running,
        warnings,
        Some((
            ErrorKind::NotRunningAfterWrite,
            "programmed and verified, but the target is not running after the broker's reset"
                .to_owned(),
        )),
    )
}

#[allow(clippy::too_many_arguments)]
fn finish_lent_ok(
    cli: &Cli,
    cmd: &str,
    family: &str,
    total: u64,
    erase_scope: &str,
    skipped: bool,
    verified: Option<bool>,
    running: Option<bool>,
    warnings: Vec<Warning>,
    monitor: Option<MonitorSource>,
) -> ExitCode {
    let exit = finish(
        cli,
        cmd,
        family,
        total,
        erase_scope,
        skipped,
        verified,
        running,
        warnings,
        None,
    );
    if let Some(source) = monitor {
        let margs = crate::args::MonitorArgs {
            cmd: None,
            source,
            port: None,
            baud: 115_200,
        };
        return crate::cmd_monitor::monitor(cli, &margs);
    }
    exit
}

/// en: Soft-reset the target and make sure it is actually executing afterwards. The probe's
/// "reset and run" (`0x0b 0x01`) puts the hart back at its reset vector, but when the probe still
/// holds the halt request from attach - always the case for a standalone `reset`, which attaches
/// and immediately resets - the hart re-enters Debug Mode on reset, and DetachChip only drops the
/// request; a halted hart needs an explicit resume to leave. Two steps make that decision sound:
/// first acknowledge the reset (DMCONTROL `ackhavereset`) - on the CH32V00x Debug Module the
/// halt/running bits in DMSTATUS stay frozen at their reset-time values until the pending
/// `havereset` is acknowledged, so without the ack a running hart still reads as halted (and the
/// reverse could happen) - then read DMSTATUS and resume if halted. Measured 2026-09-16 on a
/// CH32V006 with a UART heartbeat: before, `reset` printed "running" and the UART stayed silent
/// (3/3) with DMSTATUS `0x004c0382` (halted, havereset); after, the heartbeat appears 5/5 and
/// DMSTATUS reads `0x00430c82` (allrunning). `flash` never showed the symptom because its verify
/// step halts through the DM, whose `halt` clears the request before the reset.
/// ja: soft reset 後、target が本当に走っていることを保証する。probe の「reset して実行」
/// (`0x0b 0x01`)は hart をリセットベクタへ戻すが、attach 由来の halt 要求を probe が保持したまま
/// だと(attach 直後に reset する standalone `reset` は常にこれ)hart はリセット時に Debug Mode へ
/// 再突入し、DetachChip は要求を落とすだけで、halt した hart は明示的な resume がなければ走らない。
/// 判定を確実にするために 2 段: まず reset を ack する(DMCONTROL `ackhavereset`) — CH32V00x の DM は
/// 保留中の `havereset` を ack するまで DMSTATUS の halt/running bit がリセット時の値で固着し、走って
/// いても halted と読める — 次に DMSTATUS を読み、halt なら resume。2026-09-16 CH32V006 + UART
/// heartbeat で実測: 修正前は `reset` が "running" と出しつつ UART 無音(3/3)・DMSTATUS `0x004c0382`
/// (halted, havereset)、修正後は heartbeat 5/5・DMSTATUS `0x00430c82`(allrunning)。`flash` は verify
/// で DM 経由の `halt`(reset 前に要求をクリア)を通るため症状が出なかった。
/// en: `flash --programmer loader`: program through ch32rv's own RAM loader (the OEP path) over
/// the WCH-Link's plain DMI, to check the loader and its procedure on real silicon. The family is
/// resolved from the chip id (not the family byte), as on an OEP probe.
/// ja: `flash --programmer loader`: ch32rv 自前の RAM loader(OEP の経路)で、WCH-Link の素の DMI 越し
/// に書く。loader と手順を実機で確かめるため。family は OEP と同じく chip id から引く。
fn flash_via_loader(
    cli: &Cli,
    args: &FlashArgs,
    bytes: &[u8],
    mut session: Session,
    warnings: Vec<Warning>,
) -> ExitCode {
    const CMD: &str = "flash";
    let family = crate::cmd_target::db_family_of(&mut session);
    let Some(plan) = ch32rv_flash::loader::plan_for_family(&family) else {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            format!("the device DB has no loader plan for {family}"),
            None,
        );
    };
    let bin_offset = match &args.at {
        Some(s) => match parse::u32_addr(s) {
            Ok(a) => Some(a),
            Err(m) => return fail(cli, CMD, ErrorKind::Usage, m, None),
        },
        None => None,
    };
    let image = match parse_image(bytes, args.format, &args.file, bin_offset, CODE_FLASH_START) {
        Ok(i) => i,
        Err(e) => return fail(cli, CMD, ErrorKind::Usage, e.to_string(), None),
    };
    let flash_size = session.chip.as_ref().map(|c| c.flash_bytes).unwrap_or(0);
    if flash_size > 0
        && let Err(e) = image.check_within_flash(CODE_FLASH_START, flash_size)
    {
        return fail(cli, CMD, ErrorKind::Usage, e.to_string(), None);
    }
    // Halt before the first instruction, so a running watchdog cannot reset the part mid-write.
    if let Err(e) = session.dm().reset_halt() {
        return fail(
            cli,
            CMD,
            ErrorKind::TransferFailed,
            format!("reset-halt: {e}"),
            None,
        );
    }
    let started = std::time::Instant::now();
    let result = {
        let mut t = ch32rv_dmi::DmTarget::new(session.link());
        ch32rv_flash::loader::program(&mut t, plan, &image.segments, &mut |_, _| {})
    };
    let report = match result {
        Ok(r) => r,
        Err(e) => return fail(cli, CMD, loader_error_kind(&e), e.to_string(), None),
    };
    let secs = started.elapsed().as_secs_f64();
    if args.reset == ResetPolicy::Run
        && let Err(e) = soft_reset_and_run(&mut session)
    {
        return fail(cli, CMD, ErrorKind::TransferFailed, e, None);
    }
    let total = image.total_len();
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({
            "flash": {
                "written": total,
                "programmer": "loader",
                "family": family,
                "pages": report.pages,
                "rewritten": report.rewritten,
                "restarted_runs": report.restarted_runs,
                "verify": "readback",
                "seconds": secs,
            }
        }));
        env.warnings = warnings;
        crate::print_envelope(&env)
    } else {
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        println!(
            "flashed {total} bytes to {family} with the ch32rv loader in {secs:.2} s: {} page(s), {} rewritten, {} run(s) re-issued, verified",
            report.pages, report.rewritten, report.restarted_runs
        );
        ExitCode::SUCCESS
    }
}

pub(crate) fn soft_reset_and_run(session: &mut Session) -> Result<(), String> {
    session
        .link()
        .soft_reset()
        .map_err(|e| format!("reset failed: {e}"))?;
    // Give the hart a moment to come out of reset before judging its state.
    std::thread::sleep(Duration::from_millis(20));
    let mut dm = session.dm();
    dm.ack_have_reset()
        .map_err(|e| format!("reset acknowledge failed: {e}"))?;
    match dm.is_running() {
        Ok(true) => Ok(()),
        // Halted on reset (or the DM could not tell): a resume request is what releases it.
        Ok(false) | Err(_) => dm
            .resume()
            .map_err(|e| format!("resume after reset failed: {e}")),
    }
}

/// en: confirm-run: sample whether the target is actually executing. `status` checks the
/// running bit; `pc` additionally halts, reads dpc, checks it lies in flash, and resumes.
/// ja: confirm-run。`status` は running bit を見る。`pc` はさらに halt→dpc→flash 判定→resume。
fn confirm_run(session: &mut Session, mode: ConfirmRunMode) -> bool {
    let mut dm = session.dm();
    match mode {
        ConfirmRunMode::Status => dm.is_running().unwrap_or(false),
        ConfirmRunMode::Pc => {
            if dm.halt().is_err() {
                return false;
            }
            let pc = dm.read_reg(ch32rv_dmi::RegName::Pc).ok();
            let _ = dm.resume();
            match pc {
                // Flash executes from the low alias (< 0x0002_0000, i.e. up to 128 KiB) or the
                // 0x0800_0000 window; SRAM (0x2000_0000) means it never left the reset stub.
                Some(p) => p < 0x0002_0000 || (0x0800_0000..0x0810_0000).contains(&p),
                None => false,
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn finish(
    cli: &Cli,
    cmd: &str,
    family: &str,
    total_bytes: u64,
    erase_scope: &str,
    skipped: bool,
    verified: Option<bool>,
    running: Option<bool>,
    warnings: Vec<Warning>,
    error: Option<(ErrorKind, String)>,
) -> ExitCode {
    let ok = error.is_none();
    if cli.json {
        let mut env = if let Some((kind, msg)) = &error {
            ResultEnvelope::failure(cmd, *kind, msg.clone())
        } else {
            ResultEnvelope::success(cmd)
        };
        env.result = Some(serde_json::json!({
            "bytes": total_bytes,
            "family": family,
            "skipped": skipped,
            "scope": erase_scope,
            "verified": verified,
            "running": running,
        }));
        env.warnings = warnings;
        crate::print_envelope(&env)
    } else {
        if ok {
            if skipped {
                // --preverify: the target already held the image, so nothing was erased/programmed.
                println!("preverify: target already matches - skipped");
            } else {
                println!("flashed {total_bytes} bytes to {family}");
                println!("erase:   {erase_scope}");
                if let Some(v) = verified {
                    println!(
                        "verify:  {}",
                        if v {
                            "OK (readback matches)"
                        } else {
                            "MISMATCH"
                        }
                    );
                }
            }
            if let Some(r) = running {
                println!("running: {}", if r { "yes" } else { "NO" });
            }
        }
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        if let Some((kind, msg)) = &error {
            eprintln!("ch32rv: error[{}]: {msg}", kind.as_str());
            return kind.exit_code().into();
        }
        ExitCode::SUCCESS
    }
}

pub fn erase(cli: &Cli, args: &crate::args::EraseArgs) -> ExitCode {
    const CMD: &str = "erase";
    if args.region.is_some() || args.range.is_some() {
        return erase_range(cli, args);
    }
    // --all: whole-chip erase.
    let mut session = match crate::cmd_probe::attach(cli, CMD) {
        Ok(s) => s,
        Err(c) => return c,
    };
    if let Err(why) = confirm_destructive(cli, "Erase the entire chip flash?") {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            why,
            Some("pass --yes to confirm"),
        );
    }
    if let Err(e) = session.link().erase_flash() {
        return fail(
            cli,
            CMD,
            ErrorKind::TransferFailed,
            format!("erase failed: {e}"),
            None,
        );
    }
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({ "scope": "chip", "family": session.family() }));
        crate::print_envelope(&env)
    } else {
        println!("erased entire chip flash ({})", session.family());
        ExitCode::SUCCESS
    }
}

/// en: `erase --range <a+len|a..b>` / `--region code[+off+len]`: page-granular erase via the
/// direct FLASH controller (docs/cli.ja.md §4.1). Requires page alignment (fail-closed) since
/// erase is per-page. `code` resolves to the probe-reported code-flash window.
/// ja: `erase --range/--region` を FLASH controller の page 単位消去で実装。page 境界必須。
fn erase_range(cli: &Cli, args: &crate::args::EraseArgs) -> ExitCode {
    const CMD: &str = "erase";
    let mut session = match crate::cmd_probe::attach(cli, CMD) {
        Ok(s) => s,
        Err(c) => return c,
    };
    let family = session.attach.family_byte;
    let Some(profile) = ch32rv_flash::flash_controller_profile(family) else {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            format!(
                "range/region erase is not yet supported for {} (0x{family:02x})",
                session.family()
            ),
            Some(
                "verified so far: V20x/V30x, V003/CH641, V00x, X035/CH643, L103 (CH32V103 is a follow-up)",
            ),
        );
    };
    let page = profile.page_size;

    // Resolve (start, len) from --range or --region.
    let (start, len) = if let Some(r) = &args.range {
        match parse::range(r) {
            Ok(v) => v,
            Err(m) => return fail(cli, CMD, ErrorKind::Usage, m, None),
        }
    } else if let Some(region) = &args.region {
        let flash_bytes = session.chip.as_ref().map(|c| c.flash_bytes).unwrap_or(0);
        // erase is flash-only; pass flash_bytes for the SRAM size too so a `ram` spec still resolves
        // to a non-empty range and is then caught by the flash-window check below with a clear error.
        // erase rejects non-flash regions below, so the option base is irrelevant here.
        match parse::resolve_region(region, flash_bytes, flash_bytes, None) {
            // erase operates on flash pages only, so reject a non-flash region (e.g. ram/option).
            Ok((start, _)) if !(CODE_FLASH_START..0x1000_0000).contains(&start) => {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::Usage,
                    "erase operates on the flash (code) region only",
                    Some("to erase a sub-range use --region code+<off>+<len> or --range"),
                );
            }
            Ok(v) => v,
            Err(m) => return fail(cli, CMD, ErrorKind::Usage, m, None),
        }
    } else {
        return fail(cli, CMD, ErrorKind::Usage, "no --range or --region", None);
    };

    if len == 0 {
        return fail(cli, CMD, ErrorKind::Usage, "empty range", None);
    }
    // Erase is per-page: demand page alignment so we never silently wipe neighbours.
    if start % page != 0 || len % page != 0 {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            format!("range 0x{start:08x}+0x{len:x} is not aligned to the {page}-byte flash page"),
            Some("align both the start and the length to the page size"),
        );
    }
    let pages = len / page;
    let end = start.saturating_add(len);

    if let Err(why) = confirm_destructive(
        cli,
        &format!("Erase {len} bytes ({pages} page(s)) at 0x{start:08x}..0x{end:08x}?"),
    ) {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            why,
            Some("pass --yes to confirm"),
        );
    }

    if let Err(e) = session.dm().halt() {
        return fail(
            cli,
            CMD,
            ErrorKind::AttachFailed,
            format!("halt failed: {e}"),
            None,
        );
    }
    let mode = profile.mode;
    let mut dm = session.dm();
    for i in 0..pages {
        let addr = start + i * page;
        if let Err(e) = dm.flash_page_erase(addr, mode) {
            return fail(
                cli,
                CMD,
                ErrorKind::TransferFailed,
                format!("page erase failed at 0x{addr:08x}: {e}"),
                None,
            );
        }
    }

    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({
            "scope": "range",
            "addr": format!("0x{start:08x}"),
            "len": len,
            "pages": pages,
            "page_size": page,
            "family": family,
        }));
        crate::print_envelope(&env)
    } else {
        println!(
            "erased {pages} page(s) ({len} bytes) at 0x{start:08x}..0x{end:08x} ({})",
            session.family()
        );
        ExitCode::SUCCESS
    }
}

pub fn reset(cli: &Cli, args: &crate::args::ResetArgs) -> ExitCode {
    // An OEP probe (`tcp:`, `oep://`, or a serial port no WCH-Link owns) takes the OEP path.
    match crate::oep::addr(cli, "reset") {
        Ok(Some(a)) => return crate::oep::reset(cli, args, &a),
        Ok(None) => {}
        Err(c) => return c,
    }
    const CMD: &str = "reset";
    let mut session = match crate::cmd_probe::attach(cli, CMD) {
        Ok(s) => s,
        Err(c) => return c,
    };
    if args.dm {
        // Reset the debug module only (no target reset).
        // Best-effort: DMCONTROL dmactive toggle is inside the DM layer's halt path; here we
        // just detach/re-attach which re-initializes the DM.
        let _ = session.link().detach_chip();
        let _ = session.link().attach_chip();
    } else if args.halt {
        // Reset and halt: soft reset, then halt immediately.
        if let Err(e) = session.link().soft_reset() {
            return fail(
                cli,
                CMD,
                ErrorKind::TransferFailed,
                format!("reset failed: {e}"),
                None,
            );
        }
        let mut dm = session.dm();
        if let Err(e) = dm.halt() {
            return fail(
                cli,
                CMD,
                ErrorKind::AttachFailed,
                format!("halt after reset failed: {e}"),
                None,
            );
        }
    } else if let Err(msg) = soft_reset_and_run(&mut session) {
        return fail(cli, CMD, ErrorKind::TransferFailed, msg, None);
    }

    let mut running = None;
    if let Some(mode) = args.confirm_run
        && !args.halt
        && !args.dm
    {
        std::thread::sleep(Duration::from_millis(200));
        running = Some(confirm_run(&mut session, mode));
    }

    if cli.json {
        let mode = if args.dm {
            "dm"
        } else if args.halt {
            "halt"
        } else {
            "run"
        };
        let mut env = if running == Some(false) {
            ResultEnvelope::failure(
                CMD,
                ErrorKind::NotRunningAfterWrite,
                "target not running after reset",
            )
        } else {
            ResultEnvelope::success(CMD)
        };
        env.result = Some(serde_json::json!({ "mode": mode, "running": running }));
        crate::print_envelope(&env)
    } else {
        let what = if args.dm {
            "debug module reset"
        } else if args.halt {
            "reset and halted"
        } else {
            "reset, running"
        };
        println!("{what}");
        if running == Some(false) {
            eprintln!("ch32rv: error[not-running-after-write]: target not running after reset");
            return ErrorKind::NotRunningAfterWrite.exit_code().into();
        }
        ExitCode::SUCCESS
    }
}

pub fn verify(cli: &Cli, args: &crate::args::VerifyArgs) -> ExitCode {
    const CMD: &str = "verify";
    let bytes = match std::fs::read(&args.file) {
        Ok(d) => d,
        Err(e) => {
            return fail(
                cli,
                CMD,
                ErrorKind::Usage,
                format!("read {}: {e}", args.file.display()),
                None,
            );
        }
    };
    match crate::oep::addr(cli, CMD) {
        Ok(Some(a)) => return crate::oep::verify(cli, args, &bytes, &a),
        Ok(None) => {}
        Err(c) => return c,
    }
    let bin_offset = match &args.at {
        Some(s) => match parse::u32_addr(s) {
            Ok(a) => Some(a),
            Err(m) => return fail(cli, CMD, ErrorKind::Usage, m, None),
        },
        None => None,
    };
    let mut session = match crate::cmd_probe::attach(cli, CMD) {
        Ok(s) => s,
        Err(c) => return c,
    };
    let fb = session.attach.family_byte;
    if params_for_family(fb).is_none() && ch32rv_flash::flash_controller_profile(fb).is_none() {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            "family not supported for verify",
            None,
        );
    }
    let image = match parse_image(
        &bytes,
        args.format,
        &args.file,
        bin_offset,
        CODE_FLASH_START,
    ) {
        Ok(i) => i,
        Err(e) => return fail(cli, CMD, ErrorKind::Usage, e.to_string(), None),
    };
    if let Err(e) = session.dm().halt() {
        return fail(
            cli,
            CMD,
            ErrorKind::AttachFailed,
            format!("halt failed: {e}"),
            None,
        );
    }
    for seg in &image.segments {
        // Fast bulk read via the WCH-Link; fall back to DMI word reads on error.
        let read = match session.link().read_mem(seg.addr, seg.data.len() as u32) {
            Ok(d) => Ok(d),
            Err(_) => session.dm().read_mem(seg.addr, seg.data.len() as u32),
        };
        match read {
            Ok(readback) => {
                if readback != seg.data {
                    let at = readback
                        .iter()
                        .zip(&seg.data)
                        .position(|(a, b)| a != b)
                        .unwrap_or(0);
                    if cli.json {
                        let env = ResultEnvelope::failure(
                            CMD,
                            ErrorKind::VerifyMismatch,
                            format!("mismatch at {:#010x}", seg.addr as usize + at),
                        );
                        return crate::print_envelope(&env);
                    }
                    eprintln!("verify: MISMATCH at {:#010x}", seg.addr as usize + at);
                    return ErrorKind::VerifyMismatch.exit_code().into();
                }
            }
            Err(e) => {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::TransferFailed,
                    format!("readback failed: {e}"),
                    None,
                );
            }
        }
    }
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({ "bytes": image.total_len(), "verified": true }));
        crate::print_envelope(&env)
    } else {
        println!("verify: OK ({} bytes match)", image.total_len());
        ExitCode::SUCCESS
    }
}

pub fn recover(cli: &Cli, args: &RecoverArgs) -> ExitCode {
    match args.method {
        None => crate::cmd_recover::diagnose_only(cli),
        Some(RecoverMethod::Auto) => crate::cmd_recover::auto(cli),
        Some(m @ (RecoverMethod::PowerOff | RecoverMethod::Nrst)) => recover_special_erase(cli, m),
        Some(RecoverMethod::Unprotect) => recover_unprotect(cli),
        Some(RecoverMethod::Unbrick) => recover_unbrick(cli),
    }
}

/// en: `recover --method unprotect`: clear read protection by writing factory-default option bytes
/// (RDPR=0xA5). On a read-protected target this triggers the chip's mass erase, unbricking it. The
/// target must still attach over DMI (a fully-dead target needs power-off/nrst/unbrick instead).
/// ja: `recover --method unprotect`: 工場 option bytes(RDPR=0xA5)を書いて読み出し保護を解除。保護
/// 済み target ではこれが chip の mass erase を誘発して復旧する。attach は要る(完全死は power-off 等)。
pub(crate) fn recover_unprotect(cli: &Cli) -> ExitCode {
    const CMD: &str = "recover";
    if let Err(why) = confirm_destructive(
        cli,
        "Remove read protection? This ERASES ALL FLASH on a protected target.",
    ) {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            why,
            Some("pass --yes to confirm"),
        );
    }
    let mut session = match crate::cmd_probe::attach(cli, CMD) {
        Ok(s) => s,
        Err(c) => return c,
    };
    let family = session.family();
    // The option block is not at the same address on every part (CH32M030: 0x1FFF_F300), so take it
    // from the device DB rather than assuming - writing factory bytes to the wrong address would
    // program arbitrary memory.
    let db_family = crate::cmd_target::db_family_of(&mut session);
    let option_base = match crate::cmd_target::option_base(&db_family) {
        Ok(b) => b,
        Err(msg) => return fail(cli, CMD, ErrorKind::CapabilityUnsupported, msg, None),
    };
    let mut dm = session.dm();
    if let Err(e) = dm.halt() {
        return fail(
            cli,
            CMD,
            ErrorKind::AttachFailed,
            format!("halt failed: {e}"),
            None,
        );
    }
    // Clear read protection without touching anything else the part carries: read the current
    // bytes and replace only RDPR. A blanket USER=0xff would repartition SRAM on V20x/V307
    // (`RAM_CODE_MOD`) and change the NRST pin function on V003 (`RST_MODE`) - neither is part of
    // "remove read protection". A protected part may not hand its option bytes back, so fall back
    // to the blanket image and say so.
    let (image, preserved) = match dm.read_mem(option_base, 16) {
        Ok(v) if v.len() == 16 => {
            let mut cur = [0u8; 16];
            cur.copy_from_slice(&v);
            if crate::cmd_target::option_bytes_plausible(&cur) {
                (crate::cmd_target::unprotect_image(&cur), true)
            } else {
                (crate::cmd_target::BLANKET_FACTORY, false)
            }
        }
        _ => (crate::cmd_target::BLANKET_FACTORY, false),
    };
    if !preserved {
        eprintln!(
            "warning[option-defaults]: the target's current option bytes could not be read back, so family-specific USER bits (SRAM split, NRST mode) are set to 0xff rather than preserved"
        );
    }
    if let Err(e) = dm.flash_program_option_bytes(option_base, &image) {
        return fail(
            cli,
            CMD,
            ErrorKind::TransferFailed,
            format!("writing option bytes failed: {e}"),
            None,
        );
    }
    // Apply the option change with a system reset.
    let _ = session.link().soft_reset();
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({
            "method": "unprotect", "family": family, "preserved_user_bits": preserved, "note": "read protection cleared (RDPR=0xA5); applies after reset",
        }));
        crate::print_envelope(&env)
    } else {
        println!("recover unprotect: read protection cleared (RDPR=0xA5) on {family}");
        println!("note: a protected target is mass-erased; re-flash your firmware");
        ExitCode::SUCCESS
    }
}

/// en: `recover --method unbrick`: attach-based escalation. Attaches the target, then clears
/// whatever keeps it from a normal flash - read protection (write factory option bytes, which
/// triggers the chip's mass erase) if set, otherwise a whole-chip erase - and applies it with a
/// reset. A target that cannot attach at all (its app repurposed SWDIO/SWCLK) is beyond this:
/// point the user at the no-attach `--method power-off --chip <family>` instead.
/// ja: `recover --method unbrick`: attach ベースのエスカレーション復旧。attach して、通常 flash を
/// 妨げているもの(保護 ON なら工場 option bytes 書込=mass erase、そうでなければ chip erase)を
/// クリアし reset で反映。全く attach できない target(app が SWD ピンを転用)は対象外で、非 attach の
/// `--method power-off --chip <family>` を案内する。
fn recover_unbrick(cli: &Cli) -> ExitCode {
    const CMD: &str = "recover";
    if let Err(why) = confirm_destructive(
        cli,
        "Unbrick this target? This ERASES ALL FLASH (and clears read protection if set).",
    ) {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            why,
            Some("pass --yes to confirm"),
        );
    }
    // Quiet attach: on failure give the tailored "use power-off" hint rather than a generic error.
    let entry = match select_entry(cli, CMD) {
        Ok(e) => e,
        Err(c) => return c,
    };
    if entry.mode != ch32rv_contract::ProbeMode::Riscv {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            format!(
                "probe is in {} mode; this needs RISC-V mode",
                mode_str(entry.mode)
            ),
            None,
        );
    }
    let (speed, mut warnings) = match parse::speed(&cli.speed) {
        Ok(v) => v,
        Err(m) => return fail(cli, CMD, ErrorKind::Usage, m, None),
    };
    let timeout = Duration::from_millis(cli.timeout.map(|s| s * 1000).unwrap_or(3000));
    let mut session = match Session::attach(
        &entry,
        speed,
        timeout,
        Duration::from_secs(cli.lock_timeout),
        cli.chip.as_deref(),
        cli.db.as_deref(),
        &mut warnings,
    ) {
        Ok(s) => s,
        Err(_) => {
            return fail(
                cli,
                CMD,
                ErrorKind::AttachFailed,
                "unbrick needs the target to attach over DMI, but attach failed",
                Some(
                    "if the app repurposed SWDIO/SWCLK, use: recover --method power-off --chip <family>",
                ),
            );
        }
    };
    let family = session.family();
    // Per-family option-byte block base from the device DB (not universal: CH32M030 uses
    // 0x1FFF_F300), used for both the RDPR probe and the factory write below.
    let db_family = crate::cmd_target::db_family_of(&mut session);
    let option_base = match crate::cmd_target::option_base(&db_family) {
        Ok(b) => b,
        Err(msg) => return fail(cli, CMD, ErrorKind::CapabilityUnsupported, msg, None),
    };

    // Decide and apply under a halted hart: read protection off -> chip erase; on -> factory
    // option bytes (mass erase). Scope the DM borrow so we can reach the probe afterwards.
    let protected;
    {
        let mut dm = session.dm();
        if let Err(e) = dm.halt() {
            return fail(
                cli,
                CMD,
                ErrorKind::AttachFailed,
                format!("halt failed: {e}"),
                None,
            );
        }
        // Option byte 0 (RDPR) at the family's option base; 0xA5 = read protection disabled.
        protected = match dm.read_mem(option_base, 1) {
            Ok(b) => b.first().copied() != Some(0xA5),
            Err(_) => false,
        };
        // Same reasoning as `--method unprotect`: keep every USER bit the part carries.
        let image = match dm.read_mem(option_base, 16) {
            Ok(v) if v.len() == 16 => {
                let mut cur = [0u8; 16];
                cur.copy_from_slice(&v);
                if crate::cmd_target::option_bytes_plausible(&cur) {
                    crate::cmd_target::unprotect_image(&cur)
                } else {
                    crate::cmd_target::BLANKET_FACTORY
                }
            }
            _ => crate::cmd_target::BLANKET_FACTORY,
        };
        if protected && let Err(e) = dm.flash_program_option_bytes(option_base, &image) {
            return fail(
                cli,
                CMD,
                ErrorKind::TransferFailed,
                format!("clearing read protection failed: {e}"),
                None,
            );
        }
    }
    let action = if protected {
        "read protection cleared (RDPR=0xA5, mass erase)"
    } else {
        if let Err(e) = session.link().erase_flash() {
            return fail(
                cli,
                CMD,
                ErrorKind::TransferFailed,
                format!("chip erase failed: {e}"),
                None,
            );
        }
        "whole-chip erase"
    };
    // Apply (a protection change needs a system reset; a plain erase just re-runs blank flash).
    let _ = session.link().soft_reset();

    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({
            "method": "unbrick", "family": family, "protected": protected, "action": action,
        }));
        crate::print_envelope(&env)
    } else {
        println!("recover unbrick: {action} on {family}");
        println!("note: flash is now blank; re-flash your firmware");
        ExitCode::SUCCESS
    }
}

/// en: "Clear All Code Flash - By Power off / RST pin". Does NOT attach the target first
/// (the point is to recover a target you cannot attach). Needs `--chip` to know the family
/// byte, since we cannot read it without attaching.
/// ja: 「Clear All Code Flash」。attach しない(attach できない target の復旧が目的)。
/// family byte を読めないため `--chip` が要る。
pub(crate) fn recover_special_erase(cli: &Cli, method: RecoverMethod) -> ExitCode {
    const CMD: &str = "recover";
    let Some(chip) = cli.chip.as_deref() else {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            "special erase needs --chip <family> (the target cannot be probed for it)",
            Some("e.g. --chip CH32V203 or the family name; see `ch32rv db list`"),
        );
    };
    let Some(family_byte) = family_byte_from_name(chip) else {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            format!("unknown --chip `{chip}` for special erase (family not recognized)"),
            None,
        );
    };
    if params_for_family(family_byte).is_none_or(|p| !p.supports_special_erase) {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            format!("family `{chip}` does not support special (power-off/RST) erase"),
            None,
        );
    }

    let entry = match select_entry(cli, CMD) {
        Ok(e) => e,
        Err(c) => return c,
    };
    // Only LinkE/LinkW implement the "power-off" special erase.
    let mut link = match ch32rv_wchlink::WchLink::open(&entry.dev) {
        Ok(l) => l,
        Err(e) => return fail(cli, CMD, ErrorKind::DeviceOpenFailed, e.to_string(), None),
    };
    link.set_timeout(Duration::from_millis(
        cli.timeout.map(|s| s * 1000).unwrap_or(5000),
    ));

    let variant = link.probe_info().ok().map(|i| i.variant);
    let power_capable = matches!(
        variant,
        Some(ch32rv_wchlink::Variant::LinkE) | Some(ch32rv_wchlink::Variant::LinkW)
    );
    if method == RecoverMethod::PowerOff && !power_capable {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            "only WCH-LinkE / LinkW implement the power-off special erase",
            Some("use --method nrst with the RST pin wired, or a LinkE/LinkW probe"),
        );
    }

    // en: The probe answers `0x0f` when the erase took and `0x00` when it did not: on a CH32X035
    // the first attempt after the target stopped answering has come back `0x00` (~2.1 s) with the
    // flash untouched, and the second `0x0f` (~0.2 s) with it erased (wch-protocols E162 / E164;
    // E165 got `0x0f` first time). A `0x00` is an attempt that did not get the halt; in the stopped
    // state a reset without a power loss follows and the next attempt erases (E168) - so repeat
    // on `0x00`. Other families' answers are not recorded, so a run that never sees `0x0f` is
    // reported as unconfirmed rather than failed.
    // ja: probe は消えたら `0x0f`、消えていなければ `0x00` を返す(X035 で 1 回目が `00`、2 回目
    // `0f`。E162 / E164)。`00` なら繰り返す。他 family の応答は未記録なので、`0f` が一度も来なくても
    // 失敗ではなく「未確認」として報告する。
    const ATTEMPTS: usize = 3;
    let mut answers: Vec<u8> = Vec::new();
    for _ in 0..ATTEMPTS {
        let res = match method {
            RecoverMethod::PowerOff => link.erase_code_flash_by_power_off(family_byte),
            RecoverMethod::Nrst => link.erase_code_flash_by_rst(family_byte),
            _ => unreachable!(),
        };
        match res {
            Ok(b) => {
                answers.push(b);
                if b != 0x00 {
                    break;
                }
            }
            Err(e) => {
                return fail(
                    cli,
                    CMD,
                    ErrorKind::TransferFailed,
                    format!("special erase failed: {e}"),
                    None,
                );
            }
        }
    }
    let confirmed = answers.last() == Some(&0x0f);
    let answers_hex: Vec<String> = answers.iter().map(|b| format!("0x{b:02x}")).collect();

    // en: The special erase leaves the probe holding a stale (corrupted) readback of the target;
    // clear it so a follow-up attach/read is clean (board-identify's re-detect recovery).
    // ja: 特殊消去の後は probe が壊れ読み値を保持するため、redetect でクリアして次の attach を綺麗にする。
    let _ = link.redetect_chip();
    let _ = link.detach_chip();

    let mut warnings = Vec::new();
    if !confirmed {
        warnings.push(Warning {
            code: "special-erase-unconfirmed".to_owned(),
            msg: format!(
                "the probe did not confirm the erase (answers: {}; 0x0f is the confirmation seen on CH32X035): check with `ch32rv read --blank-check`",
                answers_hex.join(" ")
            ),
        });
    }
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.warnings = warnings;
        env.result = Some(serde_json::json!({
            "method": method.as_str(), "family": chip, "attempts": answers.len(),
            "answers": answers_hex, "confirmed": confirmed,
        }));
        crate::print_envelope(&env)
    } else {
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        println!(
            "special erase ({}) issued for {chip}: {} attempt(s), probe answered {}",
            method.as_str(),
            answers.len(),
            answers_hex.join(" ")
        );
        if confirmed {
            println!("the target code flash is cleared; re-flash normally now");
        } else {
            println!(
                "the erase is not confirmed; check with `ch32rv read --blank-check` before re-flashing"
            );
        }
        ExitCode::SUCCESS
    }
}

/// en: Map a --chip name to its AttachChip family byte (interim; the DB will replace this).
/// ja: --chip 名を AttachChip family byte へ(暫定。将来は DB)。
pub(crate) fn family_byte_from_name(name: &str) -> Option<u8> {
    let n = name.to_ascii_uppercase();
    let n = n.strip_prefix("CH32").unwrap_or(&n);
    Some(match n {
        s if s.starts_with("V103") => 0x01,
        s if s.starts_with("V20") || s.starts_with("V205") => 0x05,
        s if s.starts_with("V30") || s.starts_with("V317") => 0x06,
        s if s.starts_with("V003") => 0x09,
        s if s.starts_with("V00") => 0x4E,
        s if s.starts_with("X03") || s.starts_with("X035") => 0x0D,
        s if s.starts_with("L103") => 0x0E,
        s if s.starts_with("643") || s.starts_with("CH643") => 0x0C,
        s if s.starts_with("641") || s.starts_with("CH641") => 0x49,
        s if s.starts_with("H4") => 0xC6,
        _ => return None,
    })
}

/// en: The error kind of a RAM-loader failure: only a page that still differs after rewriting is
/// a verify mismatch; the probe or its transport failing is a transfer failure (a broker that went
/// away is not a corrupted write), a protect error is the target's protection.
/// ja: RAM loader の失敗の種別。書き直しても違う page だけが verify-mismatch。probe や transport の
/// 失敗は transfer の失敗(ブローカーが消えたのは書き込みの破損ではない)、書き込み保護は target の保護。
pub(crate) fn loader_error_kind(e: &ch32rv_flash::loader::LoaderError) -> ErrorKind {
    use ch32rv_flash::loader::LoaderError as L;
    match e {
        L::Verify { .. } => ErrorKind::VerifyMismatch,
        L::WriteProtected { .. } | L::StillLocked(_) => ErrorKind::TargetProtected,
        L::Probe(d) => crate::source::dmi_error_kind(d),
        _ => ErrorKind::TransferFailed,
    }
}

#[cfg(test)]
mod tests {
    use super::{Segment, covered_pages, overlay_page, resolve_erase};
    use ch32rv_contract::policy::EraseMode;

    const BASE: u32 = 0x0800_0000;

    #[test]
    fn auto_full_image_is_chip() {
        // An image loaded from the flash base is a full program -> the one fast whole-chip erase.
        assert_eq!(
            resolve_erase(EraseMode::Auto, Some(BASE), BASE, false),
            EraseMode::Chip
        );
    }

    #[test]
    fn auto_partial_image_is_sector() {
        // An image at an offset must not wipe flash below it.
        assert_eq!(
            resolve_erase(EraseMode::Auto, Some(BASE + 0x8000), BASE, false),
            EraseMode::Sector
        );
    }

    #[test]
    fn auto_with_restore_unwritten_is_sector_even_from_base() {
        // restore-unwritten needs page-granular erase, so it overrides the full-image chip choice.
        assert_eq!(
            resolve_erase(EraseMode::Auto, Some(BASE), BASE, true),
            EraseMode::Sector
        );
    }

    #[test]
    fn explicit_modes_pass_through() {
        for m in [EraseMode::Chip, EraseMode::Sector, EraseMode::None] {
            assert_eq!(resolve_erase(m, Some(BASE), BASE, false), m);
            assert_eq!(resolve_erase(m, Some(BASE + 0x100), BASE, true), m);
        }
    }

    // en: The pages a sector erase must clear for a given image layout.
    fn pages(segs: &[(u32, u32)], page: u32) -> Vec<u32> {
        covered_pages(segs.iter().copied(), page)
            .into_iter()
            .collect()
    }

    fn seg(addr: u32, data: &[u8]) -> Segment {
        Segment {
            addr,
            data: data.to_vec(),
        }
    }

    #[test]
    fn single_aligned_segment_one_page() {
        // A 256-byte segment exactly on a page boundary touches exactly one 256-byte page.
        assert_eq!(pages(&[(0x0800_ff00, 256)], 256), vec![0x0800_ff00]);
    }

    #[test]
    fn segment_spanning_two_pages() {
        // 260 bytes at a page start spills 4 bytes into the next page -> two pages.
        assert_eq!(
            pages(&[(0x0800_0000, 260)], 256),
            vec![0x0800_0000, 0x0800_0100]
        );
    }

    #[test]
    fn unaligned_start_pulls_in_whole_first_page() {
        // Starting mid-page erases from that page's base, not the segment's address.
        assert_eq!(
            pages(&[(0x0800_0080, 256)], 256),
            vec![0x0800_0000, 0x0800_0100]
        );
    }

    #[test]
    fn segments_sharing_a_page_collapse() {
        // Two segments in the same page must not produce a duplicate erase of that page.
        assert_eq!(
            pages(&[(0x0800_0000, 16), (0x0800_0040, 16)], 256),
            vec![0x0800_0000]
        );
    }

    #[test]
    fn full_image_covers_every_page() {
        // A 1 KiB image at the code base covers four 256-byte pages, contiguous and sorted.
        assert_eq!(
            pages(&[(0x0800_0000, 1024)], 256),
            vec![0x0800_0000, 0x0800_0100, 0x0800_0200, 0x0800_0300]
        );
    }

    #[test]
    fn honours_a_128_byte_page_size() {
        // V103 uses 128-byte pages; a 256-byte segment then spans two pages.
        assert_eq!(
            pages(&[(0x0800_0000, 256)], 128),
            vec![0x0800_0000, 0x0800_0080]
        );
    }

    // --- overlay_page (restore-unwritten merge) ---

    #[test]
    fn overlay_writes_only_the_segment_span() {
        // A page pre-read as all-0xff, image writes 4 bytes at the start -> rest stays 0xff.
        let mut page = vec![0xff_u8; 8];
        overlay_page(0x0800_0000, &mut page, &[seg(0x0800_0000, &[1, 2, 3, 4])]);
        assert_eq!(page, [1, 2, 3, 4, 0xff, 0xff, 0xff, 0xff]);
    }

    #[test]
    fn overlay_preserves_pre_read_bytes_outside_the_image() {
        // The unwritten-byte-preservation case: original content survives where the image is absent.
        let mut page = vec![0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7];
        overlay_page(0x0800_0000, &mut page, &[seg(0x0800_0002, &[0xBB, 0xCC])]);
        assert_eq!(page, [0xA0, 0xA1, 0xBB, 0xCC, 0xA4, 0xA5, 0xA6, 0xA7]);
    }

    #[test]
    fn overlay_clips_a_segment_to_the_page() {
        // A segment that starts before and ends after the page only writes the in-page slice.
        // page covers [0x100, 0x108); segment covers [0x0FE, 0x106) -> writes page[0..6].
        let mut page = vec![0u8; 8];
        overlay_page(
            0x0800_0100,
            &mut page,
            &[seg(0x0800_00fe, &[10, 11, 12, 13, 14, 15, 16, 17])],
        );
        // segment bytes at offsets 2..8 land in the page (0x100-0x0FE = 2).
        assert_eq!(page, [12, 13, 14, 15, 16, 17, 0, 0]);
    }

    #[test]
    fn overlay_ignores_a_segment_in_another_page() {
        // A segment entirely outside the page leaves it untouched.
        let mut page = vec![0x55_u8; 4];
        overlay_page(0x0800_0000, &mut page, &[seg(0x0800_1000, &[1, 2, 3, 4])]);
        assert_eq!(page, [0x55, 0x55, 0x55, 0x55]);
    }
}