oxihuman-cli 0.2.1

Command-line interface for OxiHuman body generation and export
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
// Copyright (C) 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Interactive 7-step wizard for building `.oxp` asset packs.
//!
//! All I/O is injected via generic `BufRead` / `Write` parameters so that
//! the full wizard flow can be exercised in unit tests using `std::io::Cursor`
//! and `Vec<u8>` without touching the real terminal.

use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::path::PathBuf;

use anyhow::{ensure, Context, Result};

use oxihuman_core::asset_pack_builder::{
    AssetPackBuilder, AssetPackMeta, MorphPreset, TextureAsset, TextureFormat,
};
use oxihuman_core::policy::{Policy, PolicyProfile};
use oxihuman_core::{csv_row_count, detect_format, parse_csv, ImageFormat};

use crate::commands::pack::partition_by_policy;

// ── Public API ────────────────────────────────────────────────────────────────

/// Entry point for tests / programmatic callers: accepts any `BufRead` +
/// `Write` pair so the wizard can run without a real terminal.
pub fn cmd_pack_wizard_io<R: BufRead, W: Write>(
    args: &[String],
    reader: &mut R,
    writer: &mut W,
) -> Result<()> {
    let strict = args.iter().any(|a| a == "--strict");
    let policy = if strict {
        Policy::new(PolicyProfile::Strict)
    } else {
        Policy::new(PolicyProfile::Standard)
    };

    // ── Step 1: Pack metadata ────────────────────────────────────────────────
    writeln!(writer, "=== OxiHuman Asset Pack Wizard ===").ok();
    writeln!(writer).ok();
    writeln!(writer, "Step 1: Pack metadata").ok();

    let pack_name = prompt_with_default(reader, writer, "Pack name", "my_pack")?;
    let author = prompt_with_default(reader, writer, "Author", "COOLJAPAN OU")?;
    let version = prompt_with_default(reader, writer, "Version", "0.1.0")?;
    let license = prompt_with_default(reader, writer, "License", "Apache-2.0")?;

    // ── Step 2: Targets directory (required) ─────────────────────────────────
    writeln!(writer).ok();
    writeln!(writer, "Step 2: Targets directory (required)").ok();
    let targets_raw = prompt_with_default(reader, writer, "Targets directory", "")?;
    ensure!(!targets_raw.is_empty(), "targets directory is required");
    let targets_dir = PathBuf::from(&targets_raw);
    ensure!(
        targets_dir.exists(),
        "targets directory does not exist: {}",
        targets_dir.display()
    );

    // ── Step 3: Texture directory (optional) ─────────────────────────────────
    writeln!(writer).ok();
    writeln!(
        writer,
        "Step 3: Texture directory (optional, press Enter to skip)"
    )
    .ok();
    let texture_dir = prompt_optional_path(reader, writer, "Texture directory")?;

    // ── Step 4: Preset CSV file (optional) ───────────────────────────────────
    writeln!(writer).ok();
    writeln!(
        writer,
        "Step 4: Preset CSV file (optional, press Enter to skip)"
    )
    .ok();
    let preset_csv = prompt_optional_path(reader, writer, "Preset CSV file")?;

    // ── Step 5: Output path ───────────────────────────────────────────────────
    writeln!(writer).ok();
    writeln!(writer, "Step 5: Output path").ok();
    let output_raw = prompt_with_default(reader, writer, "Output path", "./output.oxp")?;
    let output_path = PathBuf::from(&output_raw);

    // ── Step 6: Build ─────────────────────────────────────────────────────────
    writeln!(writer).ok();
    writeln!(writer, "Step 6: Building pack...").ok();

    let pack_bytes = build_pack_from_wizard(
        &pack_name,
        &author,
        &version,
        &license,
        &targets_dir,
        texture_dir.as_deref(),
        preset_csv.as_deref(),
        &policy,
        writer,
    )?;

    // Write the OXP file.
    if let Some(parent) = output_path.parent() {
        if !parent.as_os_str().is_empty() && !parent.exists() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating output directory: {}", parent.display()))?;
        }
    }
    std::fs::write(&output_path, &pack_bytes)
        .with_context(|| format!("writing pack to: {}", output_path.display()))?;
    writeln!(writer).ok();

    // Generate manifest JSON alongside the output file.
    let manifest_path = {
        let mut p = output_path.clone().into_os_string();
        p.push(".manifest.json");
        PathBuf::from(p)
    };
    let manifest_json = build_manifest_json(
        &pack_name,
        &author,
        &version,
        &license,
        &targets_dir,
        &output_path,
    );
    std::fs::write(&manifest_path, manifest_json.as_bytes())
        .with_context(|| format!("writing manifest to: {}", manifest_path.display()))?;

    // ── Step 7: Done ──────────────────────────────────────────────────────────
    writeln!(writer).ok();
    writeln!(writer, "Done: {}", output_path.display()).ok();

    Ok(())
}

/// Standard entry point that uses the real stdin/stdout.
pub fn cmd_pack_wizard(args: &[String]) -> Result<()> {
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let mut reader = stdin.lock();
    let mut writer = stdout.lock();
    cmd_pack_wizard_io(args, &mut reader, &mut writer)
}

// ── Helper: prompt with default ───────────────────────────────────────────────

/// Print `"<prompt> [<default>]: "`, read a line, and return the trimmed input.
/// If the input is empty the default is returned instead.
pub fn prompt_with_default<R: BufRead, W: Write>(
    reader: &mut R,
    writer: &mut W,
    prompt: &str,
    default: &str,
) -> Result<String> {
    if default.is_empty() {
        write!(writer, "{}: ", prompt).ok();
    } else {
        write!(writer, "{} [{}]: ", prompt, default).ok();
    }
    writer.flush().ok();

    let mut line = String::new();
    reader.read_line(&mut line).context("reading input line")?;

    let trimmed = line.trim().to_string();
    if trimmed.is_empty() {
        Ok(default.to_string())
    } else {
        Ok(trimmed)
    }
}

/// Print an optional-path prompt.  Returns `None` if the user enters nothing.
pub fn prompt_optional_path<R: BufRead, W: Write>(
    reader: &mut R,
    writer: &mut W,
    prompt: &str,
) -> Result<Option<PathBuf>> {
    write!(writer, "{} (optional): ", prompt).ok();
    writer.flush().ok();

    let mut line = String::new();
    reader.read_line(&mut line).context("reading input line")?;

    let trimmed = line.trim();
    if trimmed.is_empty() {
        Ok(None)
    } else {
        Ok(Some(PathBuf::from(trimmed)))
    }
}

// ── Internal build logic ──────────────────────────────────────────────────────

/// Scan `targets_dir` for `.target` files (filtered by `policy`), optionally
/// ingest a `texture_dir` of raster images and a `preset_csv` of morph
/// presets, and build the OXP bytes. Prints progress markers to `writer`.
#[allow(clippy::too_many_arguments)]
fn build_pack_from_wizard<W: Write>(
    pack_name: &str,
    author: &str,
    version: &str,
    license: &str,
    targets_dir: &std::path::Path,
    texture_dir: Option<&std::path::Path>,
    preset_csv: Option<&std::path::Path>,
    policy: &Policy,
    writer: &mut W,
) -> Result<Vec<u8>> {
    let mut builder = AssetPackBuilder::new(pack_name);
    let meta = AssetPackMeta {
        version: version.to_string(),
        author: author.to_string(),
        license: license.to_string(),
        description: format!("Asset pack: {}", pack_name),
        created_at: 0,
    };
    builder.set_meta(meta);

    // ── Targets: scan .target files, filtered by policy ──────────────────────
    let mut entries: Vec<std::fs::DirEntry> = std::fs::read_dir(targets_dir)
        .with_context(|| format!("reading targets dir: {}", targets_dir.display()))?
        .flatten()
        .filter(|e| e.path().extension().map(|x| x == "target").unwrap_or(false))
        .collect();
    entries.sort_by_key(|e| e.path());

    let stems: Vec<String> = entries
        .iter()
        .map(|e| {
            e.path()
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("unknown")
                .to_string()
        })
        .collect();
    let (_allowed, rejected) = partition_by_policy(&stems, policy);
    if !rejected.is_empty() {
        writeln!(
            writer,
            "  {} target(s) rejected by policy: {}",
            rejected.len(),
            rejected.join(", ")
        )
        .ok();
    }

    write!(writer, "  ").ok();
    for (entry, name) in entries.iter().zip(stems.iter()) {
        if !policy.is_target_allowed(name, &[]) {
            continue;
        }
        let path = entry.path();
        let data = std::fs::read(&path)
            .with_context(|| format!("reading target file: {}", path.display()))?;
        builder.add_target(oxihuman_core::asset_pack_builder::TargetDelta {
            name: name.clone(),
            data,
        });
        write!(writer, ".").ok();
        writer.flush().ok();
    }
    writeln!(writer).ok();

    // ── Textures: decode every recognised raster image in texture_dir ────────
    if let Some(td) = texture_dir {
        writeln!(writer, "  scanning textures in {}...", td.display()).ok();
        let mut tex_entries: Vec<std::fs::DirEntry> = std::fs::read_dir(td)
            .with_context(|| format!("reading texture dir: {}", td.display()))?
            .flatten()
            .filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
            .collect();
        tex_entries.sort_by_key(|e| e.path());

        for entry in &tex_entries {
            let path = entry.path();
            let bytes = std::fs::read(&path)
                .with_context(|| format!("reading texture file: {}", path.display()))?;
            let format = detect_format(&bytes);
            let decoded = match format {
                ImageFormat::Png => Some((oxihuman_core::png_decode(&bytes), TextureFormat::Png)),
                ImageFormat::Jpeg => Some((
                    oxihuman_core::jpeg_decode(&bytes)
                        .map_err(|e| oxihuman_core::ImageError::DecodeError(e.to_string())),
                    TextureFormat::Jpeg,
                )),
                ImageFormat::Gif => Some((
                    oxihuman_core::gif_decode(&bytes)
                        .map_err(|e| oxihuman_core::ImageError::DecodeError(e.to_string())),
                    TextureFormat::Png,
                )),
                ImageFormat::Tiff => Some((
                    oxihuman_core::tiff_decode(&bytes)
                        .map_err(|e| oxihuman_core::ImageError::DecodeError(e.to_string())),
                    TextureFormat::Png,
                )),
                ImageFormat::Webp => Some((
                    oxihuman_core::webp_decode(&bytes)
                        .map_err(|e| oxihuman_core::ImageError::DecodeError(e.to_string())),
                    TextureFormat::Png,
                )),
                _ => None,
            };

            let Some((decode_result, tex_format)) = decoded else {
                writeln!(
                    writer,
                    "    skip (unrecognised image format): {}",
                    path.display()
                )
                .ok();
                continue;
            };

            let raw = decode_result
                .with_context(|| format!("decoding texture image: {}", path.display()))?;
            let pixel_count = raw.width * raw.height;
            if pixel_count == 0 || raw.pixels.len() % pixel_count != 0 {
                writeln!(
                    writer,
                    "    skip (inconsistent pixel data): {}",
                    path.display()
                )
                .ok();
                continue;
            }
            let channels = (raw.pixels.len() / pixel_count) as u8;
            if !(1..=4).contains(&channels) {
                writeln!(
                    writer,
                    "    skip (unsupported channel count {}): {}",
                    channels,
                    path.display()
                )
                .ok();
                continue;
            }

            let name = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("texture")
                .to_string();
            let texture = TextureAsset {
                name: name.clone(),
                width: raw.width as u32,
                height: raw.height as u32,
                channels,
                data: raw.pixels,
                format: tex_format,
            };
            builder
                .add_texture(texture)
                .with_context(|| format!("adding texture '{}'", name))?;
            write!(writer, ".").ok();
            writer.flush().ok();
        }
        writeln!(writer).ok();
    }

    // ── Presets: parse preset_csv into MorphPreset entries ────────────────────
    if let Some(csv_path) = preset_csv {
        writeln!(writer, "  parsing presets from {}...", csv_path.display()).ok();
        let csv_text = std::fs::read_to_string(csv_path)
            .with_context(|| format!("reading preset CSV: {}", csv_path.display()))?;
        let table = parse_csv(&csv_text);
        ensure!(
            table.headers.iter().any(|h| h == "name"),
            "preset CSV must have a 'name' column: {}",
            csv_path.display()
        );

        let param_cols: Vec<&str> = table
            .headers
            .iter()
            .map(|h| h.as_str())
            .filter(|h| *h != "name" && *h != "description" && *h != "tags")
            .collect();

        for row in 0..csv_row_count(&table) {
            let name = oxihuman_core::csv_field(&table, row, "name")
                .unwrap_or_default()
                .to_string();
            if name.is_empty() {
                continue;
            }
            let description = oxihuman_core::csv_field(&table, row, "description")
                .unwrap_or_default()
                .to_string();
            let tags: Vec<String> = oxihuman_core::csv_field(&table, row, "tags")
                .unwrap_or_default()
                .split(';')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();

            let mut params: HashMap<String, f64> = HashMap::new();
            for col in &param_cols {
                if let Some(raw) = oxihuman_core::csv_field(&table, row, col) {
                    if let Ok(v) = raw.trim().parse::<f64>() {
                        params.insert((*col).to_string(), v);
                    }
                }
            }

            let preset = MorphPreset {
                name: name.clone(),
                description,
                params,
                tags,
            };
            builder
                .add_preset(preset)
                .with_context(|| format!("adding preset '{}'", name))?;
            write!(writer, ".").ok();
            writer.flush().ok();
        }
        writeln!(writer).ok();
    }

    builder.build()
}

/// Produce a manifest JSON string with pack metadata.
fn build_manifest_json(
    name: &str,
    author: &str,
    version: &str,
    license: &str,
    targets_dir: &std::path::Path,
    output_path: &std::path::Path,
) -> String {
    // Hand-build JSON to avoid adding a serde_json dependency (it's already
    // in the workspace transitively, but we stay within the allowed deps).
    format!(
        "{{\n  \"name\": {},\n  \"author\": {},\n  \"version\": {},\n  \"license\": {},\n  \"targets_dir\": {},\n  \"output_path\": {}\n}}\n",
        json_string(name),
        json_string(author),
        json_string(version),
        json_string(license),
        json_string(&targets_dir.display().to_string()),
        json_string(&output_path.display().to_string()),
    )
}

/// Minimal JSON string escaping for manifest values.
fn json_string(s: &str) -> String {
    let escaped = s
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t");
    format!("\"{}\"", escaped)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    /// Helper: build a simulated input stream from lines.
    fn make_input(lines: &[&str]) -> Cursor<Vec<u8>> {
        let joined = lines.join("\n") + "\n";
        Cursor::new(joined.into_bytes())
    }

    // ── Test 1: Wizard completes successfully ─────────────────────────────────

    #[test]
    fn wizard_completes_ok() -> Result<()> {
        let tmp = std::env::temp_dir().join("oxihuman_wizard_test_ok");
        std::fs::create_dir_all(&tmp)?;

        // Create a dummy .target file so the builder has something to pack.
        let target_file = tmp.join("test_target.target");
        std::fs::write(&target_file, b"1 0.1 0.0 0.0\n")?;

        let output_path = tmp.join("test_output.oxp");

        let input_lines = vec![
            "wizard_pack",                                     // pack name
            "Test Author",                                     // author
            "0.2.0",                                           // version
            "MIT",                                             // license
            tmp.to_str().unwrap_or("/tmp"),                    // targets dir
            "",                                                // texture dir (skip)
            "",                                                // preset CSV (skip)
            output_path.to_str().unwrap_or("/tmp/output.oxp"), // output path
        ];
        let mut reader = make_input(&input_lines);
        let mut writer: Vec<u8> = Vec::new();

        cmd_pack_wizard_io(&[], &mut reader, &mut writer)?;

        assert!(output_path.exists(), "output .oxp file must be created");

        let manifest_path = {
            let mut p = output_path.clone().into_os_string();
            p.push(".manifest.json");
            PathBuf::from(p)
        };
        assert!(manifest_path.exists(), "manifest JSON must be created");

        let output_text = String::from_utf8_lossy(&writer);
        assert!(
            output_text.contains("Done:"),
            "output must contain 'Done:' marker"
        );

        // Cleanup
        let _ = std::fs::remove_file(&target_file);
        let _ = std::fs::remove_file(&output_path);
        let _ = std::fs::remove_file(&manifest_path);

        Ok(())
    }

    // ── Test 2: Rejects nonexistent targets directory ─────────────────────────

    #[test]
    fn wizard_rejects_nonexistent_targets_dir() {
        let nonexistent = "/tmp/oxihuman_wizard_definitely_does_not_exist_12345";

        let input_lines = vec![
            "my_pack", // pack name
            "COOLJAPAN OU",
            "0.1.0",
            "Apache-2.0",
            nonexistent, // targets dir — does not exist
        ];
        let mut reader = make_input(&input_lines);
        let mut writer: Vec<u8> = Vec::new();

        let result = cmd_pack_wizard_io(&[], &mut reader, &mut writer);
        assert!(
            result.is_err(),
            "wizard must return Err for nonexistent targets dir"
        );
    }

    // ── Test 3: Uses defaults on all-empty input ──────────────────────────────

    #[test]
    fn wizard_uses_defaults_on_empty_input() -> Result<()> {
        let tmp = std::env::temp_dir().join("oxihuman_wizard_test_defaults");
        std::fs::create_dir_all(&tmp)?;

        // No .target files — empty directory is fine, builder will still build.
        let output_path = tmp.join("output.oxp");

        // All metadata fields are empty → defaults should kick in.
        // Targets dir must be provided (required), output is also provided.
        let input_lines = vec![
            "",                                                // pack name → "my_pack"
            "",                                                // author   → "COOLJAPAN OU"
            "",                                                // version  → "0.1.0"
            "",                                                // license  → "Apache-2.0"
            tmp.to_str().unwrap_or("/tmp"),                    // targets dir (required, must exist)
            "",                                                // texture dir → None
            "",                                                // preset CSV  → None
            output_path.to_str().unwrap_or("/tmp/output.oxp"), // output path
        ];
        let mut reader = make_input(&input_lines);
        let mut writer: Vec<u8> = Vec::new();

        cmd_pack_wizard_io(&[], &mut reader, &mut writer)?;

        // Verify the manifest JSON contains the default values.
        let manifest_path = {
            let mut p = output_path.clone().into_os_string();
            p.push(".manifest.json");
            PathBuf::from(p)
        };
        assert!(manifest_path.exists(), "manifest must be created");
        let manifest_content = std::fs::read_to_string(&manifest_path)?;
        assert!(
            manifest_content.contains("my_pack"),
            "manifest must contain default pack name 'my_pack'"
        );
        assert!(
            manifest_content.contains("COOLJAPAN OU"),
            "manifest must contain default author 'COOLJAPAN OU'"
        );
        assert!(
            manifest_content.contains("0.1.0"),
            "manifest must contain default version '0.1.0'"
        );
        assert!(
            manifest_content.contains("Apache-2.0"),
            "manifest must contain default license 'Apache-2.0'"
        );

        // Cleanup
        let _ = std::fs::remove_file(&output_path);
        let _ = std::fs::remove_file(&manifest_path);

        Ok(())
    }

    // ── Test 4: texture-dir and preset-CSV inputs are actually wired in ──────

    #[test]
    fn wizard_ingests_textures_and_presets() -> Result<()> {
        use oxihuman_core::asset_pack_builder::load_pack_from_bytes;
        use oxihuman_core::png_encode_rgb;

        let tmp = std::env::temp_dir().join(format!(
            "oxihuman_wizard_test_textures_presets_{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&tmp)?;

        let targets_dir = tmp.join("targets");
        std::fs::create_dir_all(&targets_dir)?;
        std::fs::write(targets_dir.join("height-up.target"), b"1 0.1 0.0 0.0\n")?;

        // A tiny 2x2 RGB PNG.
        let texture_dir = tmp.join("textures");
        std::fs::create_dir_all(&texture_dir)?;
        let pixels: Vec<u8> = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0];
        let png_bytes = png_encode_rgb(2, 2, &pixels).context("encoding test PNG")?;
        std::fs::write(texture_dir.join("skin_albedo.png"), &png_bytes)?;

        // A 2-row preset CSV with one numeric param column.
        let preset_csv = tmp.join("presets.csv");
        std::fs::write(
            &preset_csv,
            "name,description,tags,height\nTall,Above average,body;height,1.5\nShort,Below average,body,0.5\n",
        )?;

        let output_path = tmp.join("bundle.oxp");
        let input_lines = vec![
            "textured_pack",
            "COOLJAPAN OU",
            "0.1.0",
            "Apache-2.0",
            targets_dir.to_str().unwrap_or_default(),
            texture_dir.to_str().unwrap_or_default(),
            preset_csv.to_str().unwrap_or_default(),
            output_path.to_str().unwrap_or_default(),
        ];
        let mut reader = make_input(&input_lines);
        let mut writer: Vec<u8> = Vec::new();

        cmd_pack_wizard_io(&[], &mut reader, &mut writer)?;

        let pack_bytes = std::fs::read(&output_path)?;
        let index = load_pack_from_bytes(&pack_bytes).context("loading built pack")?;

        assert_eq!(index.textures.len(), 1, "one texture must be ingested");
        assert_eq!(index.textures[0].name, "skin_albedo");
        assert_eq!(index.textures[0].width, 2);
        assert_eq!(index.textures[0].height, 2);

        assert_eq!(
            index.presets.len(),
            2,
            "both preset CSV rows must be ingested"
        );
        let tall = index
            .presets
            .iter()
            .find(|p| p.name == "Tall")
            .expect("Tall preset must exist");
        assert!((tall.params.get("height").copied().unwrap_or(0.0) - 1.5).abs() < 1e-9);
        assert!(tall.tags.contains(&"height".to_string()));

        assert!(
            index.target_names.iter().any(|n| n == "height-up"),
            "target must still be ingested alongside textures/presets"
        );

        let _ = std::fs::remove_dir_all(&tmp);
        Ok(())
    }

    // ── Test 5: policy gate rejects blocked-tag target names ──────────────────

    #[test]
    fn wizard_filters_blocked_targets_by_policy() -> Result<()> {
        use oxihuman_core::asset_pack_builder::load_pack_from_bytes;

        let tmp = std::env::temp_dir().join(format!(
            "oxihuman_wizard_test_policy_{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&tmp)?;
        std::fs::write(tmp.join("height-up.target"), b"1 0.1 0.0 0.0\n")?;
        std::fs::write(tmp.join("explicit-pose.target"), b"1 0.1 0.0 0.0\n")?;

        let output_path = tmp.join("filtered.oxp");
        let input_lines = vec![
            "policy_pack",
            "COOLJAPAN OU",
            "0.1.0",
            "Apache-2.0",
            tmp.to_str().unwrap_or_default(),
            "",
            "",
            output_path.to_str().unwrap_or_default(),
        ];
        let mut reader = make_input(&input_lines);
        let mut writer: Vec<u8> = Vec::new();

        cmd_pack_wizard_io(&[], &mut reader, &mut writer)?;

        let pack_bytes = std::fs::read(&output_path)?;
        let index = load_pack_from_bytes(&pack_bytes).context("loading built pack")?;
        assert!(index.target_names.iter().any(|n| n == "height-up"));
        assert!(
            !index.target_names.iter().any(|n| n == "explicit-pose"),
            "blocked-tag target must be excluded from the pack"
        );

        let output_text = String::from_utf8_lossy(&writer);
        assert!(
            output_text.contains("rejected by policy"),
            "wizard output should note rejected targets"
        );

        let _ = std::fs::remove_dir_all(&tmp);
        Ok(())
    }
}