euv-cli 0.51.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
use super::*;

/// Validates that a Live-Link asset identifier contains only safe ASCII filename characters with zero path traversal.
///
/// # Arguments
///
/// - `&str` - Candidate asset identifier (`{id}`).
///
/// # Returns
///
/// - `io::Result<()>` - `Ok(())` when safe, or `ErrorKind::InvalidInput`.
pub fn validate_blender_asset_id(asset_id: &str) -> io::Result<()> {
    let all_allowed: bool = asset_id.bytes().all(|byte: u8| {
        byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_' || byte == b'.'
    });
    if asset_id.is_empty()
        || asset_id == "."
        || asset_id == ".."
        || asset_id.contains("..")
        || asset_id.contains('/')
        || asset_id.contains('\\')
        || !all_allowed
    {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_BLENDER_INVALID_ASSET_ID}: `{asset_id}`"),
        ));
    }
    Ok(())
}

/// Detects the 3D asset container format from leading magic bytes first, falling back to file extension.
///
/// # Arguments
///
/// - `&Path` - Source file path (for extension fallback).
/// - `&[u8]` - Raw file bytes (may be empty during `--plan` checks).
///
/// # Returns
///
/// - `io::Result<BlenderAssetFormat>` - Recognized asset format or `InvalidInput`.
pub fn detect_blender_asset_format(path: &Path, bytes: &[u8]) -> io::Result<BlenderAssetFormat> {
    if bytes.len() >= 8 && bytes[0..8] == EUV3D_MAGIC {
        return Ok(BlenderAssetFormat::Euv3d);
    }
    if bytes.len() >= 4 && bytes[0..4] == BLENDER_GLB_MAGIC {
        return Ok(BlenderAssetFormat::Glb);
    }
    if bytes.len() >= 7 && &bytes[0..7] == BLEND_MAGIC {
        return Ok(BlenderAssetFormat::Blend);
    }
    if bytes.len() >= 2 && bytes[0..2] == BLENDER_GZIP_MAGIC {
        let is_blend_ext: bool = path
            .extension()
            .and_then(OsStr::to_str)
            .map(|ext: &str| ext.eq_ignore_ascii_case(BLENDER_EXT_BLEND))
            .unwrap_or(false);
        if is_blend_ext {
            return Ok(BlenderAssetFormat::Blend);
        }
    }
    if bytes.len() >= 4 && bytes[0..4] == BLENDER_ZSTD_MAGIC {
        return Ok(BlenderAssetFormat::Blend);
    }
    let ext_lower: String = path
        .extension()
        .and_then(OsStr::to_str)
        .map(str::to_ascii_lowercase)
        .unwrap_or_default();
    match ext_lower.as_str() {
        BLENDER_EXT_BLEND => Ok(BlenderAssetFormat::Blend),
        BLENDER_EXT_GLB => Ok(BlenderAssetFormat::Glb),
        BLENDER_EXT_GLTF => Ok(BlenderAssetFormat::Gltf),
        BLENDER_EXT_EUV3D => Ok(BlenderAssetFormat::Euv3d),
        BLENDER_EXT_OBJ => Ok(BlenderAssetFormat::Obj),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_BLENDER_UNSUPPORTED_FORMAT}: {}", path.display()),
        )),
    }
}

/// Parses a `blender --version` output line (e.g., `"Blender 5.1.0"`) into `(major, minor, patch)`.
///
/// # Arguments
///
/// - `&str` - Raw stdout text emitted by `blender --version`.
///
/// # Returns
///
/// - `Option<(u16, u16, u16)>` - Parsed semantic version triplet if present.
#[must_use]
pub fn parse_blender_version_line(stdout: &str) -> Option<(u16, u16, u16)> {
    for line in stdout.lines() {
        let trimmed: &str = line.trim();
        let Some(rest) = trimmed.strip_prefix(BLENDER_VERSION_PREFIX) else {
            continue;
        };
        let token: &str = rest.split_whitespace().next()?;
        let mut parts: Vec<u16> = Vec::with_capacity(3);
        for piece in token.split('.') {
            let digits: String = piece
                .chars()
                .take_while(|ch: &char| ch.is_ascii_digit())
                .collect();
            if digits.is_empty() {
                break;
            }
            if let Ok(parsed) = digits.parse::<u16>() {
                parts.push(parsed);
            }
        }
        if parts.len() >= 2 {
            let major: u16 = parts[0];
            let minor: u16 = parts[1];
            let patch: u16 = parts.get(2).copied().unwrap_or(0);
            return Some((major, minor, patch));
        }
    }
    None
}

/// Resolves the local Blender executable checking `--blender-bin`, `EUV_BLENDER_BIN`, `PATH`, and OS install paths.
///
/// # Arguments
///
/// - `Option<&Path>` - Optional explicit `--blender-bin` override path.
///
/// # Returns
///
/// - `(Option<PathBuf>, BlenderBinarySource)` - Resolved binary path and discovery origin.
#[must_use]
pub fn resolve_blender_binary(explicit: Option<&Path>) -> (Option<PathBuf>, BlenderBinarySource) {
    if let Some(path) = explicit {
        if path.is_file() {
            return (Some(path.to_path_buf()), BlenderBinarySource::CliFlag);
        }
        return (None, BlenderBinarySource::NotFound);
    }
    if let Ok(env_val) = env::var(ENV_EUV_BLENDER_BIN) {
        let trimmed: &str = env_val.trim();
        if !trimmed.is_empty() {
            let candidate: PathBuf = PathBuf::from(trimmed);
            if candidate.is_file() {
                return (Some(candidate), BlenderBinarySource::EnvVar);
            }
        }
    }
    if let Some(in_path) = find_blender_in_path() {
        return (Some(in_path), BlenderBinarySource::Path);
    }
    if let Some(os_bin) = find_blender_in_os_locations() {
        return (Some(os_bin), BlenderBinarySource::OsInstall);
    }
    (None, BlenderBinarySource::NotFound)
}

/// Searches `PATH` entries for a `blender` (or `blender.exe`) executable.
///
/// # Returns
///
/// - `Option<PathBuf>` - First matching Blender executable on `PATH`.
#[must_use]
fn find_blender_in_path() -> Option<PathBuf> {
    let raw_path: OsString = env::var_os(BLENDER_ENV_PATH)?;
    let names: [&str; 2] = if cfg!(windows) {
        [BLENDER_BIN_WINDOWS, BLENDER_BIN_UNIX]
    } else {
        [BLENDER_BIN_UNIX, BLENDER_BIN_WINDOWS]
    };
    for dir in env::split_paths(&raw_path) {
        for name in names {
            let candidate: PathBuf = dir.join(name);
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    None
}

/// Searches standard macOS, Windows, and Linux Blender application installation directories.
///
/// # Returns
///
/// - `Option<PathBuf>` - Detected OS-installed Blender binary, preferring newest version.
#[must_use]
fn find_blender_in_os_locations() -> Option<PathBuf> {
    if cfg!(target_os = "macos") {
        let sys_app: PathBuf = PathBuf::from(BLENDER_MACOS_APP_BIN);
        if sys_app.is_file() {
            return Some(sys_app);
        }
        if let Ok(home) = env::var(BLENDER_ENV_HOME) {
            let user_app: PathBuf = PathBuf::from(home).join(BLENDER_MACOS_HOME_APP_REL);
            if user_app.is_file() {
                return Some(user_app);
            }
        }
    }
    if cfg!(windows)
        && let Ok(program_files) = env::var(BLENDER_ENV_PROGRAM_FILES)
    {
        let foundation_dir: PathBuf =
            PathBuf::from(program_files).join(BLENDER_WINDOWS_FOUNDATION_DIR);
        if let Ok(entries) = fs::read_dir(&foundation_dir) {
            let mut candidates: Vec<PathBuf> = Vec::new();
            for entry in entries.flatten() {
                let exe: PathBuf = entry.path().join(BLENDER_BIN_WINDOWS);
                if exe.is_file() {
                    candidates.push(exe);
                }
            }
            candidates.sort();
            if let Some(latest) = candidates.pop() {
                return Some(latest);
            }
        }
    }
    for linux_path in BLENDER_LINUX_CANDIDATE_BINS {
        let candidate: PathBuf = PathBuf::from(linux_path);
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    None
}

/// Locates standard Blender user add-on directories (`scripts/addons`) on the current host.
///
/// # Returns
///
/// - `Vec<PathBuf>` - Ordered list of existing Blender user add-on directories (newest version first).
#[must_use]
pub fn discover_blender_addon_dirs() -> Vec<PathBuf> {
    let mut config_roots: Vec<PathBuf> = Vec::new();
    if cfg!(target_os = "macos")
        && let Ok(home) = env::var(BLENDER_ENV_HOME)
    {
        config_roots.push(PathBuf::from(home).join(BLENDER_MACOS_CONFIG_REL));
    } else if cfg!(windows)
        && let Ok(appdata) = env::var(BLENDER_ENV_APPDATA)
    {
        config_roots.push(
            PathBuf::from(appdata)
                .join(BLENDER_WINDOWS_FOUNDATION_DIR)
                .join(BLENDER_BIN_UNIX),
        );
    } else if let Ok(home) = env::var(BLENDER_ENV_HOME) {
        config_roots.push(PathBuf::from(home).join(BLENDER_LINUX_CONFIG_REL));
    }
    let mut addon_dirs: Vec<PathBuf> = Vec::new();
    for root in config_roots.into_iter() {
        let Ok(entries) = fs::read_dir(&root) else {
            continue;
        };
        let mut versions: Vec<PathBuf> = Vec::new();
        for entry in entries.flatten() {
            let path: PathBuf = entry.path();
            if path.is_dir() {
                versions.push(path);
            }
        }
        versions.sort();
        versions.reverse();
        for version_dir in versions.into_iter() {
            addon_dirs.push(version_dir.join(BLENDER_ADDONS_REL));
        }
    }
    addon_dirs
}

/// Probes whether a TCP listener (such as the Blender Lab MCP bridge) is accepting connections on `127.0.0.1:<port>`.
///
/// # Arguments
///
/// - `u16` - Localhost TCP port to probe.
///
/// # Returns
///
/// - `bool` - `true` when TCP handshake succeeds within the bounded timeout.
#[must_use]
pub fn probe_localhost_tcp_port(port: u16) -> bool {
    if port == 0 {
        return false;
    }
    let addr: SocketAddr = SocketAddr::from(([127, 0, 0, 1], port));
    TcpStream::connect_timeout(&addr, Duration::from_millis(BLENDER_MCP_PROBE_TIMEOUT_MS)).is_ok()
}

/// Runs `euv blender doctor`, checking Blender binary, version, glTF exporter readiness, Live-Link add-on, and MCP reachability.
///
/// # Arguments
///
/// - `&BlenderDoctorConfig` - Optional binary override, MCP port, and glTF probe toggle.
///
/// # Returns
///
/// - `BlenderDoctorReport` - Structured host readiness report.
#[must_use]
pub fn detect_blender_doctor(config: &BlenderDoctorConfig) -> BlenderDoctorReport {
    let (resolved_bin, binary_source): (Option<PathBuf>, BlenderBinarySource) =
        resolve_blender_binary(config.try_get_blender_bin().as_deref());
    let mut version_raw: Option<String> = None;
    let mut version_major: Option<u16> = None;
    let mut version_minor: Option<u16> = None;
    let mut version_patch: Option<u16> = None;
    let mut gltf_exporter_ready: bool = false;
    if let Some(bin_path) = resolved_bin.as_ref() {
        if let Ok(out) = Command::new(bin_path)
            .arg(BLENDER_ARG_VERSION)
            .stdin(Stdio::null())
            .output()
            && out.status.success()
        {
            let text: String = String::from_utf8_lossy(&out.stdout).into_owned();
            if let Some(first_line) = text.lines().next() {
                version_raw = Some(first_line.trim().to_string());
            }
            if let Some((maj, min, pat)) = parse_blender_version_line(&text) {
                version_major = Some(maj);
                version_minor = Some(min);
                version_patch = Some(pat);
            }
        }
        if config.get_probe_gltf_exporter()
            && let Ok(out) = Command::new(bin_path)
                .args([
                    BLENDER_ARG_BACKGROUND,
                    BLENDER_ARG_PYTHON_EXPR,
                    BLENDER_PROBE_GLTF_EXPR,
                ])
                .stdin(Stdio::null())
                .output()
            && out.status.success()
        {
            let text: String = String::from_utf8_lossy(&out.stdout).into_owned();
            gltf_exporter_ready = text.contains(BLENDER_GLTF_READY_MARKER);
        }
    }
    let supports_gltf_exporter: bool = version_major
        .map(|maj: u16| maj >= BLENDER_MIN_GLTF_MAJOR)
        .unwrap_or(false);
    let supports_blender_mcp_version: bool = match (version_major, version_minor) {
        (Some(maj), Some(min)) => {
            maj > BLENDER_MCP_MIN_MAJOR
                || (maj == BLENDER_MCP_MIN_MAJOR && min >= BLENDER_MCP_MIN_MINOR)
        }
        _ => false,
    };
    let addon_dirs: Vec<PathBuf> = discover_blender_addon_dirs();
    let live_link_addon_path: Option<String> = addon_dirs
        .iter()
        .map(|dir: &PathBuf| dir.join(BLENDER_LIVE_LINK_ADDON_FILENAME))
        .find(|candidate: &PathBuf| candidate.is_file())
        .map(|found: PathBuf| found.display().to_string());
    let live_link_addon_installed: bool = live_link_addon_path.is_some();
    let mcp_port: u16 = config.get_mcp_port();
    let mcp_reachable: bool = probe_localhost_tcp_port(mcp_port);
    let mut hints: Vec<String> = Vec::new();
    if resolved_bin.is_none() {
        hints.push(format!(
            "Install Blender 4.0+/5.1+ or set {ENV_EUV_BLENDER_BIN}=/path/to/blender (native .blend/.glb/.euv3d inspection works without Blender)"
        ));
    } else if !supports_gltf_exporter {
        hints.push(
            "Upgrade Blender to 4.0+ (5.1+ recommended) for Principled BSDF glTF 2.0 export"
                .to_string(),
        );
    }
    if !live_link_addon_installed {
        hints.push(format!(
            "Run `euv blender addon-install` to generate `{BLENDER_LIVE_LINK_ADDON_FILENAME}` for 50ms Live-Link sync on port {DEFAULT_BLENDER_SYNC_PORT}"
        ));
    }
    if !mcp_reachable {
        hints.push(format!(
            "Blender Lab MCP bridge not detected on 127.0.0.1:{mcp_port}; enable the official MCP add-on in Blender 5.1+ if AI scene editing is desired"
        ));
    }
    BlenderDoctorReport {
        blender_found: resolved_bin.is_some(),
        blender_path: resolved_bin.map(|p: PathBuf| p.display().to_string()),
        binary_source,
        version_raw,
        version_major,
        version_minor,
        version_patch,
        supports_gltf_exporter,
        gltf_exporter_ready,
        supports_blender_mcp_version,
        live_link_addon_installed,
        live_link_addon_path,
        live_sync_default_port: DEFAULT_BLENDER_SYNC_PORT,
        mcp_port,
        mcp_reachable,
        hints,
    }
}

/// Formats a `BlenderDoctorReport` into concise terminal diagnostics.
///
/// # Arguments
///
/// - `&BlenderDoctorReport` - Collected Blender toolchain report.
///
/// # Returns
///
/// - `String` - Multi-line human-readable report.
#[must_use]
pub fn format_blender_doctor_report(report: &BlenderDoctorReport) -> String {
    let bin_line: &str = report
        .try_get_blender_path()
        .as_deref()
        .unwrap_or(BLENDER_STATUS_MISSING);
    let ver_line: &str = report
        .try_get_version_raw()
        .as_deref()
        .unwrap_or(BLENDER_STATUS_MISSING);
    let gltf_mark: &str = if report.get_gltf_exporter_ready() {
        BLENDER_STATUS_OK
    } else {
        BLENDER_STATUS_MISSING
    };
    let addon_mark: &str = if report.get_live_link_addon_installed() {
        BLENDER_STATUS_OK
    } else {
        BLENDER_STATUS_MISSING
    };
    let mcp_mark: &str = if report.get_mcp_reachable() {
        BLENDER_STATUS_OK
    } else {
        BLENDER_STATUS_MISSING
    };
    let mut out: String = format!(
        "blender: {} [source={}]\nversion: {}\ngltf-exporter: [{}] (4.0+ supported={})\nlive-link-addon: [{}] (default sync port={})\nblender-mcp (127.0.0.1:{}): [{}] (5.1+ supported={})\n",
        bin_line,
        report.get_binary_source().as_str(),
        ver_line,
        gltf_mark,
        report.get_supports_gltf_exporter(),
        addon_mark,
        report.get_live_sync_default_port(),
        report.get_mcp_port(),
        mcp_mark,
        report.get_supports_blender_mcp_version(),
    );
    if !report.get_hints().is_empty() {
        out.push_str("hints:\n");
        for hint in report.get_hints().iter() {
            out.push_str(&format!("  - {hint}\n"));
        }
    }
    out
}

/// Maps an `Euv3dSectionKind` discriminant to a stable lowercase section label.
///
/// # Arguments
///
/// - `Euv3dSectionKind` - Decoded `.euv3d` section kind.
///
/// # Returns
///
/// - `&'static str` - Snake-case section label.
#[must_use]
fn section_kind_label(kind: Euv3dSectionKind) -> &'static str {
    match kind {
        Euv3dSectionKind::SceneMetadataJson => SECTION_LABEL_METADATA,
        Euv3dSectionKind::Vertices => SECTION_LABEL_VERTICES,
        Euv3dSectionKind::Indices => SECTION_LABEL_INDICES,
        Euv3dSectionKind::SkinInfluences => SECTION_LABEL_SKINS,
        Euv3dSectionKind::MorphDeltas => SECTION_LABEL_MORPHS,
        Euv3dSectionKind::Meshlets => SECTION_LABEL_MESHLETS,
        Euv3dSectionKind::LodTable => SECTION_LABEL_LOD_TABLE,
        Euv3dSectionKind::Bvh4Nodes => SECTION_LABEL_BVH4_NODES,
        Euv3dSectionKind::BvhTri4Packets => SECTION_LABEL_BVH_PACKETS,
        Euv3dSectionKind::BvhTriangles => SECTION_LABEL_BVH_TRIANGLES,
        Euv3dSectionKind::AnimationsBlob => SECTION_LABEL_ANIMATIONS,
        Euv3dSectionKind::TexturesBlob => SECTION_LABEL_TEXTURES,
    }
}

/// Converts a parsed Wavefront `ImportedModel3D` (`.obj`) into an `ImportedScene3D` compatible with `.euv3d` baking.
///
/// # Arguments
///
/// - `&ImportedModel3D` - Parsed Wavefront OBJ model bundle.
///
/// # Returns
///
/// - `ImportedScene3D` - Equivalent scene with hierarchy and Principled BSDF materials.
#[must_use]
fn imported_obj_to_scene(model: &ImportedModel3D) -> ImportedScene3D {
    let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
    let mut meshes: Vec<Mesh3D> = Vec::with_capacity(model.get_meshes().len());
    let mut materials: Vec<PrincipledMaterial3D> = Vec::with_capacity(model.get_meshes().len());
    for (idx, chain) in model.get_meshes().iter().enumerate() {
        let Some(base_mesh) = chain.get_levels().first() else {
            continue;
        };
        let mut mesh_copy: Mesh3D = base_mesh.clone();
        let mat_idx: u32 = materials.len() as u32;
        mesh_copy.set_material_index(Some(mat_idx));
        let legacy: PbrMaterial = mesh_copy.get_material();
        let mut principled: PrincipledMaterial3D = PrincipledMaterial3D::default();
        let _: &mut PrincipledMaterial3D = principled
            .set_name(format!("{}_mat_{idx}", mesh_copy.get_name()))
            .set_base_color_factor([
                legacy.get_base_color().get_x(),
                legacy.get_base_color().get_y(),
                legacy.get_base_color().get_z(),
                1.0,
            ])
            .set_metallic_factor(legacy.get_metallic())
            .set_roughness_factor(legacy.get_roughness())
            .set_emissive_factor(legacy.get_emissive().to_array());
        materials.push(principled);
        let mesh_id: u32 = meshes.len() as u32;
        let node_name: String = mesh_copy.get_name().clone();
        meshes.push(mesh_copy);
        let mut node: SceneNode3D = SceneNode3D::from_name(&node_name, None);
        let _: &mut SceneNode3D = node.set_mesh_id(Some(mesh_id));
        let _: u32 = scene_graph.add_node(node);
    }
    let _: usize = scene_graph.propagate_world_matrices();
    let mut scene: ImportedScene3D = ImportedScene3D::default();
    let _: &mut ImportedScene3D = scene
        .set_name(model.get_name().clone())
        .set_generator(BLENDER_OBJ_GENERATOR.to_string())
        .set_scene_graph(scene_graph)
        .set_meshes(meshes)
        .set_materials(materials);
    scene
}

/// Loads a Wavefront `.obj` file (plus sibling `.mtl` when referenced via `mtllib`) into an `ImportedScene3D`.
///
/// # Arguments
///
/// - `&Path` - Path to the `.obj` source file.
/// - `&[u8]` - Raw `.obj` file bytes.
///
/// # Returns
///
/// - `io::Result<ImportedScene3D>` - Converted scene bundle or parse error.
fn load_obj_scene_from_bytes(path: &Path, bytes: &[u8]) -> io::Result<ImportedScene3D> {
    let source: &str =
        from_utf8(bytes).map_err(|err: Utf8Error| Error::new(ErrorKind::InvalidData, err))?;
    let mtl_text: Option<String> = source
        .lines()
        .find_map(|line: &str| line.trim().strip_prefix(OBJ_DIRECTIVE_MTLLIB))
        .and_then(|rel_name: &str| {
            let trimmed: &str = rel_name.trim();
            let base: &Path = path.parent().unwrap_or_else(|| Path::new("."));
            let mtl_path: PathBuf = base.join(trimmed);
            fs::read_to_string(mtl_path).ok()
        })
        .or_else(|| {
            let sibling: PathBuf = path.with_extension(BLENDER_EXT_MTL);
            fs::read_to_string(sibling).ok()
        });
    let model: ImportedModel3D =
        ModelImporter3D::parse_obj_with_mtl(source, mtl_text.as_deref(), PbrMaterial::default())
            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
    Ok(imported_obj_to_scene(&model))
}

/// Inspects a `.blend`, `.glb`, `.gltf`, `.euv3d`, or `.obj` file natively in pure Rust with zero Blender installation required.
///
/// # Arguments
///
/// - `&Path` - Source 3D asset file path.
///
/// # Returns
///
/// - `io::Result<BlenderInspectReport>` - Structured asset inspection report.
pub fn inspect_blender_asset(path: &Path) -> io::Result<BlenderInspectReport> {
    if !path.is_file() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!("{ERR_BLENDER_INPUT_MISSING}: {}", path.display()),
        ));
    }
    let bytes: Vec<u8> = fs::read(path)?;
    let file_bytes: u64 = bytes.len() as u64;
    let format: BlenderAssetFormat = detect_blender_asset_format(path, &bytes)?;
    match format {
        BlenderAssetFormat::Blend => {
            let native: BlendInspectionReport = inspect_blend_bytes(&bytes)
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            Ok(BlenderInspectReport {
                path: path.display().to_string(),
                format,
                file_bytes,
                blend: Some(BlenderNativeBlendSummary::from_blend_report(&native)),
                scene: None,
                euv3d: None,
            })
        }
        BlenderAssetFormat::Glb | BlenderAssetFormat::Gltf => {
            let base_dir: PathBuf = path
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from("."));
            let resolver: DirectoryGltfResolver = DirectoryGltfResolver::from_dir(base_dir);
            let scene: ImportedScene3D = parse_gltf_or_glb_bytes(&bytes, Some(&resolver))
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            Ok(BlenderInspectReport {
                path: path.display().to_string(),
                format,
                file_bytes,
                blend: None,
                scene: Some(BlenderSceneSummary::from_imported_scene(&scene)),
                euv3d: None,
            })
        }
        BlenderAssetFormat::Euv3d => {
            let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(&bytes)
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            let decoded: BakedAssetBundle3D = Euv3dPackage::decode_bytes(&bytes)
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            let header: Euv3dHeader = view.get_header();
            let sections: Vec<BlenderEuv3dSectionSummary> = view
                .get_sections()
                .iter()
                .map(|entry: &Euv3dSectionEntry| {
                    let aligned_64: bool =
                        (entry.get_offset() as usize).is_multiple_of(EUV3D_SECTION_ALIGNMENT);
                    BlenderEuv3dSectionSummary::new(
                        section_kind_label(entry.get_kind()).to_string(),
                        entry.get_offset(),
                        entry.get_byte_length(),
                        entry.get_element_count(),
                        aligned_64,
                    )
                })
                .collect();
            let has_bvh4: bool = view.section_entry(Euv3dSectionKind::Bvh4Nodes).is_some();
            let has_meshlets: bool = view.section_entry(Euv3dSectionKind::Meshlets).is_some();
            let max_lod_levels: usize = decoded
                .get_lod_chains()
                .iter()
                .map(|chain: &MeshLodChain| chain.get_levels().len())
                .max()
                .unwrap_or(0);
            let euv3d_summary: BlenderEuv3dSummary = BlenderEuv3dSummary {
                format_version: header.get_version(),
                content_crc32: header.get_content_crc32(),
                digest_fnv1a: header.get_digest_fnv1a(),
                has_bvh4,
                has_meshlets,
                has_lods: max_lod_levels > 1,
                max_lod_levels,
                bvh_count: decoded.get_local_bvhs().len(),
                sections,
            };
            Ok(BlenderInspectReport {
                path: path.display().to_string(),
                format,
                file_bytes,
                blend: None,
                scene: Some(BlenderSceneSummary::from_imported_scene(
                    decoded.get_scene(),
                )),
                euv3d: Some(euv3d_summary),
            })
        }
        BlenderAssetFormat::Obj => {
            let scene: ImportedScene3D = load_obj_scene_from_bytes(path, &bytes)?;
            Ok(BlenderInspectReport {
                path: path.display().to_string(),
                format,
                file_bytes,
                blend: None,
                scene: Some(BlenderSceneSummary::from_imported_scene(&scene)),
                euv3d: None,
            })
        }
    }
}

/// Formats a `BlenderInspectReport` into concise terminal output.
///
/// # Arguments
///
/// - `&BlenderInspectReport` - Completed asset inspection report.
///
/// # Returns
///
/// - `String` - Multi-line formatted summary.
#[must_use]
pub fn format_blender_inspect_report(report: &BlenderInspectReport) -> String {
    let mut out: String = format!(
        "path: {}\nformat: {}\nsize_bytes: {}\n",
        report.get_path(),
        report.get_format().as_str(),
        report.get_file_bytes(),
    );
    if let Some(blend) = report.try_get_blend() {
        out.push_str(&format!(
            "blender_version: {} (v5_large_header={}, ptr={}B, le={}, compression={})\nblocks: {} (dna_structs={})\nscenes: {} | collections: {} | objects: {} | meshes: {} | materials: {} | cameras: {} | lights: {} | armatures: {} | actions: {}\n",
            blend.get_version(),
            blend.get_is_large_header_v5(),
            blend.get_pointer_size_bytes(),
            blend.get_is_little_endian(),
            blend.get_compression(),
            blend.get_block_count(),
            blend.get_dna_struct_count(),
            blend.get_scenes().len(),
            blend.get_collections().len(),
            blend.get_objects().len(),
            blend.get_meshes().len(),
            blend.get_materials().len(),
            blend.get_cameras().len(),
            blend.get_lights().len(),
            blend.get_armatures().len(),
            blend.get_actions().len(),
        ));
    }
    if let Some(euv3d) = report.try_get_euv3d() {
        out.push_str(&format!(
            "euv3d: v{} crc32=0x{:08x} digest=0x{:016x} lods={} bvh4={} ({}) meshlets={} sections={}\n",
            euv3d.get_format_version(),
            euv3d.get_content_crc32(),
            euv3d.get_digest_fnv1a(),
            euv3d.get_max_lod_levels(),
            euv3d.get_has_bvh4(),
            euv3d.get_bvh_count(),
            euv3d.get_has_meshlets(),
            euv3d.get_sections().len(),
        ));
    }
    if let Some(scene) = report.try_get_scene() {
        out.push_str(&format!(
            "scene: {} (generator={})\nnodes: {} | meshes: {} | vertices: {} | triangles: {} | materials: {} | textures: {} | skins: {} | animations: {} | cameras: {} | lights: {}\n",
            scene.get_name(),
            scene.get_generator(),
            scene.get_node_count(),
            scene.get_mesh_count(),
            scene.get_total_vertices(),
            scene.get_total_triangles(),
            scene.get_material_count(),
            scene.get_texture_count(),
            scene.get_skin_count(),
            scene.get_animation_count(),
            scene.get_camera_count(),
            scene.get_light_count(),
        ));
    }
    out
}

/// Builds the headless Blender CLI argument vector used to convert a `.blend` file to `.glb`.
///
/// # Arguments
///
/// - `&Path` - Resolved Blender executable path.
/// - `&Path` - Source `.blend` file path.
/// - `&Path` - Script file path containing `EXPORT_BLEND_TO_GLB_PY`.
/// - `&Path` - Destination `.glb` output path.
///
/// # Returns
///
/// - `Vec<String>` - Complete argv list `[blender_bin, --background, ...]`.
#[must_use]
pub fn build_headless_blend_export_argv(
    blender_bin: &Path,
    blend_input: &Path,
    script_path: &Path,
    glb_output: &Path,
) -> Vec<String> {
    vec![
        blender_bin.display().to_string(),
        BLENDER_ARG_BACKGROUND.to_string(),
        blend_input.display().to_string(),
        BLENDER_ARG_PYTHON.to_string(),
        script_path.display().to_string(),
        BLENDER_ARG_SEP.to_string(),
        glb_output.display().to_string(),
    ]
}

/// Exports a `.blend` file to `.glb` by executing embedded `EXPORT_BLEND_TO_GLB_PY` inside headless Blender.
///
/// # Arguments
///
/// - `&Path` - Source `.blend` file path.
/// - `&Path` - Destination `.glb` output file path.
/// - `Option<&Path>` - Optional explicit Blender binary override.
///
/// # Returns
///
/// - `io::Result<Vec<String>>` - Executed command argv on success, or descriptive I/O error.
pub fn export_blend_file_to_glb(
    blend_input: &Path,
    glb_output: &Path,
    explicit_blender_bin: Option<&Path>,
) -> io::Result<Vec<String>> {
    let (resolved_bin, _): (Option<PathBuf>, BlenderBinarySource) =
        resolve_blender_binary(explicit_blender_bin);
    let Some(blender_bin) = resolved_bin else {
        return Err(Error::new(ErrorKind::NotFound, ERR_BLENDER_BINARY_MISSING));
    };
    if let Some(parent) = glb_output.parent() {
        fs::create_dir_all(parent)?;
    }
    let seq: u64 = BLENDER_TMP_SCRIPT_SEQ.fetch_add(1, Ordering::Relaxed);
    let script_path: PathBuf = env::temp_dir().join(format!(
        "{BLENDER_EXPORT_SCRIPT_PREFIX}_{}_{seq}.py",
        process::id()
    ));
    fs::write(&script_path, EXPORT_BLEND_TO_GLB_PY)?;
    let argv: Vec<String> =
        build_headless_blend_export_argv(&blender_bin, blend_input, &script_path, glb_output);
    let result: io::Result<Output> = Command::new(&blender_bin)
        .args(&argv[1..])
        .stdin(Stdio::null())
        .output();
    let _: io::Result<()> = fs::remove_file(&script_path);
    let output: Output = result?;
    if !output.status.success() || !glb_output.is_file() {
        let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
        let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
        return Err(Error::other(format!(
            "{ERR_BLENDER_EXPORT_FAILED}: stderr={stderr} stdout={stdout}"
        )));
    }
    Ok(argv)
}

/// Loads any supported source file (`.blend`, `.glb`, `.gltf`, `.obj`, `.euv3d`) into an `ImportedScene3D`.
///
/// # Arguments
///
/// - `&Path` - Source 3D asset path.
/// - `Option<&Path>` - Optional explicit Blender binary override for `.blend` files.
///
/// # Returns
///
/// - `io::Result<(BlenderAssetFormat, ImportedScene3D, Vec<String>, u64)>` - Format, imported scene, optional Blender argv, and input size in bytes.
fn load_scene_for_pipeline(
    input: &Path,
    explicit_blender_bin: Option<&Path>,
) -> io::Result<(BlenderAssetFormat, ImportedScene3D, Vec<String>, u64)> {
    if !input.is_file() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!("{ERR_BLENDER_INPUT_MISSING}: {}", input.display()),
        ));
    }
    let raw_bytes: Vec<u8> = fs::read(input)?;
    let input_bytes: u64 = raw_bytes.len() as u64;
    let format: BlenderAssetFormat = detect_blender_asset_format(input, &raw_bytes)?;
    match format {
        BlenderAssetFormat::Blend => {
            let seq: u64 = BLENDER_TMP_SCRIPT_SEQ.fetch_add(1, Ordering::Relaxed);
            let tmp_glb: PathBuf = env::temp_dir().join(format!(
                "euv_blender_stage_{}_{seq}.{BLENDER_EXT_GLB}",
                process::id()
            ));
            let argv: Vec<String> =
                export_blend_file_to_glb(input, &tmp_glb, explicit_blender_bin)?;
            let glb_bytes: Vec<u8> = fs::read(&tmp_glb)?;
            let _: io::Result<()> = fs::remove_file(&tmp_glb);
            let scene: ImportedScene3D = parse_gltf_or_glb_bytes(&glb_bytes, None)
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            Ok((format, scene, argv, input_bytes))
        }
        BlenderAssetFormat::Glb | BlenderAssetFormat::Gltf => {
            let base_dir: PathBuf = input
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from("."));
            let resolver: DirectoryGltfResolver = DirectoryGltfResolver::from_dir(base_dir);
            let scene: ImportedScene3D = parse_gltf_or_glb_bytes(&raw_bytes, Some(&resolver))
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            Ok((format, scene, Vec::new(), input_bytes))
        }
        BlenderAssetFormat::Obj => {
            let scene: ImportedScene3D = load_obj_scene_from_bytes(input, &raw_bytes)?;
            Ok((format, scene, Vec::new(), input_bytes))
        }
        BlenderAssetFormat::Euv3d => {
            let decoded: BakedAssetBundle3D = Euv3dPackage::decode_bytes(&raw_bytes)
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            Ok((format, decoded.get_scene().clone(), Vec::new(), input_bytes))
        }
    }
}

/// Replaces non-finite float fields (such as default `f32::INFINITY` `attenuation_distance` on materials without `KHR_materials_volume`) with finite bounds so JSON `.euv3d` metadata round-trips cleanly.
///
/// # Arguments
///
/// - `&mut ImportedScene3D` - Imported scene about to be baked into `.euv3d`.
fn sanitize_scene_for_euv3d_bake(scene: &mut ImportedScene3D) {
    for mat in scene.get_mut_materials().iter_mut() {
        if !mat.get_attenuation_distance().is_finite() {
            let _: &mut PrincipledMaterial3D = mat.set_attenuation_distance(1.0e9);
        }
    }
}

/// Imports a `.blend`, `.glb`, `.gltf`, or `.obj` asset into `--out <dir>`, generating `asset-manifest.json` and optional `.euv3d`.
///
/// # Arguments
///
/// - `&BlenderImportConfig` - Input path, output directory, optional Blender binary, and bake flags.
///
/// # Returns
///
/// - `io::Result<BlenderImportReport>` - Structured import report or error.
pub fn import_blender_asset(config: &BlenderImportConfig) -> io::Result<BlenderImportReport> {
    let started: Instant = Instant::now();
    let input: &Path = config.get_input();
    let out_dir: &Path = config.get_out_dir();
    let stem: String = input
        .file_stem()
        .and_then(OsStr::to_str)
        .filter(|name: &&str| !name.is_empty())
        .unwrap_or(BLENDER_DEFAULT_ASSET_STEM)
        .to_string();
    let preview_bytes: Vec<u8> = if input.is_file() {
        fs::read(input)?
    } else if config.get_plan() {
        Vec::new()
    } else {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!("{ERR_BLENDER_INPUT_MISSING}: {}", input.display()),
        ));
    };
    let input_format: BlenderAssetFormat = detect_blender_asset_format(input, &preview_bytes)?;
    if config.get_plan() {
        let planned_glb: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_GLB}"));
        let planned_cmd: Vec<String> = if input_format == BlenderAssetFormat::Blend {
            let bin_ref: PathBuf = resolve_blender_binary(config.try_get_blender_bin().as_deref())
                .0
                .unwrap_or_else(|| PathBuf::from(BLENDER_BIN_UNIX));
            build_headless_blend_export_argv(
                &bin_ref,
                input,
                Path::new(BLENDER_EXPORT_SCRIPT_PREFIX),
                &planned_glb,
            )
        } else {
            Vec::new()
        };
        let baked_path: Option<String> = if config.get_bake() {
            Some(
                out_dir
                    .join(format!("{stem}.{BLENDER_EXT_EUV3D}"))
                    .display()
                    .to_string(),
            )
        } else {
            None
        };
        return Ok(BlenderImportReport {
            input_path: input.display().to_string(),
            input_format,
            out_dir: out_dir.display().to_string(),
            asset_output_path: Some(planned_glb.display().to_string()),
            baked_euv3d_path: baked_path,
            manifest_path: Some(
                out_dir
                    .join(BLENDER_IMPORT_MANIFEST_FILE)
                    .display()
                    .to_string(),
            ),
            planned_command: planned_cmd,
            scene: None,
            elapsed_ms: started.elapsed().as_millis() as u64,
        });
    }
    fs::create_dir_all(out_dir)?;
    let (asset_output_path, mut scene, planned_command): (PathBuf, ImportedScene3D, Vec<String>) =
        if input_format == BlenderAssetFormat::Blend {
            let glb_out: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_GLB}"));
            let argv: Vec<String> =
                export_blend_file_to_glb(input, &glb_out, config.try_get_blender_bin().as_deref())?;
            let glb_bytes: Vec<u8> = fs::read(&glb_out)?;
            let parsed_scene: ImportedScene3D = parse_gltf_or_glb_bytes(&glb_bytes, None)
                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
            (glb_out, parsed_scene, argv)
        } else {
            let (_, parsed_scene, argv, _): (
                BlenderAssetFormat,
                ImportedScene3D,
                Vec<String>,
                u64,
            ) = load_scene_for_pipeline(input, config.try_get_blender_bin().as_deref())?;
            let copied_path: PathBuf = out_dir.join(format!("{stem}.{}", input_format.as_str()));
            atomic_write_synced(&copied_path, &preview_bytes)?;
            (copied_path, parsed_scene, argv)
        };
    let baked_euv3d_path: Option<String> = if config.get_bake() {
        sanitize_scene_for_euv3d_bake(&mut scene);
        let euv3d_out: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_EUV3D}"));
        let mut bake_cfg: Euv3dBakeConfig = Euv3dBakeConfig::default();
        let _: &mut Euv3dBakeConfig = bake_cfg
            .set_lod_levels(config.get_lods().clamp(1, EUV3D_DEFAULT_LOD_LEVELS))
            .set_build_meshlets(config.get_build_meshlets())
            .set_bake_bvh4(config.get_bake_bvh4());
        let euv3d_bytes: Vec<u8> = Euv3dPackage::bake_from_scene(&scene, &bake_cfg)
            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
        let _: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(&euv3d_bytes)
            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
        atomic_write_synced(&euv3d_out, &euv3d_bytes)?;
        Some(euv3d_out.display().to_string())
    } else {
        None
    };
    let scene_summary: BlenderSceneSummary = BlenderSceneSummary::from_imported_scene(&scene);
    let manifest_path: PathBuf = out_dir.join(BLENDER_IMPORT_MANIFEST_FILE);
    let manifest_json: String = to_string_pretty(&scene_summary)
        .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
    atomic_write_synced(&manifest_path, manifest_json.as_bytes())?;
    Ok(BlenderImportReport {
        input_path: input.display().to_string(),
        input_format,
        out_dir: out_dir.display().to_string(),
        asset_output_path: Some(asset_output_path.display().to_string()),
        baked_euv3d_path,
        manifest_path: Some(manifest_path.display().to_string()),
        planned_command,
        scene: Some(scene_summary),
        elapsed_ms: started.elapsed().as_millis() as u64,
    })
}

/// Compiles a `.blend`, `.glb`, `.gltf`, or `.obj` source into a zero-copy 64-byte-aligned `.euv3d` package with QEM LODs, spatial meshlets, and SIMD BVH4.
///
/// # Arguments
///
/// - `&BlenderBakeConfig` - Input path, output `.euv3d` file, LOD depth, meshlet/BVH4 flags, and optional `--plan`.
///
/// # Returns
///
/// - `io::Result<BlenderBakeReport>` - Verified archive metrics and checksum report.
pub fn bake_blender_asset(config: &BlenderBakeConfig) -> io::Result<BlenderBakeReport> {
    let started: Instant = Instant::now();
    let input: &Path = config.get_input();
    let out_file: &Path = config.get_out_file();
    let lods: usize = config.get_lods().clamp(1, EUV3D_DEFAULT_LOD_LEVELS);
    if config.get_plan() {
        let preview: Vec<u8> = if input.is_file() {
            fs::read(input)?
        } else {
            Vec::new()
        };
        let input_format: BlenderAssetFormat = detect_blender_asset_format(input, &preview)?;
        let planned_command: Vec<String> = if input_format == BlenderAssetFormat::Blend {
            let bin_ref: PathBuf = resolve_blender_binary(config.try_get_blender_bin().as_deref())
                .0
                .unwrap_or_else(|| PathBuf::from(BLENDER_BIN_UNIX));
            build_headless_blend_export_argv(
                &bin_ref,
                input,
                Path::new(BLENDER_EXPORT_SCRIPT_PREFIX),
                &out_file.with_extension(BLENDER_EXT_GLB),
            )
        } else {
            Vec::new()
        };
        return Ok(BlenderBakeReport {
            input_path: input.display().to_string(),
            input_format,
            out_file: out_file.display().to_string(),
            input_bytes: preview.len() as u64,
            output_bytes: 0,
            lod_levels: lods,
            meshlets_enabled: config.get_build_meshlets(),
            bvh4_enabled: config.get_bake_bvh4(),
            content_crc32: 0,
            digest_fnv1a: 0,
            section_count: 0,
            scene: None,
            planned_command,
            elapsed_ms: started.elapsed().as_millis() as u64,
        });
    }
    let (input_format, mut scene, planned_command, input_bytes): (
        BlenderAssetFormat,
        ImportedScene3D,
        Vec<String>,
        u64,
    ) = load_scene_for_pipeline(input, config.try_get_blender_bin().as_deref())?;
    sanitize_scene_for_euv3d_bake(&mut scene);
    let mut bake_cfg: Euv3dBakeConfig = Euv3dBakeConfig::default();
    let _: &mut Euv3dBakeConfig = bake_cfg
        .set_lod_levels(lods)
        .set_build_meshlets(config.get_build_meshlets())
        .set_bake_bvh4(config.get_bake_bvh4());
    let euv3d_bytes: Vec<u8> = Euv3dPackage::bake_from_scene(&scene, &bake_cfg)
        .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
    let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(&euv3d_bytes)
        .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
    atomic_write_synced(out_file, &euv3d_bytes)?;
    let header: Euv3dHeader = view.get_header();
    Ok(BlenderBakeReport {
        input_path: input.display().to_string(),
        input_format,
        out_file: out_file.display().to_string(),
        input_bytes,
        output_bytes: euv3d_bytes.len() as u64,
        lod_levels: lods,
        meshlets_enabled: config.get_build_meshlets(),
        bvh4_enabled: config.get_bake_bvh4(),
        content_crc32: header.get_content_crc32(),
        digest_fnv1a: header.get_digest_fnv1a(),
        section_count: view.get_sections().len(),
        scene: Some(BlenderSceneSummary::from_imported_scene(&scene)),
        planned_command,
        elapsed_ms: started.elapsed().as_millis() as u64,
    })
}

/// Emits or installs the embedded `euv_live_link.py` Blender 4.x/5.x add-on.
///
/// # Arguments
///
/// - `&BlenderAddonInstallConfig` - Destination path override or `--print` flag.
///
/// # Returns
///
/// - `io::Result<BlenderAddonInstallReport>` - Written file path, digest, and activation guide.
pub fn install_blender_addon(
    config: &BlenderAddonInstallConfig,
) -> io::Result<BlenderAddonInstallReport> {
    let source_bytes: &[u8] = EUV_LIVE_LINK_ADDON_PY.as_bytes();
    let sha256: String = sha256_hex(source_bytes);
    let instructions: String = format!(
        "In Blender 4.x/5.x: Edit > Preferences > Add-ons > Install from Disk -> select `{BLENDER_LIVE_LINK_ADDON_FILENAME}`, enable 'Euv Live-Link', open View3D Sidebar (N) > Euv, and run `euv blender live-sync --port {DEFAULT_BLENDER_SYNC_PORT}`."
    );
    if config.get_print_only() {
        return Ok(BlenderAddonInstallReport {
            filename: BLENDER_LIVE_LINK_ADDON_FILENAME.to_string(),
            installed_path: None,
            byte_length: source_bytes.len(),
            sha256,
            default_port: DEFAULT_BLENDER_SYNC_PORT,
            instructions,
        });
    }
    let destination: PathBuf = match config.try_get_out() {
        Some(target) => {
            if target.is_dir() {
                target.join(BLENDER_LIVE_LINK_ADDON_FILENAME)
            } else {
                target.to_path_buf()
            }
        }
        None => {
            let dirs: Vec<PathBuf> = discover_blender_addon_dirs();
            if let Some(first_dir) = dirs.first() {
                first_dir.join(BLENDER_LIVE_LINK_ADDON_FILENAME)
            } else {
                PathBuf::from(BLENDER_LIVE_LINK_ADDON_FILENAME)
            }
        }
    };
    atomic_write_synced(&destination, source_bytes)?;
    Ok(BlenderAddonInstallReport {
        filename: BLENDER_LIVE_LINK_ADDON_FILENAME.to_string(),
        installed_path: Some(destination.display().to_string()),
        byte_length: source_bytes.len(),
        sha256,
        default_port: DEFAULT_BLENDER_SYNC_PORT,
        instructions,
    })
}

/// Validates an uploaded Live-Link binary asset payload (`.glb`, `.gltf`, or `.euv3d`) and returns its format and mesh/triangle counts.
///
/// # Arguments
///
/// - `&[u8]` - Raw binary asset bytes received on `POST /blender/asset/{id}`.
///
/// # Returns
///
/// - `io::Result<(BlenderAssetFormat, usize, usize)>` - `(format, mesh_count, triangle_count)` or `InvalidData`.
#[cfg(feature = "update-server")]
pub(crate) fn validate_live_asset_payload(
    bytes: &[u8],
) -> io::Result<(BlenderAssetFormat, usize, usize)> {
    if bytes.len() >= 8 && bytes[0..8] == EUV3D_MAGIC {
        let decoded: BakedAssetBundle3D = Euv3dPackage::decode_bytes(bytes)
            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
        let summary: BlenderSceneSummary =
            BlenderSceneSummary::from_imported_scene(decoded.get_scene());
        return Ok((
            BlenderAssetFormat::Euv3d,
            summary.get_mesh_count(),
            summary.get_total_triangles(),
        ));
    }
    let format: BlenderAssetFormat = if bytes.len() >= 4 && bytes[0..4] == BLENDER_GLB_MAGIC {
        BlenderAssetFormat::Glb
    } else {
        BlenderAssetFormat::Gltf
    };
    let scene: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)
        .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
    let summary: BlenderSceneSummary = BlenderSceneSummary::from_imported_scene(&scene);
    Ok((
        format,
        summary.get_mesh_count(),
        summary.get_total_triangles(),
    ))
}

/// Registers the Blender Live-Link HTTP and SSE routes onto a Hyperlane `Server`.
///
/// # Arguments
///
/// - `&mut Server` - Hyperlane server instance receiving Live-Link routes.
/// - `Arc<BlenderLiveSyncState>` - Shared Live-Link state.
#[cfg(feature = "update-server")]
pub fn register_blender_live_sync_routes(server: &mut Server, state: Arc<BlenderLiveSyncState>) {
    let slot: &RwLock<Option<Arc<BlenderLiveSyncState>>> =
        DEFAULT_BLENDER_LIVE_SYNC_STATE.get_or_init(|| RwLock::new(None));
    if let Ok(mut guard) = slot.write() {
        *guard = Some(state);
    }
    let _: &mut Server = server
        .route::<BlenderDeltaRouteHook>(BLENDER_ROUTE_DELTA)
        .route::<BlenderAssetRouteHook>(BLENDER_ROUTE_ASSET)
        .route::<BlenderEventsRouteHook>(BLENDER_ROUTE_EVENTS)
        .route::<BlenderStatusRouteHook>(BLENDER_ROUTE_STATUS)
        .route::<BlenderStatusRouteHook>(BLENDER_ROUTE_HEALTHZ);
}

/// Starts a live Hyperlane HTTP+SSE Blender Live-Link daemon supporting ephemeral ports (`port == 0`).
///
/// # Arguments
///
/// - `BlenderLiveSyncConfig` - Host, port, optional disk mirror directory, heartbeat, and replay settings.
///
/// # Returns
///
/// - `io::Result<BlenderLiveSyncHandle>` - Active Live-Link server handle.
#[cfg(feature = "update-server")]
pub fn start_blender_live_sync_server(
    config: BlenderLiveSyncConfig,
) -> io::Result<BlenderLiveSyncHandle> {
    if let Some(dir) = config.try_get_out_dir() {
        fs::create_dir_all(dir)?;
    }
    let sse_config: SseConfig = SseConfig::default()
        .with_heartbeat_ms(config.get_heartbeat_ms())
        .with_retry_ms(2_000)
        .with_replay_capacity(config.get_replay_capacity());
    let state: Arc<BlenderLiveSyncState> = Arc::new(BlenderLiveSyncState::new(
        sse_config,
        config.try_get_out_dir().clone(),
        config.get_max_asset_bytes(),
        config.get_replay_capacity(),
    ));
    let runtime_ref: runtime::Runtime = runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()?;
    let max_attempts: usize = if config.get_port() == 0 { 8 } else { 1 };
    let mut last_err: Option<Error> = None;
    let mut bound_pair: Option<(SocketAddr, ServerControlHook)> = None;
    for _ in 0..max_attempts {
        let candidate_addr: SocketAddr =
            resolve_blender_bind_addr(config.get_host(), config.get_port())?;
        register_blender_live_sync_state(candidate_addr, Arc::clone(&state));
        let mut server_cfg: ServerConfig = ServerConfig::default();
        server_cfg.set_address(candidate_addr.to_string());
        let mut server: Server = Server::from(server_cfg);
        register_blender_live_sync_routes(&mut server, Arc::clone(&state));
        match runtime_ref.block_on(async move { server.run().await }) {
            Ok(control) => {
                bound_pair = Some((candidate_addr, control));
                break;
            }
            Err(err) => {
                unregister_blender_live_sync_state(candidate_addr);
                last_err = Some(Error::other(err.to_string()));
            }
        }
    }
    let (resolved_addr, control): (SocketAddr, ServerControlHook) = match bound_pair {
        Some(pair) => pair,
        None => {
            return Err(last_err.unwrap_or_else(|| Error::from(ErrorKind::AddrInUse)));
        }
    };
    Ok(BlenderLiveSyncHandle {
        address: resolved_addr,
        state,
        control: Some(control),
        runtime: Some(runtime_ref),
    })
}

/// Runs the Hyperlane HTTP+SSE Blender Live-Link daemon in blocking CLI mode (or exits immediately when `--once` is set).
///
/// # Arguments
///
/// - `BlenderLiveSyncConfig` - Live-Link bind address, heartbeat, and `--once` flag.
///
/// # Returns
///
/// - `io::Result<BlenderLiveSyncReport>` - Machine-readable server startup report.
#[cfg(feature = "update-server")]
pub fn run_blender_live_sync_blocking(
    config: BlenderLiveSyncConfig,
) -> io::Result<BlenderLiveSyncReport> {
    let once: bool = config.get_once();
    let mut handle: BlenderLiveSyncHandle = start_blender_live_sync_server(config)?;
    let report: BlenderLiveSyncReport = handle.report(once);
    if once {
        handle.shutdown();
        return Ok(report);
    }
    eprintln!(
        "[euv-blender] live-sync listening on {} (delta={} asset={} events={})",
        report.get_url(),
        report.get_delta_url(),
        report.get_asset_url(),
        report.get_events_url(),
    );
    while handle.is_running() {
        thread::sleep(Duration::from_millis(250));
    }
    handle.shutdown();
    Ok(report)
}

/// Returns a clear feature error when `euv blender live-sync` is invoked without the `update-server` feature enabled.
///
/// # Arguments
///
/// - `BlenderLiveSyncConfig` - Unused Live-Link configuration.
///
/// # Returns
///
/// - `io::Result<BlenderLiveSyncReport>` - Always returns `ErrorKind::Unsupported`.
#[cfg(not(feature = "update-server"))]
pub fn run_blender_live_sync_blocking(
    _config: BlenderLiveSyncConfig,
) -> io::Result<BlenderLiveSyncReport> {
    Err(Error::new(
        ErrorKind::Unsupported,
        ERR_BLENDER_LIVE_SYNC_DISABLED,
    ))
}

/// Collects watchable 3D source files (`.blend`, `.glb`, `.gltf`, `.obj`) under a file or directory path.
///
/// # Arguments
///
/// - `&Path` - Watched file or directory root.
///
/// # Returns
///
/// - `io::Result<Vec<PathBuf>>` - Sorted list of source 3D asset paths.
fn collect_watched_blender_sources(root: &Path) -> io::Result<Vec<PathBuf>> {
    if root.is_file() {
        return Ok(vec![root.to_path_buf()]);
    }
    if !root.is_dir() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!("{ERR_BLENDER_INPUT_MISSING}: {}", root.display()),
        ));
    }
    let mut found: Vec<PathBuf> = Vec::new();
    for entry_res in fs::read_dir(root)? {
        let entry: DirEntry = entry_res?;
        let path: PathBuf = entry.path();
        if !path.is_file() {
            continue;
        }
        let ext: String = path
            .extension()
            .and_then(OsStr::to_str)
            .map(str::to_ascii_lowercase)
            .unwrap_or_default();
        let ext_str: &str = ext.as_str();
        let supported: bool = ext_str == BLENDER_EXT_BLEND
            || ext_str == BLENDER_EXT_GLB
            || ext_str == BLENDER_EXT_GLTF
            || ext_str == BLENDER_EXT_OBJ;
        if supported {
            found.push(path);
        }
    }
    found.sort();
    Ok(found)
}

/// Watches a `.blend`/`.glb`/`.gltf`/`.obj` file or directory, compiling `.euv3d` bundles to `--out` and pushing live updates over SSE.
///
/// # Arguments
///
/// - `BlenderWatchConfig` - Watched path, output directory, Live-Link port, poll cadence, and `--once` mode.
///
/// # Returns
///
/// - `io::Result<BlenderWatchReport>` - Summary of baked outputs and Live-Link endpoints.
pub fn run_blender_watch(config: BlenderWatchConfig) -> io::Result<BlenderWatchReport> {
    let watch_path: PathBuf = config.get_path().clone();
    let out_dir: PathBuf = config.get_out_dir().clone();
    fs::create_dir_all(&out_dir)?;
    let initial_sources: Vec<PathBuf> = collect_watched_blender_sources(&watch_path)?;
    #[cfg(feature = "update-server")]
    let mut live_handle: Option<BlenderLiveSyncHandle> = {
        let mut srv_cfg: BlenderLiveSyncConfig = BlenderLiveSyncConfig::default();
        let _: &mut BlenderLiveSyncConfig = srv_cfg
            .set_host(config.get_host().clone())
            .set_port(config.get_port())
            .set_out_dir(Some(out_dir.clone()));
        Some(start_blender_live_sync_server(srv_cfg)?)
    };
    let mut digests: BTreeMap<PathBuf, String> = BTreeMap::new();
    let mut baked_assets: Vec<BlenderBakeReport> = Vec::new();
    for src in initial_sources.iter() {
        let raw: Vec<u8> = fs::read(src)?;
        let digest: String = sha256_hex(&raw);
        let _: Option<String> = digests.insert(src.clone(), digest);
        let stem: String = src
            .file_stem()
            .and_then(OsStr::to_str)
            .filter(|name: &&str| !name.is_empty())
            .unwrap_or(BLENDER_DEFAULT_ASSET_STEM)
            .to_string();
        let out_euv3d: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_EUV3D}"));
        let mut bake_cfg: BlenderBakeConfig = BlenderBakeConfig::default();
        let _: &mut BlenderBakeConfig = bake_cfg
            .set_input(src.clone())
            .set_out_file(out_euv3d.clone())
            .set_blender_bin(config.try_get_blender_bin().clone())
            .set_lods(config.get_lods());
        let report: BlenderBakeReport = bake_blender_asset(&bake_cfg)?;
        #[cfg(feature = "update-server")]
        if let Some(handle) = live_handle.as_ref()
            && let Ok(baked_bytes) = fs::read(&out_euv3d)
        {
            let _: io::Result<BlenderLiveAssetNotice> =
                handle.state().record_asset(&stem, baked_bytes);
        }
        baked_assets.push(report);
    }
    #[cfg(feature = "update-server")]
    let (live_sync_url, events_url): (Option<String>, Option<String>) = live_handle
        .as_ref()
        .map(|handle: &BlenderLiveSyncHandle| {
            let base: String = handle.url();
            let ev: String = format!("{base}{BLENDER_ROUTE_EVENTS}");
            (Some(base), Some(ev))
        })
        .unwrap_or((None, None));
    #[cfg(not(feature = "update-server"))]
    let (live_sync_url, events_url): (Option<String>, Option<String>) = (None, None);
    let report: BlenderWatchReport = BlenderWatchReport {
        watch_path: watch_path.display().to_string(),
        out_dir: out_dir.display().to_string(),
        live_sync_url,
        events_url,
        baked_assets,
        once: config.get_once(),
    };
    if config.get_once() {
        #[cfg(feature = "update-server")]
        if let Some(mut handle) = live_handle.take() {
            handle.shutdown();
        }
        return Ok(report);
    }
    let poll_delay: Duration = Duration::from_millis(config.get_poll_ms().max(50));
    while watch_path.exists() {
        thread::sleep(poll_delay);
        #[cfg(feature = "update-server")]
        if let Some(handle) = live_handle.as_ref()
            && !handle.is_running()
        {
            break;
        }
        let Ok(current_sources) = collect_watched_blender_sources(&watch_path) else {
            continue;
        };
        for src in current_sources.into_iter() {
            let Ok(raw) = fs::read(&src) else {
                continue;
            };
            let next_sha: String = sha256_hex(&raw);
            if digests.get(&src).map(String::as_str) == Some(next_sha.as_str()) {
                continue;
            }
            let stem: String = src
                .file_stem()
                .and_then(OsStr::to_str)
                .filter(|name: &&str| !name.is_empty())
                .unwrap_or(BLENDER_DEFAULT_ASSET_STEM)
                .to_string();
            let out_euv3d: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_EUV3D}"));
            let mut bake_cfg: BlenderBakeConfig = BlenderBakeConfig::default();
            let _: &mut BlenderBakeConfig = bake_cfg
                .set_input(src.clone())
                .set_out_file(out_euv3d.clone())
                .set_blender_bin(config.try_get_blender_bin().clone())
                .set_lods(config.get_lods());
            if let Ok(baked_rep) = bake_blender_asset(&bake_cfg) {
                let _: Option<String> = digests.insert(src, next_sha);
                #[cfg(feature = "update-server")]
                if let Some(handle) = live_handle.as_ref()
                    && let Ok(baked_bytes) = fs::read(&out_euv3d)
                {
                    let _: io::Result<BlenderLiveAssetNotice> =
                        handle.state().record_asset(&stem, baked_bytes);
                }
                eprintln!(
                    "[euv-blender] rebaked {} -> {} ({} bytes)",
                    baked_rep.get_input_path(),
                    baked_rep.get_out_file(),
                    baked_rep.get_output_bytes()
                );
            }
        }
    }
    #[cfg(feature = "update-server")]
    if let Some(mut handle) = live_handle.take() {
        handle.shutdown();
    }
    Ok(report)
}

/// Resolves a concrete bind `SocketAddr`, allocating an ephemeral port when `port == 0`.
///
/// # Arguments
///
/// - `&str` - Host address string.
/// - `u16` - Requested TCP port (`0` allocates an ephemeral port).
///
/// # Returns
///
/// - `io::Result<SocketAddr>` - Resolved concrete socket address.
#[cfg(feature = "update-server")]
fn resolve_blender_bind_addr(host: &str, port: u16) -> io::Result<SocketAddr> {
    if port != 0 {
        let raw: String = format!("{host}:{port}");
        return raw
            .parse::<SocketAddr>()
            .map_err(|err: AddrParseError| Error::new(ErrorKind::InvalidInput, err.to_string()));
    }
    let probe: TcpListener = TcpListener::bind(format!("{host}:0"))?;
    let addr: SocketAddr = probe.local_addr()?;
    drop(probe);
    Ok(addr)
}

/// Registers `state` for `addr` in the per-listener Live-Link server registry.
///
/// # Arguments
///
/// - `SocketAddr` - Bound listener address.
/// - `Arc<BlenderLiveSyncState>` - Shared Live-Link daemon state.
#[cfg(feature = "update-server")]
pub(crate) fn register_blender_live_sync_state(addr: SocketAddr, state: Arc<BlenderLiveSyncState>) {
    let map: &RwLock<HashMap<SocketAddr, Arc<BlenderLiveSyncState>>> =
        BLENDER_LIVE_SYNC_REGISTRY.get_or_init(|| RwLock::new(HashMap::new()));
    if let Ok(mut guard) = map.write() {
        let _: Option<Arc<BlenderLiveSyncState>> = guard.insert(addr, state);
    }
}

/// Removes `addr` from the per-listener Live-Link server registry upon shutdown.
///
/// # Arguments
///
/// - `SocketAddr` - Listener address being closed.
#[cfg(feature = "update-server")]
pub(crate) fn unregister_blender_live_sync_state(addr: SocketAddr) {
    if let Some(map) = BLENDER_LIVE_SYNC_REGISTRY.get()
        && let Ok(mut guard) = map.write()
    {
        let _: Option<Arc<BlenderLiveSyncState>> = guard.remove(&addr);
    }
}

/// Resolves the `BlenderLiveSyncState` associated with the active Hyperlane client `Stream`.
///
/// # Arguments
///
/// - `&Stream` - Active Hyperlane client stream.
///
/// # Returns
///
/// - `Option<Arc<BlenderLiveSyncState>>` - Matching server state if registered.
#[cfg(feature = "update-server")]
pub(crate) fn resolve_blender_live_sync_state(
    stream: &Stream,
) -> Option<Arc<BlenderLiveSyncState>> {
    if let Ok(local_addr) = stream.get_local_addr()
        && let Some(map) = BLENDER_LIVE_SYNC_REGISTRY.get()
        && let Ok(guard) = map.read()
        && let Some(found) = guard.get(&local_addr)
    {
        return Some(Arc::clone(found));
    }
    DEFAULT_BLENDER_LIVE_SYNC_STATE
        .get()
        .and_then(|lock: &RwLock<Option<Arc<BlenderLiveSyncState>>>| lock.read().ok())
        .and_then(|guard: RwLockReadGuard<'_, Option<Arc<BlenderLiveSyncState>>>| guard.clone())
}

/// Streams buffered `Last-Event-ID` replay frames followed by live `blender.delta` and `blender.asset` SSE events.
///
/// # Arguments
///
/// - `&mut Stream` - Active Hyperlane client stream.
/// - `&mut Context` - Active Hyperlane request context.
/// - `Vec<BlenderLiveEventRecord>` - Buffered events strictly newer than `Last-Event-ID`.
/// - `SseSubscription` - Live Hyperlane SSE subscription.
/// - `&SseConfig` - Heartbeat and reconnect configuration.
///
/// # Returns
///
/// - `Result<(), SseError>` - Completes cleanly when the stream closes or disconnects.
#[cfg(feature = "update-server")]
pub(crate) async fn serve_blender_sse_stream(
    stream: &mut Stream,
    ctx: &mut Context,
    replay_events: Vec<BlenderLiveEventRecord>,
    mut subscription: SseSubscription,
    config: &SseConfig,
) -> Result<(), SseError> {
    SseStream::prepare(ctx);
    apply_update_cors_headers(ctx);
    let _: &mut Response = ctx
        .get_mut_response()
        .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE)
        .set_header(BLENDER_HDR_ACCEL_BUFFERING, BLENDER_VAL_NO_BUFFER);
    let head: ResponseData = ctx.get_mut_response().build_head();
    stream
        .try_send(&head)
        .await
        .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
    let mut scratch: Vec<u8> = Vec::with_capacity(256);
    if config.get_retry_ms() > 0 {
        let hint: SseEvent =
            SseEvent::comment_only(BLENDER_SSE_CONNECTED_COMMENT).with_retry(config.get_retry_ms());
        SseStream::send_event_buffered(stream, &hint, &mut scratch).await?;
    }
    let mut last_sent_seq: u64 = 0;
    for rec in replay_events.into_iter() {
        let sse_ev: SseEvent = SseEvent::new(rec.get_json_data().clone())
            .with_id(rec.get_seq().to_string())
            .with_event(rec.get_event_name().clone());
        SseStream::send_event_buffered(stream, &sse_ev, &mut scratch).await?;
        if rec.get_seq() > last_sent_seq {
            last_sent_seq = rec.get_seq();
        }
    }
    let heartbeat_ms: u64 = config.get_heartbeat_ms();
    if heartbeat_ms == 0 {
        loop {
            match subscription.recv().await {
                Ok(event) => {
                    let ev_seq: u64 = event
                        .get_id()
                        .as_deref()
                        .and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
                        .unwrap_or(u64::MAX);
                    if ev_seq <= last_sent_seq {
                        continue;
                    }
                    SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
                    if ev_seq != u64::MAX {
                        last_sent_seq = ev_seq;
                    }
                }
                Err(SseError::Lagged(_)) => continue,
                Err(SseError::ChannelClosed) => return Ok(()),
                Err(err) => return Err(err),
            }
        }
    }
    let heartbeat_frame: Vec<u8> = SseEvent::comment_only(BLENDER_SSE_HEARTBEAT_COMMENT).encode();
    let mut ticker: Interval = interval(Duration::from_millis(heartbeat_ms));
    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
    let _: Instant = ticker.tick().await.into_std();
    loop {
        select! {
            _ = ticker.tick() => {
                stream
                    .try_send(&heartbeat_frame)
                    .await
                    .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
            }
            next = subscription.recv() => {
                match next {
                    Ok(event) => {
                        let ev_seq: u64 = event
                            .get_id()
                            .as_deref()
                            .and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
                            .unwrap_or(u64::MAX);
                        if ev_seq <= last_sent_seq {
                            continue;
                        }
                        SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
                        if ev_seq != u64::MAX {
                            last_sent_seq = ev_seq;
                        }
                    }
                    Err(SseError::Lagged(_)) => continue,
                    Err(SseError::ChannelClosed) => return Ok(()),
                    Err(err) => return Err(err),
                }
            }
        }
    }
}