euv-cli 0.50.0

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

/// Parses a user-supplied Android ABI string into an `AndroidAbi` discriminant.
///
/// # Arguments
///
/// - `&str` - Raw ABI label such as `arm64-v8a`, `arm64`, `armeabi-v7a`, or `x86_64`.
///
/// # Returns
///
/// - `io::Result<AndroidAbi>` - Parsed ABI or an `InvalidInput` error.
pub fn parse_android_abi(raw: &str) -> io::Result<AndroidAbi> {
    let normalized: String = raw.trim().to_ascii_lowercase();
    if normalized == ANDROID_ABI_ARM64
        || normalized == ANDROID_ABI_ALIAS_ARM64
        || normalized == ANDROID_ABI_ALIAS_AARCH64
        || normalized == ANDROID_TRIPLE_ARM64
    {
        return Ok(AndroidAbi::Arm64V8a);
    }
    if normalized == ANDROID_ABI_ARMV7
        || normalized == ANDROID_ABI_ALIAS_ARMV7
        || normalized == ANDROID_TRIPLE_ARMV7
    {
        return Ok(AndroidAbi::ArmeabiV7a);
    }
    if normalized == ANDROID_ABI_X86_64
        || normalized == ANDROID_ABI_ALIAS_AMD64
        || normalized == ANDROID_TRIPLE_X86_64
    {
        return Ok(AndroidAbi::X86_64);
    }
    Err(Error::new(
        ErrorKind::InvalidInput,
        format!("unsupported Android ABI '{raw}'"),
    ))
}

/// Resolves the dynamic workspace semver from the workspace manifest.
///
/// # Arguments
///
/// - `&Path` - Root directory of the `euv` workspace or package.
///
/// # Returns
///
/// - `String` - Parsed semantic version string, falling back to `0.1.0` when unavailable.
#[must_use]
pub fn resolve_workspace_semver(workspace_root: &Path) -> String {
    let manifest_path: PathBuf = workspace_root.join(MOBILE_FILE_CARGO_TOML);
    let Ok(manifest_text) = fs::read_to_string(&manifest_path) else {
        return MOBILE_FALLBACK_VERSION.to_string();
    };
    if let Some(found) = extract_toml_section_version(&manifest_text, TOML_SECTION_WORKSPACE_PKG) {
        return found;
    }
    if let Some(found) = extract_toml_section_version(&manifest_text, TOML_SECTION_PKG) {
        return found;
    }
    MOBILE_FALLBACK_VERSION.to_string()
}

/// Extracts `version = "..."` from a named TOML table section.
///
/// # Arguments
///
/// - `&str` - Full TOML manifest contents.
/// - `&str` - Exact table header such as `[workspace.package]`.
///
/// # Returns
///
/// - `Option<String>` - Trimmed version string when found inside the target section.
fn extract_toml_section_version(manifest_text: &str, section_header: &str) -> Option<String> {
    let mut in_section: bool = false;
    for raw_line in manifest_text.lines() {
        let trimmed: &str = raw_line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            in_section = trimmed == section_header;
            continue;
        }
        if !in_section {
            continue;
        }
        if let Some((key_raw, val_raw)) = trimmed.split_once('=')
            && key_raw.trim() == TOML_VERSION_KEY
        {
            let cleaned: &str = val_raw.trim().trim_matches('"');
            if !cleaned.is_empty() {
                return Some(cleaned.to_string());
            }
        }
    }
    None
}

/// Computes a deterministic monotonic numeric version code (`major * 10000 + minor * 100 + patch`).
///
/// # Arguments
///
/// - `&str` - Semantic version string such as `"0.49.4"`.
///
/// # Returns
///
/// - `u32` - Positive version code (`>= 1`).
#[must_use]
pub fn compute_semver_version_code(version: &str) -> u32 {
    let core_part: &str = version.split('-').next().unwrap_or(version);
    let mut segments: Vec<u32> = Vec::new();
    for token in core_part.split('.') {
        let parsed: u32 = token.trim().parse::<u32>().unwrap_or(0);
        segments.push(parsed);
    }
    let major: u32 = segments.first().copied().unwrap_or(0);
    let minor: u32 = segments.get(1).copied().unwrap_or(0);
    let patch: u32 = segments.get(2).copied().unwrap_or(0);
    let computed: u32 = major
        .saturating_mul(10_000)
        .saturating_add(minor.saturating_mul(100))
        .saturating_add(patch);
    computed.max(1)
}

/// Maps a CLI `RenderArg` variant to its generated Rust `RenderMode` expression.
///
/// # Arguments
///
/// - `RenderArg` - CLI render mode selector.
///
/// # Returns
///
/// - `&'static str` - Rust expression string written into `host_config.rs`.
#[must_use]
pub fn render_mode_const_expr(render_mode: RenderArg) -> &'static str {
    match render_mode {
        RenderArg::Hardware => HOST_RENDER_EXPR_HARDWARE,
        RenderArg::Hybrid => HOST_RENDER_EXPR_HYBRID,
        RenderArg::Software => HOST_RENDER_EXPR_SOFTWARE,
        RenderArg::Auto => HOST_RENDER_EXPR_AUTO,
    }
}

/// Counts occurrences of dev-only `euv.ai.schema.v1` and `euv.ai.schema.v2` markers in binary bytes.
///
/// # Arguments
///
/// - `&[u8]` - Raw compiled binary or library byte slice.
///
/// # Returns
///
/// - `usize` - Total number of matching dev-only AI schema byte sequences.
#[must_use]
pub fn count_ai_schema_markers(bytes: &[u8]) -> usize {
    let v1_hits: usize = count_subslice_occurrences(bytes, MOBILE_AI_SCHEMA_V1_MARKER);
    let v2_hits: usize = count_subslice_occurrences(bytes, MOBILE_AI_SCHEMA_V2_MARKER);
    v1_hits + v2_hits
}

/// Counts non-overlapping occurrences of `needle` inside `haystack`.
///
/// # Arguments
///
/// - `&[u8]` - Input byte buffer to search.
/// - `&[u8]` - Target byte pattern.
///
/// # Returns
///
/// - `usize` - Number of occurrences found.
fn count_subslice_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
    if needle.is_empty() || haystack.len() < needle.len() {
        return 0;
    }
    let mut matches: usize = 0;
    let mut offset: usize = 0;
    let limit: usize = haystack.len() - needle.len();
    while offset <= limit {
        if &haystack[offset..offset + needle.len()] == needle {
            matches += 1;
            offset += needle.len();
        } else {
            offset += 1;
        }
    }
    matches
}

/// Verifies that a compiled release binary contains zero dev-only AI schema markers.
///
/// # Arguments
///
/// - `&Path` - Path to the compiled release `.so`, `.wasm`, or executable binary.
///
/// # Returns
///
/// - `io::Result<()>` - `Ok(())` when clean, or an error describing the leak count.
pub fn assert_release_binary_ai_schema_clean(binary_path: &Path) -> io::Result<()> {
    let raw_bytes: Vec<u8> = fs::read(binary_path)?;
    let leak_count: usize = count_ai_schema_markers(&raw_bytes);
    if leak_count != 0 {
        return Err(Error::other(format!(
            "release binary {} leaked {leak_count} dev-only AI schema marker(s)",
            binary_path.display()
        )));
    }
    Ok(())
}

/// Writes an icon PNG via the supplied callback or emits the embedded 1x1 transparent PNG fallback.
///
/// # Arguments
///
/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
/// - `&Path` - Destination PNG file path.
/// - `u32` - Requested square pixel dimension.
///
/// # Returns
///
/// - `io::Result<()>` - Write outcome.
pub fn write_icon_or_fallback(
    icon_writer: Option<&MobileIconWriter<'_>>,
    output_path: &Path,
    size_px: u32,
) -> io::Result<()> {
    if let Some(parent_dir) = output_path.parent() {
        fs::create_dir_all(parent_dir)?;
    }
    if let Some(writer) = icon_writer {
        return writer(output_path, size_px);
    }
    fs::write(output_path, MOBILE_FALLBACK_ICON_PNG_BYTES)
}

/// Resolves the Android NDK prebuilt LLVM host directory tag for a given host OS name.
///
/// # Arguments
///
/// - `&str` - Host operating system identifier (`consts::OS`, e.g. `"macos"`, `"linux"`, `"windows"`).
///
/// # Returns
///
/// - `&'static str` - Prebuilt LLVM host tag (`darwin-x86_64`, `linux-x86_64`, or `windows-x86_64`).
#[must_use]
pub fn resolve_android_ndk_host_tag(host_os: &str) -> &'static str {
    if host_os == MOBILE_HOST_OS_MACOS {
        return ANDROID_NDK_HOST_TAG_MACOS;
    }
    if host_os == MOBILE_HOST_OS_WINDOWS {
        return ANDROID_NDK_HOST_TAG_WINDOWS;
    }
    ANDROID_NDK_HOST_TAG_LINUX
}

/// Resolves the exact Android NDK clang linker executable for `abi` and `api_level`.
///
/// # Arguments
///
/// - `&Path` - Path to `<ndk>/toolchains/llvm/prebuilt/<host_tag>/bin`.
/// - `AndroidAbi` - Target Android CPU ABI.
/// - `&str` - Preferred Android API level string such as `"35"`.
///
/// # Returns
///
/// - `io::Result<PathBuf>` - Resolved executable path or `NotFound` error.
pub fn resolve_android_ndk_linker(
    ndk_llvm_bin: &Path,
    abi: AndroidAbi,
    api_level: &str,
) -> io::Result<PathBuf> {
    let prefix: &str = abi.clang_prefix();
    let exact_base: String = format!("{prefix}{api_level}{CLANG_SUFFIX}");
    if let Some(found) = find_host_executable(ndk_llvm_bin, &exact_base) {
        return Ok(found);
    }
    let mut candidates: Vec<(Vec<u64>, String, PathBuf)> = Vec::new();
    if let Ok(entries) = fs::read_dir(ndk_llvm_bin) {
        for entry_res in entries {
            let Ok(entry) = entry_res else {
                continue;
            };
            let entry_path: PathBuf = entry.path();
            if !entry_path.is_file() {
                continue;
            }
            let Some(file_name) = entry_path.file_name().and_then(OsStr::to_str) else {
                continue;
            };
            let stripped: &str = strip_windows_script_ext(file_name);
            if !stripped.starts_with(prefix) || !stripped.ends_with(CLANG_SUFFIX) {
                continue;
            }
            let api_slice: &str =
                &stripped[prefix.len()..stripped.len().saturating_sub(CLANG_SUFFIX.len())];
            if api_slice.is_empty()
                || !api_slice
                    .chars()
                    .all(|digit_char: char| digit_char.is_ascii_digit())
            {
                continue;
            }
            let version_key: Vec<u64> = parse_version_sort_key(api_slice);
            candidates.push((version_key, file_name.to_string(), entry_path));
        }
    }
    candidates.sort_by(
        |left: &(Vec<u64>, String, PathBuf), right: &(Vec<u64>, String, PathBuf)| {
            left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))
        },
    );
    if let Some((_, best_name, best_path)) = candidates.pop() {
        let stripped: &str = strip_windows_script_ext(&best_name);
        if let Some(preferred) = find_host_executable(ndk_llvm_bin, stripped) {
            return Ok(preferred);
        }
        return Ok(best_path);
    }
    Err(Error::new(
        ErrorKind::NotFound,
        format!(
            "Android NDK clang linker for {} not found in {}",
            abi.rust_triple(),
            ndk_llvm_bin.display()
        ),
    ))
}

/// Detects the Android SDK, NDK, and build-tools executables from environment variables and standard paths.
///
/// # Arguments
///
/// - `Option<&str>` - Optional Android API level override (defaults to `ANDROID_API_LEVEL` or `"35"`).
/// - `Option<&str>` - Optional build-tools version override (defaults to `ANDROID_BUILD_TOOLS` or `"35.0.0"`).
///
/// # Returns
///
/// - `io::Result<AndroidToolchain>` - Populated toolchain paths or a diagnostic `NotFound` error.
pub fn detect_android_toolchain(
    api_level: Option<&str>,
    build_tools: Option<&str>,
) -> io::Result<AndroidToolchain> {
    let sdk_root: PathBuf = resolve_android_sdk_root()?;
    let resolved_api: String = api_level
        .map(str::to_string)
        .or_else(|| env::var(ENV_ANDROID_API_LEVEL).ok())
        .filter(|val: &String| !val.trim().is_empty())
        .unwrap_or_else(|| ANDROID_DEFAULT_API_LEVEL.to_string());
    let resolved_bt: String = build_tools
        .map(str::to_string)
        .or_else(|| env::var(ENV_ANDROID_BUILD_TOOLS).ok())
        .filter(|val: &String| !val.trim().is_empty())
        .unwrap_or_else(|| ANDROID_DEFAULT_BUILD_TOOLS.to_string());
    let ndk_root: PathBuf = resolve_android_ndk_root(&sdk_root)?;
    let host_tag: String = resolve_android_ndk_host_tag(consts::OS).to_string();
    let ndk_llvm_bin: PathBuf = ndk_root
        .join(ANDROID_NDK_PREBUILT_REL)
        .join(&host_tag)
        .join(MOBILE_DIR_BIN);
    if !ndk_llvm_bin.is_dir() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!(
                "Android NDK LLVM bin directory not found at {}",
                ndk_llvm_bin.display()
            ),
        ));
    }
    let android_jar: PathBuf = sdk_root
        .join(ANDROID_PLATFORMS_DIR)
        .join(format!("android-{resolved_api}"))
        .join(FILE_ANDROID_JAR);
    if !android_jar.is_file() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!("Android platform jar missing: {}", android_jar.display()),
        ));
    }
    let bt_dir: PathBuf = sdk_root.join(ANDROID_BUILD_TOOLS_DIR).join(&resolved_bt);
    let aapt2_bin: PathBuf = require_host_executable(&bt_dir, TOOL_AAPT2)?;
    let d8_bin: PathBuf = require_host_executable(&bt_dir, TOOL_D8)?;
    let zipalign_bin: PathBuf = require_host_executable(&bt_dir, TOOL_ZIPALIGN)?;
    let apksigner_bin: PathBuf = require_host_executable(&bt_dir, TOOL_APKSIGNER)?;
    let adb_dir: PathBuf = sdk_root.join(ANDROID_PLATFORM_TOOLS_DIR);
    let adb_bin: PathBuf =
        find_host_executable(&adb_dir, TOOL_ADB).unwrap_or_else(|| adb_dir.join(TOOL_ADB));
    let emu_dir: PathBuf = sdk_root.join(ANDROID_EMULATOR_DIR);
    let emulator_bin: PathBuf = find_host_executable(&emu_dir, TOOL_EMULATOR)
        .unwrap_or_else(|| emu_dir.join(TOOL_EMULATOR));
    Ok(AndroidToolchain {
        sdk_root,
        ndk_root,
        api_level: resolved_api,
        build_tools: resolved_bt,
        host_tag,
        ndk_llvm_bin,
        android_jar,
        aapt2_bin,
        d8_bin,
        zipalign_bin,
        apksigner_bin,
        adb_bin,
        emulator_bin,
    })
}

/// Renders the complete `AndroidManifest.xml` for an Android phone or Wear OS build.
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Android build configuration specifying package, label, and target kind.
/// - `&str` - Resolved semantic version name.
/// - `u32` - Resolved numeric version code.
///
/// # Returns
///
/// - `String` - Complete UTF-8 `AndroidManifest.xml` text.
#[must_use]
pub fn render_android_manifest_xml(
    config: &AndroidBuildConfig,
    version: &str,
    version_code: u32,
) -> String {
    let target_kind: AndroidTargetKind = config.get_target_kind();
    let app_label: &str = config
        .try_get_app_label()
        .as_deref()
        .unwrap_or_else(|| target_kind.default_app_label());
    let package_id: &str = config.get_package_id();
    let target_sdk: &str = config
        .try_get_api_level()
        .as_deref()
        .unwrap_or(ANDROID_DEFAULT_API_LEVEL);
    let wearos_feature: &str = if target_kind.is_wearos() {
        ANDROID_WEAROS_FEATURE_XML
    } else {
        ""
    };
    let wearos_meta: &str = if target_kind.is_wearos() {
        ANDROID_WEAROS_META_XML
    } else {
        ""
    };
    format!(
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n\
    package=\"{package_id}\"\n\
    android:versionCode=\"{version_code}\"\n\
    android:versionName=\"{version}\">\n\
    <uses-sdk android:minSdkVersion=\"{ANDROID_MIN_SDK_LEVEL}\" android:targetSdkVersion=\"{target_sdk}\" />\n\
{wearos_feature}\
    <uses-permission android:name=\"android.permission.VIBRATE\" />\n\
    <uses-permission android:name=\"android.permission.POST_NOTIFICATIONS\" />\n\
    <uses-permission android:name=\"android.permission.INTERNET\" />\n\
    <uses-permission android:name=\"android.permission.CAMERA\" />\n\
    <uses-permission android:name=\"android.permission.RECORD_AUDIO\" />\n\
    <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />\n\
    <uses-permission android:name=\"android.permission.READ_CONTACTS\" />\n\
    <uses-permission android:name=\"android.permission.READ_CALENDAR\" />\n\
    <uses-permission android:name=\"android.permission.READ_MEDIA_IMAGES\" />\n\
    <uses-permission android:name=\"android.permission.BLUETOOTH_CONNECT\" />\n\
    <uses-permission android:name=\"android.permission.USE_BIOMETRIC\" />\n\
    <uses-permission android:name=\"android.permission.BODY_SENSORS\" />\n\
    <uses-permission android:name=\"android.permission.NEARBY_WIFI_DEVICES\" />\n\
    <application\n\
        android:label=\"{app_label}\"\n\
        android:usesCleartextTraffic=\"true\"\n\
        android:icon=\"@mipmap/ic_launcher\"\n\
        android:roundIcon=\"@mipmap/ic_launcher\"\n\
        android:theme=\"@style/EuvLaunchTheme\"\n\
        android:hardwareAccelerated=\"true\">\n\
{wearos_meta}\
        <activity\n\
            android:name=\".EuvActivity\"\n\
            android:exported=\"true\"\n\
            android:windowSoftInputMode=\"adjustResize|stateHidden\"\n\
            android:configChanges=\"orientation|screenSize|screenLayout|smallestScreenSize|density|fontScale|uiMode|locale|keyboard|keyboardHidden|navigation\">\n\
            <intent-filter>\n\
                <action android:name=\"android.intent.action.MAIN\" />\n\
                <category android:name=\"android.intent.category.LAUNCHER\" />\n\
            </intent-filter>\n\
            <intent-filter>\n\
                <action android:name=\"android.intent.action.VIEW\" />\n\
                <category android:name=\"android.intent.category.DEFAULT\" />\n\
                <category android:name=\"android.intent.category.BROWSABLE\" />\n\
                <data android:scheme=\"euv\" />\n\
            </intent-filter>\n\
        </activity>\n\
    </application>\n\
</manifest>\n"
    )
}

/// Generates the complete standalone Android or Wear OS host project (Rust crate, JNI Java bridge, manifest, styles, icons).
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Build configuration specifying workspace root, target kind, ABIs, and output paths.
/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing mipmap PNG icons at requested sizes.
///
/// # Returns
///
/// - `io::Result<AndroidBuildReport>` - Summary of generated paths and resolved metadata.
pub fn generate_android_host_project(
    config: &AndroidBuildConfig,
    icon_writer: Option<&MobileIconWriter<'_>>,
) -> io::Result<AndroidBuildReport> {
    let workspace_root: PathBuf = resolve_absolute_path(config.get_workspace_root());
    let target_kind: AndroidTargetKind = config.get_target_kind();
    let version: String = config
        .try_get_app_version()
        .clone()
        .unwrap_or_else(|| resolve_workspace_semver(&workspace_root));
    let version_code: u32 = config
        .try_get_version_code()
        .unwrap_or_else(|| compute_semver_version_code(&version));
    let build_dir: PathBuf = config.try_get_build_dir().clone().unwrap_or_else(|| {
        workspace_root
            .join(MOBILE_HOSTS_SUBDIR)
            .join(target_kind.host_dir_name())
    });
    let apk_path: PathBuf = config.try_get_out_file().clone().unwrap_or_else(|| {
        workspace_root
            .join(MOBILE_DIST_DIR_NAME)
            .join(target_kind.default_out_subdir())
            .join(target_kind.default_apk_name())
    });
    let rust_src_dir: PathBuf = build_dir.join(MOBILE_DIR_RUST).join(MOBILE_DIR_SRC);
    let java_pkg_dir: PathBuf = build_dir.join(ANDROID_JAVA_PKG_REL);
    let res_dir: PathBuf = build_dir.join(DIR_RES);
    fs::create_dir_all(&rust_src_dir)?;
    fs::create_dir_all(&java_pkg_dir)?;
    if let Some(apk_parent) = apk_path.parent() {
        fs::create_dir_all(apk_parent)?;
    }
    let host_config_src: String = render_android_host_config(target_kind, config.get_render_mode());
    let cargo_toml_src: String = render_android_host_cargo_toml(&workspace_root, &version);
    fs::write(
        rust_src_dir.join(MOBILE_FILE_HOST_CONFIG_RS),
        host_config_src,
    )?;
    fs::write(
        build_dir.join(MOBILE_DIR_RUST).join(MOBILE_FILE_CARGO_TOML),
        cargo_toml_src,
    )?;
    fs::write(
        rust_src_dir.join(MOBILE_FILE_LIB_RS),
        ANDROID_HOST_LIB_RS_TEMPLATE,
    )?;
    fs::write(
        java_pkg_dir.join(ANDROID_JAVA_BRIDGE_FILE),
        ANDROID_JAVA_BRIDGE_TEMPLATE,
    )?;
    fs::write(
        java_pkg_dir.join(ANDROID_JAVA_ACTIVITY_FILE),
        ANDROID_JAVA_ACTIVITY_TEMPLATE,
    )?;
    let manifest_xml: String = render_android_manifest_xml(config, &version, version_code);
    fs::write(build_dir.join(ANDROID_MANIFEST_FILE), manifest_xml)?;
    write_android_resources(&res_dir, icon_writer)?;
    let abis: Vec<String> = resolved_android_abis(config)
        .iter()
        .map(|abi_item: &AndroidAbi| abi_item.as_abi_dir().to_string())
        .collect();
    Ok(AndroidBuildReport {
        target_kind: target_kind.as_label().to_string(),
        version,
        version_code,
        abis,
        build_dir,
        apk_path,
        apk_bytes: 0,
        ai_schema_clean: true,
        installed: false,
    })
}

/// Builds, aligns, signs, verifies, and optionally installs an Android or Wear OS APK in pure Rust.
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Full Android build, signing, and deployment configuration.
/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing mipmap PNG icons at requested sizes.
///
/// # Returns
///
/// - `io::Result<AndroidBuildReport>` - Detailed build report including final APK path and byte length.
pub fn build_android_apk(
    config: &AndroidBuildConfig,
    icon_writer: Option<&MobileIconWriter<'_>>,
) -> io::Result<AndroidBuildReport> {
    let generated: AndroidBuildReport = generate_android_host_project(config, icon_writer)?;
    if config.get_shell_only() {
        return Ok(generated);
    }
    let toolchain: AndroidToolchain = detect_android_toolchain(
        config.try_get_api_level().as_deref(),
        config.try_get_build_tools().as_deref(),
    )?;
    let build_dir: &Path = generated.get_build_dir();
    let rust_dir: PathBuf = build_dir.join(MOBILE_DIR_RUST);
    let abis: Vec<AndroidAbi> = resolved_android_abis(config);
    let mut staged_so_files: Vec<(String, Vec<u8>)> = Vec::new();
    for abi_item in abis.iter().copied() {
        let so_bytes: Vec<u8> =
            compile_android_rust_abi(&rust_dir, &toolchain, abi_item, config.get_release())?;
        let entry_name: String = format!("lib/{}/{}", abi_item.as_abi_dir(), ANDROID_HOST_SO_NAME);
        staged_so_files.push((entry_name, so_bytes));
    }
    let dex_bytes: Vec<u8> = compile_android_java_dex(build_dir, &toolchain)?;
    let res_dir: PathBuf = build_dir.join(DIR_RES);
    let res_zip: PathBuf = build_dir.join(FILE_RES_ZIP);
    let unaligned_apk: PathBuf = build_dir.join(FILE_UNALIGNED_APK);
    let aligned_apk: PathBuf = build_dir.join(FILE_ALIGNED_APK);
    let apk_out: &Path = generated.get_apk_path();
    remove_file_if_exists(&res_zip)?;
    remove_file_if_exists(&unaligned_apk)?;
    remove_file_if_exists(&aligned_apk)?;
    remove_file_if_exists(apk_out)?;
    run_checked_command(
        toolchain.get_aapt2_bin(),
        &[
            OsStr::new(ARG_COMPILE),
            OsStr::new(ARG_DIR),
            res_dir.as_os_str(),
            OsStr::new("-o"),
            res_zip.as_os_str(),
        ],
        None,
        &[],
    )?;
    let manifest_path: PathBuf = build_dir.join(ANDROID_MANIFEST_FILE);
    run_checked_command(
        toolchain.get_aapt2_bin(),
        &[
            OsStr::new(ARG_LINK),
            OsStr::new("-I"),
            toolchain.get_android_jar().as_os_str(),
            OsStr::new(ARG_MANIFEST),
            manifest_path.as_os_str(),
            OsStr::new(ARG_AUTO_ADD_OVERLAY),
            OsStr::new("-R"),
            res_zip.as_os_str(),
            OsStr::new("-o"),
            unaligned_apk.as_os_str(),
        ],
        None,
        &[],
    )?;
    let mut zip_entries: Vec<(&str, &[u8])> = Vec::with_capacity(1 + staged_so_files.len());
    zip_entries.push((ANDROID_CLASSES_DEX_NAME, dex_bytes.as_slice()));
    for (entry_path, so_bytes) in staged_so_files.iter() {
        zip_entries.push((entry_path.as_str(), so_bytes.as_slice()));
    }
    append_stored_entries_to_zip(&unaligned_apk, &zip_entries)?;
    run_checked_command(
        toolchain.get_zipalign_bin(),
        &[
            OsStr::new("-f"),
            OsStr::new("-P"),
            OsStr::new(ARG_ALIGN_PAGE_16),
            OsStr::new(ARG_ALIGN_BYTES_4),
            unaligned_apk.as_os_str(),
            aligned_apk.as_os_str(),
        ],
        None,
        &[],
    )?;
    sign_and_verify_apk(config, &toolchain, &aligned_apk, apk_out)?;
    let apk_bytes: u64 = fs::metadata(apk_out)?.len();
    let installed: bool = if config.get_install() {
        install_and_launch_apk(config, &toolchain, apk_out)?;
        true
    } else {
        false
    };
    Ok(AndroidBuildReport {
        target_kind: generated.get_target_kind().clone(),
        version: generated.get_version().clone(),
        version_code: generated.get_version_code(),
        abis: generated.get_abis().clone(),
        build_dir: generated.get_build_dir().clone(),
        apk_path: apk_out.to_path_buf(),
        apk_bytes,
        ai_schema_clean: true,
        installed,
    })
}

/// Appends uncompressed (`STORED`, method 0) entries to an existing ZIP archive in pure Rust.
///
/// # Arguments
///
/// - `&Path` - Path to the existing ZIP or unaligned APK file modified in place.
/// - `&[(&str, &[u8])]` - Ordered `(entry_path, raw_bytes)` pairs appended uncompressed.
///
/// # Returns
///
/// - `io::Result<()>` - Success or I/O / malformed-ZIP error.
pub fn append_stored_entries_to_zip(zip_path: &Path, entries: &[(&str, &[u8])]) -> io::Result<()> {
    let existing: Vec<u8> = fs::read(zip_path)?;
    let eocd_pos: usize = locate_zip_eocd(&existing)?;
    let existing_count: usize =
        u16::from_le_bytes([existing[eocd_pos + 10], existing[eocd_pos + 11]]) as usize;
    let existing_cd_size: usize = u32::from_le_bytes([
        existing[eocd_pos + 12],
        existing[eocd_pos + 13],
        existing[eocd_pos + 14],
        existing[eocd_pos + 15],
    ]) as usize;
    let existing_cd_offset: usize = u32::from_le_bytes([
        existing[eocd_pos + 16],
        existing[eocd_pos + 17],
        existing[eocd_pos + 18],
        existing[eocd_pos + 19],
    ]) as usize;
    let cd_end: usize = existing_cd_offset.saturating_add(existing_cd_size);
    if cd_end > eocd_pos {
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!(
                "corrupt ZIP central directory bounds in {}",
                zip_path.display()
            ),
        ));
    }
    let mut output_buf: Vec<u8> = Vec::with_capacity(existing.len());
    output_buf.extend_from_slice(&existing[..existing_cd_offset]);
    let mut central_dir: Vec<u8> = Vec::with_capacity(existing_cd_size);
    central_dir.extend_from_slice(&existing[existing_cd_offset..cd_end]);
    for (entry_name, entry_bytes) in entries.iter().copied() {
        let local_offset: u32 = u32::try_from(output_buf.len())
            .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_4GIB_LIMIT))?;
        let entry_size: u32 = u32::try_from(entry_bytes.len())
            .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_ENTRY_4GIB))?;
        let name_bytes: &[u8] = entry_name.as_bytes();
        let name_len: u16 = u16::try_from(name_bytes.len())
            .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_NAME_TOO_LONG))?;
        let crc: u32 = compute_ieee_crc32(entry_bytes);
        write_zip_local_header(&mut output_buf, name_bytes, name_len, crc, entry_size);
        output_buf.extend_from_slice(entry_bytes);
        write_zip_central_header(
            &mut central_dir,
            name_bytes,
            name_len,
            crc,
            entry_size,
            local_offset,
        );
    }
    let new_cd_offset: u32 = u32::try_from(output_buf.len())
        .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_CD_OVERFLOW))?;
    let new_cd_size: u32 = u32::try_from(central_dir.len())
        .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_CD_TOO_LARGE))?;
    let total_entries: u16 = u16::try_from(existing_count + entries.len())
        .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_ENTRY_COUNT_OVERFLOW))?;
    output_buf.extend_from_slice(&central_dir);
    write_zip_eocd(&mut output_buf, total_entries, new_cd_size, new_cd_offset);
    fs::write(zip_path, output_buf)
}

/// Computes the standard IEEE 802.3 CRC-32 checksum for `data`.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `u32` - CRC-32 checksum.
#[must_use]
pub fn compute_ieee_crc32(data: &[u8]) -> u32 {
    let mut crc: u32 = 0xFFFF_FFFF;
    for byte_val in data.iter().copied() {
        crc ^= u32::from(byte_val);
        for _bit in 0..8 {
            if (crc & 1) != 0 {
                crc = (crc >> 1) ^ CRC32_POLY_REFLECTED;
            } else {
                crc >>= 1;
            }
        }
    }
    !crc
}

/// Locates the byte offset of the End-of-Central-Directory record in a ZIP archive.
///
/// # Arguments
///
/// - `&[u8]` - Raw ZIP archive bytes.
///
/// # Returns
///
/// - `io::Result<usize>` - Byte offset of the EOCD signature or `InvalidData` error.
fn locate_zip_eocd(data: &[u8]) -> io::Result<usize> {
    if data.len() < ZIP_EOCD_MIN_LEN {
        return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_SHORT_EOCD));
    }
    let min_pos: usize = data
        .len()
        .saturating_sub(ZIP_EOCD_MIN_LEN + ZIP_MAX_COMMENT_LEN);
    let mut cursor: usize = data.len() - ZIP_EOCD_MIN_LEN;
    loop {
        let sig: u32 = u32::from_le_bytes([
            data[cursor],
            data[cursor + 1],
            data[cursor + 2],
            data[cursor + 3],
        ]);
        if sig == ZIP_EOCD_SIG {
            let comment_len: usize =
                u16::from_le_bytes([data[cursor + 20], data[cursor + 21]]) as usize;
            if cursor + ZIP_EOCD_MIN_LEN + comment_len == data.len() {
                return Ok(cursor);
            }
        }
        if cursor == min_pos {
            break;
        }
        cursor -= 1;
    }
    Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_NO_EOCD))
}

/// Appends a 30-byte ZIP Local File Header (method 0 / STORED) to `buf`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Target archive byte buffer.
/// - `&[u8]` - UTF-8 entry name bytes.
/// - `u16` - Byte length of `name_bytes`.
/// - `u32` - IEEE CRC-32 checksum.
/// - `u32` - Uncompressed and stored byte length.
fn write_zip_local_header(
    buf: &mut Vec<u8>,
    name_bytes: &[u8],
    name_len: u16,
    crc: u32,
    entry_size: u32,
) {
    buf.extend_from_slice(&ZIP_LOCAL_FILE_SIG.to_le_bytes());
    buf.extend_from_slice(&20u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&crc.to_le_bytes());
    buf.extend_from_slice(&entry_size.to_le_bytes());
    buf.extend_from_slice(&entry_size.to_le_bytes());
    buf.extend_from_slice(&name_len.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(name_bytes);
}

/// Appends a 46-byte ZIP Central Directory Header (method 0 / STORED) to `buf`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Target central directory byte buffer.
/// - `&[u8]` - UTF-8 entry name bytes.
/// - `u16` - Byte length of `name_bytes`.
/// - `u32` - IEEE CRC-32 checksum.
/// - `u32` - Uncompressed and stored byte length.
/// - `u32` - Local file header byte offset inside the archive.
fn write_zip_central_header(
    buf: &mut Vec<u8>,
    name_bytes: &[u8],
    name_len: u16,
    crc: u32,
    entry_size: u32,
    local_offset: u32,
) {
    buf.extend_from_slice(&ZIP_CENTRAL_DIR_SIG.to_le_bytes());
    buf.extend_from_slice(&20u16.to_le_bytes());
    buf.extend_from_slice(&20u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&crc.to_le_bytes());
    buf.extend_from_slice(&entry_size.to_le_bytes());
    buf.extend_from_slice(&entry_size.to_le_bytes());
    buf.extend_from_slice(&name_len.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u32.to_le_bytes());
    buf.extend_from_slice(&local_offset.to_le_bytes());
    buf.extend_from_slice(name_bytes);
}

/// Appends a 22-byte ZIP End-of-Central-Directory record to `buf`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Target archive byte buffer.
/// - `u16` - Total entry count in the archive.
/// - `u32` - Total byte length of the central directory.
/// - `u32` - Byte offset of the central directory start.
fn write_zip_eocd(buf: &mut Vec<u8>, total_entries: u16, cd_size: u32, cd_offset: u32) {
    buf.extend_from_slice(&ZIP_EOCD_SIG.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
    buf.extend_from_slice(&total_entries.to_le_bytes());
    buf.extend_from_slice(&total_entries.to_le_bytes());
    buf.extend_from_slice(&cd_size.to_le_bytes());
    buf.extend_from_slice(&cd_offset.to_le_bytes());
    buf.extend_from_slice(&0u16.to_le_bytes());
}

/// Renders the Android host `host_config.rs` source file.
///
/// # Arguments
///
/// - `AndroidTargetKind` - Selected Android device form factor.
/// - `RenderArg` - Selected render pipeline mode.
///
/// # Returns
///
/// - `String` - Generated `host_config.rs` file contents.
fn render_android_host_config(target_kind: AndroidTargetKind, render_mode: RenderArg) -> String {
    let platform_expr: &str = target_kind.platform_kind_expr();
    let render_expr: &str = render_mode_const_expr(render_mode);
    let is_wearos: bool = target_kind.is_wearos();
    format!(
        "use euv::{{PlatformKind, RenderMode}};\n\n\
pub const HOST_PLATFORM_KIND: PlatformKind = {platform_expr};\n\
pub const HOST_RENDER_MODE: RenderMode = {render_expr};\n\
pub const HOST_IS_WEAROS: bool = {is_wearos};\n"
    )
}

/// Renders the standalone Android host crate `Cargo.toml` referencing the active workspace.
///
/// # Arguments
///
/// - `&Path` - Absolute path to the `euv` workspace root.
/// - `&str` - Dynamic semantic version string.
///
/// # Returns
///
/// - `String` - Generated `Cargo.toml` contents.
fn render_android_host_cargo_toml(workspace_root: &Path, version: &str) -> String {
    let root_escaped: String = escape_toml_path(workspace_root);
    let example_escaped: String = escape_toml_path(&workspace_root.join(MOBILE_DIR_EXAMPLE));
    format!(
        "[workspace]\n\n\
[package]\n\
name = \"euv-android-host\"\n\
version = \"{version}\"\n\
edition = \"2024\"\n\n\
[lib]\n\
crate-type = [\"cdylib\"]\n\n\
[dependencies]\n\
euv = {{ path = \"{root_escaped}\" }}\n\
euv-example = {{ path = \"{example_escaped}\" }}\n\n\
[profile.release]\n\
opt-level = 3\n\
lto = \"thin\"\n\
codegen-units = 1\n\
panic = \"abort\"\n\
strip = \"symbols\"\n"
    )
}

/// Writes Android theme XML resources and all five mipmap launcher icon densities.
///
/// # Arguments
///
/// - `&Path` - Target Android `res/` staging directory.
/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
///
/// # Returns
///
/// - `io::Result<()>` - Resource staging outcome.
fn write_android_resources(
    res_dir: &Path,
    icon_writer: Option<&MobileIconWriter<'_>>,
) -> io::Result<()> {
    if res_dir.exists() {
        fs::remove_dir_all(res_dir)?;
    }
    let style_dirs: [(&str, &str); 4] = [
        (DIR_VALUES, ANDROID_STYLES_LIGHT_XML),
        (DIR_VALUES_NIGHT, ANDROID_STYLES_NIGHT_XML),
        (DIR_VALUES_V31, ANDROID_STYLES_V31_XML),
        (DIR_VALUES_NIGHT_V31, ANDROID_STYLES_NIGHT_V31_XML),
    ];
    for (dir_name, xml_body) in style_dirs.iter().copied() {
        let style_dir: PathBuf = res_dir.join(dir_name);
        fs::create_dir_all(&style_dir)?;
        fs::write(style_dir.join(FILE_STYLES_XML), xml_body)?;
    }
    for (density_dir, size_px) in ANDROID_MIPMAP_DENSITIES.iter().copied() {
        let icon_path: PathBuf = res_dir.join(density_dir).join(ANDROID_LAUNCHER_ICON_FILE);
        write_icon_or_fallback(icon_writer, &icon_path, size_px)?;
    }
    Ok(())
}

/// Compiles the Android Rust host shared library for a single ABI and verifies release AI-schema stripping.
///
/// # Arguments
///
/// - `&Path` - Directory containing the generated `euv-android-host` `Cargo.toml`.
/// - `&AndroidToolchain` - Resolved Android SDK/NDK toolchain paths.
/// - `AndroidAbi` - Target CPU ABI to compile.
/// - `bool` - Whether to compile with `--release` and enforce zero AI-schema markers.
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Compiled `libeuv_android_host.so` bytes.
fn compile_android_rust_abi(
    rust_dir: &Path,
    toolchain: &AndroidToolchain,
    abi: AndroidAbi,
    release: bool,
) -> io::Result<Vec<u8>> {
    let linker: PathBuf =
        resolve_android_ndk_linker(toolchain.get_ndk_llvm_bin(), abi, toolchain.get_api_level())?;
    let llvm_ar: PathBuf = find_host_executable(toolchain.get_ndk_llvm_bin(), TOOL_LLVM_AR)
        .unwrap_or_else(|| toolchain.get_ndk_llvm_bin().join(TOOL_LLVM_AR));
    let cc_key: String = format!("CC_{}", abi.cargo_env_triple());
    let ar_key: String = format!("AR_{}", abi.cargo_env_triple());
    let mut args: Vec<&OsStr> = Vec::new();
    args.push(OsStr::new(MOBILE_ARG_BUILD));
    if release {
        args.push(OsStr::new(MOBILE_ARG_RELEASE));
    }
    args.push(OsStr::new(MOBILE_ARG_TARGET));
    args.push(OsStr::new(abi.rust_triple()));
    let envs: [(&str, &OsStr); 3] = [
        (abi.cargo_linker_env(), linker.as_os_str()),
        (cc_key.as_str(), linker.as_os_str()),
        (ar_key.as_str(), llvm_ar.as_os_str()),
    ];
    run_checked_command(Path::new(MOBILE_CMD_CARGO), &args, Some(rust_dir), &envs)?;
    let profile_dir: &str = if release {
        MOBILE_DIR_RELEASE
    } else {
        MOBILE_DIR_DEBUG
    };
    let so_path: PathBuf = rust_dir
        .join(MOBILE_DIR_TARGET)
        .join(abi.rust_triple())
        .join(profile_dir)
        .join(ANDROID_HOST_SO_NAME);
    if release {
        assert_release_binary_ai_schema_clean(&so_path)?;
    }
    fs::read(&so_path)
}

/// Compiles the Android Java bridge sources into bytecode and packages `classes.dex` via `d8`.
///
/// # Arguments
///
/// - `&Path` - Android host build staging directory.
/// - `&AndroidToolchain` - Resolved Android SDK toolchain paths.
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Compiled `classes.dex` bytes.
fn compile_android_java_dex(build_dir: &Path, toolchain: &AndroidToolchain) -> io::Result<Vec<u8>> {
    let classes_dir: PathBuf = build_dir.join(DIR_CLASSES);
    let dex_dir: PathBuf = build_dir.join(DIR_DEX);
    if classes_dir.exists() {
        fs::remove_dir_all(&classes_dir)?;
    }
    if dex_dir.exists() {
        fs::remove_dir_all(&dex_dir)?;
    }
    fs::create_dir_all(&classes_dir)?;
    fs::create_dir_all(&dex_dir)?;
    let bridge_java: PathBuf = build_dir
        .join(ANDROID_JAVA_PKG_REL)
        .join(ANDROID_JAVA_BRIDGE_FILE);
    let activity_java: PathBuf = build_dir
        .join(ANDROID_JAVA_PKG_REL)
        .join(ANDROID_JAVA_ACTIVITY_FILE);
    run_checked_command(
        Path::new(CMD_JAVAC),
        &[
            OsStr::new(ARG_SOURCE),
            OsStr::new(JAVA_BYTECODE_LEVEL),
            OsStr::new(ARG_JAVA_TARGET),
            OsStr::new(JAVA_BYTECODE_LEVEL),
            OsStr::new(ARG_CLASSPATH),
            toolchain.get_android_jar().as_os_str(),
            OsStr::new("-d"),
            classes_dir.as_os_str(),
            bridge_java.as_os_str(),
            activity_java.as_os_str(),
        ],
        None,
        &[],
    )?;
    let mut class_files: Vec<PathBuf> = Vec::new();
    collect_files_with_extension(&classes_dir, EXT_CLASS, &mut class_files)?;
    class_files.sort();
    let mut d8_args: Vec<&OsStr> = vec![
        OsStr::new(ARG_MIN_API),
        OsStr::new(ANDROID_MIN_SDK_LEVEL),
        OsStr::new(MOBILE_ARG_LIB),
        toolchain.get_android_jar().as_os_str(),
        OsStr::new(ARG_OUTPUT),
        dex_dir.as_os_str(),
    ];
    for class_file in class_files.iter() {
        d8_args.push(class_file.as_os_str());
    }
    run_checked_command(toolchain.get_d8_bin(), &d8_args, None, &[])?;
    fs::read(dex_dir.join(ANDROID_CLASSES_DEX_NAME))
}

/// Signs and verifies the aligned APK using either a custom keystore or an auto-created debug keystore.
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Android build configuration with optional keystore overrides.
/// - `&AndroidToolchain` - Resolved Android SDK toolchain paths.
/// - `&Path` - Aligned input APK path.
/// - `&Path` - Signed final APK output path.
///
/// # Returns
///
/// - `io::Result<()>` - Signing and verification outcome.
fn sign_and_verify_apk(
    config: &AndroidBuildConfig,
    toolchain: &AndroidToolchain,
    aligned_apk: &Path,
    apk_out: &Path,
) -> io::Result<()> {
    let ks_path: PathBuf = resolve_android_keystore_path(config)?;
    let ks_pass: String = config
        .try_get_keystore_pass()
        .clone()
        .or_else(|| env::var(ENV_EUV_ANDROID_KEYSTORE_PASS).ok())
        .unwrap_or_else(|| ANDROID_DEFAULT_KEYSTORE_PASS.to_string());
    let key_pass: String = config
        .try_get_key_pass()
        .clone()
        .or_else(|| env::var(ENV_EUV_ANDROID_KEY_PASS).ok())
        .unwrap_or_else(|| ks_pass.clone());
    let key_alias: String = config
        .try_get_key_alias()
        .clone()
        .or_else(|| env::var(ENV_EUV_ANDROID_KEY_ALIAS).ok())
        .unwrap_or_else(|| ANDROID_DEFAULT_KEY_ALIAS.to_string());
    if !ks_path.is_file() {
        if let Some(ks_parent) = ks_path.parent() {
            fs::create_dir_all(ks_parent)?;
        }
        run_checked_command(
            Path::new(CMD_KEYTOOL),
            &[
                OsStr::new(ARG_GENKEYPAIR),
                OsStr::new("-v"),
                OsStr::new(ARG_KEYSTORE),
                ks_path.as_os_str(),
                OsStr::new(ARG_STOREPASS),
                OsStr::new(&ks_pass),
                OsStr::new(ARG_ALIAS),
                OsStr::new(&key_alias),
                OsStr::new(ARG_KEYTOOL_KEYPASS),
                OsStr::new(&key_pass),
                OsStr::new(ARG_KEYALG),
                OsStr::new(ARG_KEYALG_RSA),
                OsStr::new(ARG_KEYSIZE),
                OsStr::new(ARG_KEYSIZE_2048),
                OsStr::new(ARG_VALIDITY),
                OsStr::new(ARG_VALIDITY_10000),
                OsStr::new(ARG_DNAME),
                OsStr::new(ANDROID_DEBUG_DNAME),
            ],
            None,
            &[],
        )?;
    }
    let ks_pass_arg: String = format!("pass:{ks_pass}");
    let key_pass_arg: String = format!("pass:{key_pass}");
    run_checked_command(
        toolchain.get_apksigner_bin(),
        &[
            OsStr::new(ARG_SIGN),
            OsStr::new(ARG_KS),
            ks_path.as_os_str(),
            OsStr::new(ARG_KS_PASS),
            OsStr::new(&ks_pass_arg),
            OsStr::new(ARG_KEY_PASS),
            OsStr::new(&key_pass_arg),
            OsStr::new(ARG_KS_KEY_ALIAS),
            OsStr::new(&key_alias),
            OsStr::new(ARG_OUT),
            apk_out.as_os_str(),
            aligned_apk.as_os_str(),
        ],
        None,
        &[],
    )?;
    let _: Output = run_checked_command(
        toolchain.get_apksigner_bin(),
        &[OsStr::new(ARG_VERIFY), apk_out.as_os_str()],
        None,
        &[],
    )?;
    Ok(())
}

/// Installs and launches the signed APK across all online ADB devices, booting an AVD if none are online.
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Android build configuration with package ID and optional AVD name.
/// - `&AndroidToolchain` - Resolved Android SDK toolchain paths.
/// - `&Path` - Signed APK path to deploy.
///
/// # Returns
///
/// - `io::Result<()>` - Installation and launch outcome.
fn install_and_launch_apk(
    config: &AndroidBuildConfig,
    toolchain: &AndroidToolchain,
    apk_out: &Path,
) -> io::Result<()> {
    let adb_bin: &Path = toolchain.get_adb_bin();
    let _: io::Result<Output> = Command::new(adb_bin).arg(ARG_ADB_START_SERVER).output();
    let mut serials: Vec<String> = list_online_adb_serials(adb_bin)?;
    if serials.is_empty() {
        let avd_name: String = resolve_android_avd_name(config);
        let mut emulator_cmd: Command = Command::new(toolchain.get_emulator_bin());
        let _: &mut Command = emulator_cmd
            .arg(ARG_EMULATOR_AVD)
            .arg(&avd_name)
            .arg(ARG_EMULATOR_NO_BOOT_ANIM)
            .arg(ARG_EMULATOR_GPU)
            .arg(ARG_EMULATOR_GPU_AUTO)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        let _: Child = emulator_cmd.spawn()?;
        run_checked_command(adb_bin, &[OsStr::new(ARG_ADB_WAIT_FOR_DEVICE)], None, &[])?;
        for _attempt in 0..ANDROID_AVD_BOOT_POLL_ATTEMPTS {
            let boot_out: Output = Command::new(adb_bin)
                .args([ARG_ADB_SHELL, ARG_ADB_GETPROP, ANDROID_PROP_BOOT_COMPLETED])
                .output()?;
            let prop_val: String = String::from_utf8_lossy(&boot_out.stdout).trim().to_string();
            if prop_val == "1" {
                break;
            }
            thread::sleep(Duration::from_secs(ANDROID_AVD_BOOT_POLL_SECS));
        }
        thread::sleep(Duration::from_secs(ANDROID_AVD_BOOT_SETTLE_SECS));
        serials = list_online_adb_serials(adb_bin)?;
    }
    let activity_component: String =
        format!("{}/{}", config.get_package_id(), ANDROID_ACTIVITY_COMPONENT);
    for serial in serials.iter() {
        run_checked_command(
            adb_bin,
            &[
                OsStr::new("-s"),
                OsStr::new(serial),
                OsStr::new(ARG_ADB_INSTALL),
                OsStr::new("-r"),
                apk_out.as_os_str(),
            ],
            None,
            &[],
        )?;
        run_checked_command(
            adb_bin,
            &[
                OsStr::new("-s"),
                OsStr::new(serial),
                OsStr::new(ARG_ADB_SHELL),
                OsStr::new("am"),
                OsStr::new(ARG_ADB_START),
                OsStr::new("-n"),
                OsStr::new(&activity_component),
            ],
            None,
            &[],
        )?;
    }
    Ok(())
}

/// Lists all currently online `adb` device serials in `device` state.
///
/// # Arguments
///
/// - `&Path` - Path to the `adb` executable.
///
/// # Returns
///
/// - `io::Result<Vec<String>>` - Online device serial numbers.
fn list_online_adb_serials(adb_bin: &Path) -> io::Result<Vec<String>> {
    let output: Output = Command::new(adb_bin).arg(ARG_ADB_DEVICES).output()?;
    let stdout_str: Cow<'_, str> = String::from_utf8_lossy(&output.stdout);
    let mut serials: Vec<String> = Vec::new();
    for raw_line in stdout_str.lines().skip(1) {
        let mut parts: SplitWhitespace<'_> = raw_line.split_whitespace();
        let Some(serial) = parts.next() else {
            continue;
        };
        let Some(state) = parts.next() else {
            continue;
        };
        if state == ANDROID_ADB_STATUS_DEVICE {
            serials.push(serial.to_string());
        }
    }
    Ok(serials)
}

/// Resolves the active Android ABI list, defaulting to `Arm64V8a` when empty.
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Android build configuration.
///
/// # Returns
///
/// - `Vec<AndroidAbi>` - Non-empty ABI list.
fn resolved_android_abis(config: &AndroidBuildConfig) -> Vec<AndroidAbi> {
    if config.get_abis().is_empty() {
        return vec![AndroidAbi::Arm64V8a];
    }
    config.get_abis().clone()
}

/// Resolves the Android SDK root directory from environment variables or OS defaults.
///
/// # Returns
///
/// - `io::Result<PathBuf>` - Existing Android SDK root path or `NotFound` error.
fn resolve_android_sdk_root() -> io::Result<PathBuf> {
    for env_key in [ENV_ANDROID_HOME, ENV_ANDROID_SDK_ROOT] {
        if let Ok(raw_val) = env::var(env_key) {
            let trimmed: &str = raw_val.trim();
            if !trimmed.is_empty() {
                let candidate: PathBuf = PathBuf::from(trimmed);
                if candidate.is_dir() {
                    return Ok(candidate);
                }
            }
        }
    }
    let mut candidates: Vec<PathBuf> = Vec::new();
    if let Some(home_dir) = resolve_user_home_dir() {
        if consts::OS == MOBILE_HOST_OS_MACOS {
            candidates.push(home_dir.join(ANDROID_MACOS_HOME_SDK_REL));
        } else if consts::OS == MOBILE_HOST_OS_WINDOWS {
            candidates.push(home_dir.join(ANDROID_WINDOWS_HOME_SDK_REL));
        } else {
            candidates.push(home_dir.join(ANDROID_LINUX_HOME_SDK_REL));
        }
    }
    candidates.push(PathBuf::from(ANDROID_CI_LINUX_SDK_FALLBACK));
    for candidate in candidates.into_iter() {
        if candidate.is_dir() {
            return Ok(candidate);
        }
    }
    Err(Error::new(ErrorKind::NotFound, ERR_ANDROID_SDK_MISSING))
}

/// Resolves the Android NDK root directory from env vars or highest installed `<sdk>/ndk/<version>`.
///
/// # Arguments
///
/// - `&Path` - Resolved Android SDK root directory.
///
/// # Returns
///
/// - `io::Result<PathBuf>` - Existing Android NDK root directory or `NotFound` error.
fn resolve_android_ndk_root(sdk_root: &Path) -> io::Result<PathBuf> {
    for env_key in [ENV_ANDROID_NDK_LATEST_HOME, ENV_ANDROID_NDK_HOME] {
        if let Ok(raw_val) = env::var(env_key) {
            let trimmed: &str = raw_val.trim();
            if !trimmed.is_empty() {
                let candidate: PathBuf = PathBuf::from(trimmed);
                if candidate.is_dir() {
                    return Ok(candidate);
                }
            }
        }
    }
    if let Ok(preferred) = env::var(ENV_EUV_ANDROID_NDK_VERSION) {
        let trimmed: &str = preferred.trim();
        if !trimmed.is_empty() {
            let preferred_dir: PathBuf = sdk_root.join(ANDROID_NDK_DIR).join(trimmed);
            if preferred_dir.is_dir() {
                return Ok(preferred_dir);
            }
        }
    }
    let ndk_parent: PathBuf = sdk_root.join(ANDROID_NDK_DIR);
    let mut versions: Vec<(Vec<u64>, String, PathBuf)> = Vec::new();
    if let Ok(entries) = fs::read_dir(&ndk_parent) {
        for entry_res in entries {
            let Ok(entry) = entry_res else {
                continue;
            };
            let entry_path: PathBuf = entry.path();
            if !entry_path.is_dir() {
                continue;
            }
            let Some(name_str) = entry_path.file_name().and_then(OsStr::to_str) else {
                continue;
            };
            versions.push((
                parse_version_sort_key(name_str),
                name_str.to_string(),
                entry_path,
            ));
        }
    }
    versions.sort_by(
        |left: &(Vec<u64>, String, PathBuf), right: &(Vec<u64>, String, PathBuf)| {
            left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))
        },
    );
    if let Some((_, _, latest_dir)) = versions.pop() {
        return Ok(latest_dir);
    }
    Err(Error::new(
        ErrorKind::NotFound,
        format!(
            "Android NDK not found under {} (set ANDROID_NDK_HOME)",
            ndk_parent.display()
        ),
    ))
}

/// Resolves the target Android keystore file path from config, env, or `~/.android/debug.keystore`.
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Android build configuration.
///
/// # Returns
///
/// - `io::Result<PathBuf>` - Resolved keystore path.
fn resolve_android_keystore_path(config: &AndroidBuildConfig) -> io::Result<PathBuf> {
    if let Some(custom) = config.try_get_keystore_path() {
        return Ok(custom.clone());
    }
    if let Ok(env_ks) = env::var(ENV_EUV_ANDROID_KEYSTORE) {
        let trimmed: &str = env_ks.trim();
        if !trimmed.is_empty() {
            return Ok(PathBuf::from(trimmed));
        }
    }
    let home_dir: PathBuf = resolve_user_home_dir()
        .ok_or_else(|| Error::new(ErrorKind::NotFound, ERR_ANDROID_HOME_MISSING))?;
    Ok(home_dir.join(ANDROID_DEBUG_KEYSTORE_REL))
}

/// Resolves the target Android AVD name from config, environment variables, or target kind defaults.
///
/// # Arguments
///
/// - `&AndroidBuildConfig` - Android build configuration.
///
/// # Returns
///
/// - `String` - Resolved AVD name.
fn resolve_android_avd_name(config: &AndroidBuildConfig) -> String {
    if let Some(custom) = config.try_get_avd_name() {
        return custom.clone();
    }
    let env_key: &str = if config.get_target_kind().is_wearos() {
        ENV_ANDROID_WEAR_AVD_NAME
    } else {
        ENV_ANDROID_AVD_NAME
    };
    if let Ok(val) = env::var(env_key) {
        let trimmed: &str = val.trim();
        if !trimmed.is_empty() {
            return trimmed.to_string();
        }
    }
    config.get_target_kind().default_avd_name().to_string()
}

/// Resolves the current user home directory across Unix (`HOME`) and Windows (`USERPROFILE`).
///
/// # Returns
///
/// - `Option<PathBuf>` - User home directory path when set.
pub(crate) fn resolve_user_home_dir() -> Option<PathBuf> {
    for env_key in [MOBILE_ENV_HOME, MOBILE_ENV_USERPROFILE] {
        if let Ok(raw_val) = env::var(env_key) {
            let trimmed: &str = raw_val.trim();
            if !trimmed.is_empty() {
                return Some(PathBuf::from(trimmed));
            }
        }
    }
    None
}

/// Resolves a path to an absolute canonical path where possible.
///
/// # Arguments
///
/// - `&Path` - Input relative or absolute path.
///
/// # Returns
///
/// - `PathBuf` - Absolute path suitable for generated host `Cargo.toml` dependencies.
pub(crate) fn resolve_absolute_path(path: &Path) -> PathBuf {
    if let Ok(canonical) = fs::canonicalize(path) {
        return canonical;
    }
    if path.is_absolute() {
        return path.to_path_buf();
    }
    env::current_dir()
        .map(|cwd: PathBuf| cwd.join(path))
        .unwrap_or_else(|_err: Error| path.to_path_buf())
}

/// Formats a filesystem path as a TOML string literal with forward slashes for cross-OS portability.
///
/// # Arguments
///
/// - `&Path` - Path to encode inside a double-quoted TOML string.
///
/// # Returns
///
/// - `String` - Escaped path string.
pub(crate) fn escape_toml_path(path: &Path) -> String {
    path.to_string_lossy()
        .replace('\\', "/")
        .replace('"', "\\\"")
}

/// Executes an external command and returns a detailed error containing stderr/stdout on failure.
///
/// # Arguments
///
/// - `&Path` - Executable program name or absolute path.
/// - `&[&OsStr]` - Command-line arguments.
/// - `Option<&Path>` - Optional working directory.
/// - `&[(&str, &OsStr)]` - Additional environment variable pairs.
///
/// # Returns
///
/// - `io::Result<Output>` - Captured command output on zero exit status.
pub(crate) fn run_checked_command(
    program: &Path,
    args: &[&OsStr],
    cwd: Option<&Path>,
    envs: &[(&str, &OsStr)],
) -> io::Result<Output> {
    let mut cmd: Command = Command::new(program);
    let _: &mut Command = cmd.args(args);
    if let Some(dir) = cwd {
        let _: &mut Command = cmd.current_dir(dir);
    }
    for (env_key, env_val) in envs.iter().copied() {
        let _: &mut Command = cmd.env(env_key, env_val);
    }
    let output: Output = cmd.output().map_err(|err: Error| {
        Error::new(
            err.kind(),
            format!("failed to execute {}: {err}", program.display()),
        )
    })?;
    if !output.status.success() {
        let stderr_text: Cow<'_, str> = String::from_utf8_lossy(&output.stderr);
        let stdout_text: Cow<'_, str> = String::from_utf8_lossy(&output.stdout);
        return Err(Error::other(format!(
            "command {} failed (status={}): {}{}",
            program.display(),
            output.status,
            stderr_text.trim(),
            if stderr_text.trim().is_empty() {
                stdout_text.trim()
            } else {
                ""
            }
        )));
    }
    Ok(output)
}

/// Locates an executable in `dir`, probing `.exe`/`.cmd`/`.bat` suffixes on Windows.
///
/// # Arguments
///
/// - `&Path` - Directory containing the tool binary.
/// - `&str` - Base executable stem.
///
/// # Returns
///
/// - `Option<PathBuf>` - Matching executable path when present on disk.
fn find_host_executable(dir: &Path, tool_name: &str) -> Option<PathBuf> {
    if cfg!(windows) {
        for suffix in [MOBILE_WIN_EXE_EXT, MOBILE_WIN_CMD_EXT, MOBILE_WIN_BAT_EXT] {
            let with_ext: PathBuf = dir.join(format!("{tool_name}{suffix}"));
            if with_ext.is_file() {
                return Some(with_ext);
            }
        }
        let direct: PathBuf = dir.join(tool_name);
        if direct.is_file() {
            return Some(direct);
        }
        return None;
    }
    let direct: PathBuf = dir.join(tool_name);
    if direct.is_file() {
        return Some(direct);
    }
    for suffix in [MOBILE_WIN_EXE_EXT, MOBILE_WIN_CMD_EXT, MOBILE_WIN_BAT_EXT] {
        let with_ext: PathBuf = dir.join(format!("{tool_name}{suffix}"));
        if with_ext.is_file() {
            return Some(with_ext);
        }
    }
    None
}

/// Requires an executable to exist in `dir`, returning a `NotFound` error otherwise.
///
/// # Arguments
///
/// - `&Path` - Directory expected to contain the tool.
/// - `&str` - Executable stem name.
///
/// # Returns
///
/// - `io::Result<PathBuf>` - Existing executable path.
fn require_host_executable(dir: &Path, tool_name: &str) -> io::Result<PathBuf> {
    find_host_executable(dir, tool_name).ok_or_else(|| {
        Error::new(
            ErrorKind::NotFound,
            format!(
                "required Android tool '{tool_name}' not found in {}",
                dir.display()
            ),
        )
    })
}

/// Strips Windows `.exe`/`.cmd`/`.bat` suffixes from a filename for matching.
///
/// # Arguments
///
/// - `&str` - Filename string.
///
/// # Returns
///
/// - `&str` - Filename without Windows executable suffix.
fn strip_windows_script_ext(file_name: &str) -> &str {
    for suffix in [MOBILE_WIN_EXE_EXT, MOBILE_WIN_CMD_EXT, MOBILE_WIN_BAT_EXT] {
        if let Some(prefix) = file_name.strip_suffix(suffix) {
            return prefix;
        }
    }
    file_name
}

/// Parses dot-delimited numeric segments of a version label for natural version sorting.
///
/// # Arguments
///
/// - `&str` - Version label such as `"27.2.12479018"` or `"35"`.
///
/// # Returns
///
/// - `Vec<u64>` - Parsed numeric segments.
fn parse_version_sort_key(raw: &str) -> Vec<u64> {
    raw.split('.')
        .map(|part: &str| {
            let digits: String = part
                .chars()
                .take_while(|ch: &char| ch.is_ascii_digit())
                .collect();
            digits.parse::<u64>().unwrap_or(0)
        })
        .collect()
}

/// Recursively collects regular files matching `extension` under `root_dir`.
///
/// # Arguments
///
/// - `&Path` - Root directory to traverse.
/// - `&str` - Expected file extension without leading dot.
/// - `&mut Vec<PathBuf>` - Destination list of discovered file paths.
///
/// # Returns
///
/// - `io::Result<()>` - Directory traversal outcome.
fn collect_files_with_extension(
    root_dir: &Path,
    extension: &str,
    out: &mut Vec<PathBuf>,
) -> io::Result<()> {
    for entry_res in fs::read_dir(root_dir)? {
        let entry: DirEntry = entry_res?;
        let entry_path: PathBuf = entry.path();
        if entry_path.is_dir() {
            collect_files_with_extension(&entry_path, extension, out)?;
        } else if entry_path.extension().and_then(OsStr::to_str) == Some(extension) {
            out.push(entry_path);
        }
    }
    Ok(())
}

/// Removes a regular file if it currently exists on disk.
///
/// # Arguments
///
/// - `&Path` - File path to remove when present.
///
/// # Returns
///
/// - `io::Result<()>` - Removal outcome.
pub(crate) fn remove_file_if_exists(path: &Path) -> io::Result<()> {
    if path.exists() {
        fs::remove_file(path)?;
    }
    Ok(())
}