imferno 1.1.0

Command-line interface for SMPTE ST 2067 IMF packages
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
//! IMF CLI - Command-line tool for inspecting IMF packages

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use imferno_core::package::{Imferno, ValidationOptions};
use imferno_core::validation::{AppSpecTarget, CoreSpecTarget};
use imferno_core::{Category, Severity, ValidationIssue, ValidationProfile, ValidationReport};
use std::io::IsTerminal;
use std::path::PathBuf;

// ── ANSI colour helpers ───────────────────────────────────────────────────────

fn use_color() -> bool {
    std::io::stdout().is_terminal()
        && std::env::var("NO_COLOR").is_err()
        && std::env::var("TERM").map_or(true, |t| t != "dumb")
}

fn c_red(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[31m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_yellow(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[33m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_cyan(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[36m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_green(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[32m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_bold(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[1m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_dim(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[2m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}

#[derive(Parser)]
#[command(name = "imferno")]
#[command(about = "SMPTE ST 2067 IMF validator and inspector", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Inspect an IMF package directory
    Inspect {
        /// Path to the IMF package directory
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Output format
        #[arg(short, long, value_enum, default_value = "summary")]
        format: OutputFormat,
    },

    /// Show detailed CPL information
    Cpl {
        /// Path to the IMF package directory
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// CPL UUID (optional, shows first CPL if not specified)
        #[arg(short, long)]
        uuid: Option<String>,
    },

    /// Validate an IMF package structure
    Validate {
        /// Path to the IMF package directory
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Verify SHA-1 hashes of all assets against PKL (slow — reads every file)
        #[arg(long)]
        verify_hashes: bool,

        /// Output format (summary = human-readable, json = ValidationReport)
        #[arg(short, long, value_enum, default_value = "summary")]
        format: OutputFormat,

        /// Core constraints spec version selection
        #[arg(long, value_enum, default_value = "auto")]
        core_spec: CoreSpecVersion,

        /// Application profile selection (App2E + ST 2067-201 IAB plug-ins)
        #[arg(long, value_enum, default_value = "auto")]
        app2e_spec: App2eSpecVersion,

        /// Skip file manifest (existence/size) and MXF header checks.
        /// Validates XML structure only — useful for packages on slow or remote filesystems
        /// (e.g. S3 via MacFUSE) where disk I/O would be prohibitively slow.
        #[arg(long)]
        xml_only: bool,

        /// Always exit with code 0, even when validation errors are found (useful for CI
        /// pipelines that collect results without failing the build)
        #[arg(long)]
        exit_zero: bool,

        /// Path to a JSON rules config file with ESLint-style severity overrides.
        /// Example: { "SegmentDuration": "warn", "DanglingEssenceDescriptor": "off" }
        #[arg(long, value_name = "PATH")]
        rules_config: Option<PathBuf>,
    },

    /// Export a full report (package metadata + validation + CPL analysis)
    Export {
        /// Path to the IMF package directory
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Path to ancestor IMP directory (for supplemental packages)
        #[arg(long)]
        ancestor: Option<PathBuf>,
    },
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum OutputFormat {
    Summary,
    Json,
    Detailed,
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum CoreSpecVersion {
    Auto,
    V2013,
    V2016,
    V2020,
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum App2eSpecVersion {
    Auto,
    None,
    V2020,
    V2021,
    V2023,
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Inspect { path, format } => {
            inspect_package(&path, format)?;
        }
        Commands::Cpl { path, uuid } => {
            show_cpl(&path, uuid)?;
        }
        Commands::Validate {
            path,
            verify_hashes,
            xml_only,
            format,
            core_spec,
            app2e_spec,
            exit_zero,
            rules_config,
        } => {
            validate_package(
                &path,
                verify_hashes,
                xml_only,
                format,
                core_spec,
                app2e_spec,
                exit_zero,
                rules_config.as_deref(),
            )?;
        }
        Commands::Export { path, ancestor } => {
            generate_report(&path, ancestor.as_deref())?;
        }
    }

    Ok(())
}

fn inspect_package(path: &PathBuf, format: OutputFormat) -> Result<()> {
    let package = Imferno::parse(imferno_core::package::read_dir(path)?)?;
    let inspection = package.inspect();

    match format {
        OutputFormat::Summary => {
            println!("IMF Package: {}", inspection.path.display());
            println!("============");
            println!("Volume Index: {}", inspection.volume_index);
            println!("Asset Map ID: {}", inspection.asset_map_id);
            println!("Total Assets: {}", inspection.asset_count);
            println!("CPL Count: {}", inspection.cpl_count);

            if let Some(ref main_cpl) = inspection.main_cpl {
                println!("\nMain CPL:");
                println!("  Title: {}", main_cpl.title);
                println!("  Kind: {}", main_cpl.kind);
                println!("  ID: {}", main_cpl.id);
            }
        }
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&inspection)?);
        }
        OutputFormat::Detailed => {
            println!("IMF Package Details");
            println!("===================");
            println!("Path: {}", inspection.path.display());
            println!("Volume Index: {}", inspection.volume_index);
            println!("\nAsset Map:");
            println!("  ID: {}", inspection.asset_map_id);
            println!("  Issue Date: {}", inspection.asset_map_issue_date);
            if let Some(ref issuer) = inspection.asset_map_issuer {
                println!("  Issuer: {}", issuer);
            }
            if let Some(ref creator) = inspection.asset_map_creator {
                println!("  Creator: {}", creator);
            }

            println!("\nAssets ({}):", inspection.asset_count);
            for asset in &package.asset_map.asset_list.assets {
                println!("  - {}", asset.id);
                for chunk in &asset.chunk_list.chunks {
                    println!("    └─ {}", chunk.path);
                }
            }

            println!("\nComposition Playlists ({}):", inspection.cpl_count);
            let cpls = package.list_cpls();
            for cpl in &cpls {
                println!("  CPL: {}", cpl.id);
                println!("    Title: {}", cpl.title);
                println!("    Kind: {}", cpl.kind);
                println!("    Issue Date: {}", cpl.issue_date);
                if let Some(ref issuer) = cpl.issuer {
                    println!("    Issuer: {}", issuer);
                }
                println!("    Segments: {}", cpl.segments);
            }
        }
    }

    Ok(())
}

fn show_cpl(path: &PathBuf, uuid: Option<String>) -> Result<()> {
    let package = Imferno::parse(imferno_core::package::read_dir(path)?)?;

    let cpl_uuid = if let Some(uuid) = uuid {
        uuid
    } else {
        let inspection = package.inspect();
        if let Some(ref main_cpl) = inspection.main_cpl {
            main_cpl.id.clone()
        } else {
            return Err(anyhow::anyhow!("No CPLs found in package"));
        }
    };

    let details = package
        .get_cpl_details(&cpl_uuid)
        .ok_or_else(|| anyhow::anyhow!("CPL with UUID {} not found", cpl_uuid))?;

    println!("CPL Details");
    println!("===========");
    println!("ID: {}", details.id);
    println!("Title: {}", details.title);
    println!("Kind: {}", details.kind);
    println!("Issue Date: {}", details.issue_date);

    if let Some(ref annotation) = details.annotation {
        println!("Annotation: {}", annotation);
    }
    if let Some(ref issuer) = details.issuer {
        println!("Issuer: {}", issuer);
    }
    if let Some(ref creator) = details.creator {
        println!("Creator: {}", creator);
    }
    if let Some(ref originator) = details.content_originator {
        println!("Content Originator: {}", originator);
    }

    if !details.content_versions.is_empty() {
        println!("\nContent Versions:");
        for version in &details.content_versions {
            println!("  - {}", version);
        }
    }

    println!("\nSegments: {}", details.segments.len());
    for (i, segment) in details.segments.iter().enumerate() {
        println!(
            "  Segment {}: {} ({} sequences)",
            i + 1,
            segment.id,
            segment.sequence_count
        );
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn validate_package(
    path: &PathBuf,
    verify_hashes: bool,
    xml_only: bool,
    format: OutputFormat,
    core_spec: CoreSpecVersion,
    app2e_spec: App2eSpecVersion,
    exit_zero: bool,
    rules_config_path: Option<&std::path::Path>,
) -> Result<()> {
    let rules: imferno_core::package::RulesConfig = match rules_config_path {
        Some(p) => {
            let json = std::fs::read_to_string(p)
                .with_context(|| format!("Cannot read rules config: {}", p.display()))?;
            serde_json::from_str(&json)
                .with_context(|| format!("Invalid rules config JSON: {}", p.display()))?
        }
        None => Default::default(),
    };

    let color = use_color() && !matches!(format, OutputFormat::Json);

    if !matches!(format, OutputFormat::Json) {
        println!(
            "Validating IMF package: {}",
            c_bold(&path.display().to_string(), color)
        );
    }

    // Parse
    let parse_result = imferno_core::package::read_dir(path).and_then(Imferno::parse);
    let package = match parse_result {
        Ok(p) => {
            if !matches!(format, OutputFormat::Json) {
                println!("  {}  VOLINDEX.xml found", c_green("ok", color));
                println!("  {}  ASSETMAP.xml found", c_green("ok", color));
            }
            p
        }
        Err(e) => {
            if matches!(format, OutputFormat::Json) {
                let mut report = ValidationReport::new(ValidationProfile::SMPTE);
                report.add(
                    ValidationIssue::new(
                        Severity::Critical,
                        Category::Structure,
                        "PARSE-PACKAGE-FAILED",
                        format!("Failed to load IMF package: {}", e),
                    )
                    .with_suggestion(
                        "Ensure the directory contains VOLINDEX.xml and ASSETMAP.xml.",
                    ),
                );
                println!("{}", serde_json::to_string_pretty(&report)?);
                return Ok(());
            }
            return Err(e.into());
        }
    };

    let inspection = package.inspect();

    if !matches!(format, OutputFormat::Json) {
        println!(
            "  {}  {} assets mapped",
            c_green("ok", color),
            inspection.asset_count
        );
        println!(
            "  {}  {} CPL(s) parsed",
            c_green("ok", color),
            inspection.cpl_count
        );
        let scm_count = package.sidecar_composition_maps.len();
        if scm_count > 0 {
            let total_sidecars: usize = package
                .sidecar_composition_maps
                .values()
                .map(|s| s.sidecar_assets.len())
                .sum();
            println!(
                "  {}  {} SCM(s) parsed, {} sidecar asset(s) declared",
                c_green("ok", color),
                scm_count,
                total_sidecars
            );
            for scm in package.sidecar_composition_maps.values() {
                for sa in &scm.sidecar_assets {
                    let cpl_labels: Vec<String> = sa
                        .cpl_ids
                        .iter()
                        .map(|id| format!("{:.8}", id.to_string()))
                        .collect();
                    let filename = package
                        .asset_paths
                        .get(&sa.id)
                        .and_then(|p| p.file_name())
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_else(|| sa.id.to_string());
                    println!(
                        "        {} → CPL(s): [{}]",
                        c_dim(&filename, color),
                        c_dim(&cpl_labels.join(", "), color)
                    );
                }
            }
        }
        let unref = package.unreferenced_assets();
        if !unref.is_empty() {
            println!(
                "  {}  {} unreferenced asset(s) — no CPL track reference, no SCM declaration",
                c_yellow("info", color),
                unref.len()
            );
            for asset in &unref {
                let filename = asset
                    .chunk_list
                    .chunks
                    .first()
                    .map(|c| c.path.as_str())
                    .unwrap_or("(no path)");
                println!("        {}", c_dim(filename, color));
            }
        }
    }

    // Map CLI args to spec targets
    let core_spec_target = match core_spec {
        CoreSpecVersion::Auto => None,
        CoreSpecVersion::V2013 => Some(CoreSpecTarget::St2067_2_2013),
        CoreSpecVersion::V2016 => Some(CoreSpecTarget::St2067_2_2016),
        CoreSpecVersion::V2020 => Some(CoreSpecTarget::St2067_2_2020),
    };

    let app_spec_targets = match app2e_spec {
        App2eSpecVersion::Auto => None,
        App2eSpecVersion::None => Some(vec![]),
        App2eSpecVersion::V2020 => Some(vec![AppSpecTarget::St2067_21_2020]),
        App2eSpecVersion::V2021 => Some(vec![AppSpecTarget::St2067_21_2021]),
        App2eSpecVersion::V2023 => Some(vec![AppSpecTarget::St2067_21_2023]),
    };

    let options = ValidationOptions {
        rules,
        core_spec: core_spec_target,
        app_specs: app_spec_targets,
        skip_disk_checks: xml_only,
        ..Default::default()
    };

    let mut report = package.validate(&options);

    if !matches!(format, OutputFormat::Json) {
        let all_issues: Vec<_> = report
            .critical
            .iter()
            .chain(report.errors.iter())
            .chain(report.warnings.iter())
            .chain(report.info.iter())
            .collect();

        if !all_issues.is_empty() {
            println!("{}", c_bold("Validation findings:", color));

            for issue in &all_issues {
                let (label, colorize): (&str, fn(&str, bool) -> String) = match issue.severity {
                    Severity::Critical => ("error", c_red),
                    Severity::Error => ("error", c_red),
                    Severity::Warning => ("warning", c_yellow),
                    Severity::Info => ("info", c_cyan),
                };
                let location = if let Some(ref c) = issue.location.cpl_id {
                    c_dim(&format!(" [CPL:{}]", &c[..c.len().min(8)]), color)
                } else if let Some(ref f) = issue.location.file {
                    let fname = f.file_name().and_then(|n| n.to_str()).unwrap_or("?");
                    c_dim(&format!(" [{}]", fname), color)
                } else {
                    String::new()
                };
                println!(
                    "  {} {}{} {}",
                    colorize(&format!("{:<7}", label), color),
                    c_bold(&issue.code, color),
                    location,
                    issue.message,
                );
                if let Some(ref s) = issue.suggestion {
                    println!("          {} {}", c_dim("", color), c_dim(s, color));
                }
            }
        }
    }

    // File existence is already checked inside validate_package_structure_with_cpl_validator.
    // Only run the separate hash-verification pass when explicitly requested.
    if verify_hashes {
        if !matches!(format, OutputFormat::Json) {
            println!("Verifying file hashes (this may take a moment)...");
        }
        let hash_errs: Vec<_> = package
            .validate_file_hashes()
            .into_iter()
            .filter(|e| {
                !matches!(
                    e,
                    imferno_core::package::FileValidationError::Missing { .. }
                )
            })
            .collect();
        if hash_errs.is_empty() && !matches!(format, OutputFormat::Json) {
            println!("  {}  All PKL file hashes verified", c_green("ok", color));
        }
        for err in &hash_errs {
            report.add(ValidationIssue::new(
                Severity::Error,
                Category::Asset,
                "FILE-HASH-ERROR",
                err.to_string(),
            ));
            if !matches!(format, OutputFormat::Json) {
                println!("{}", err);
            }
        }
    }

    if matches!(format, OutputFormat::Json) {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        let total_errors = report.critical.len() + report.errors.len();
        let total_warnings = report.warnings.len();
        if total_errors > 0 {
            let mut reasons = Vec::new();
            if total_errors > 0 {
                reasons.push(format!("{} error(s)", total_errors));
            }
            if total_warnings > 0 {
                reasons.push(format!("{} warning(s)", total_warnings));
            }
            println!(
                "{} {}",
                c_red("failed", color),
                c_bold(&reasons.join(", "), color)
            );
            if !exit_zero {
                return Err(anyhow::anyhow!("Validation failed"));
            }
        } else if total_warnings > 0 {
            println!(
                "{}",
                c_yellow(&format!("valid  {} warning(s)", total_warnings), color)
            );
        } else {
            println!("{}", c_green("valid", color));
        }
    }

    Ok(())
}

fn generate_report(path: &PathBuf, ancestor_path: Option<&std::path::Path>) -> Result<()> {
    let package = Imferno::parse(imferno_core::package::read_dir(path)?)?;

    let ancestor = if let Some(anc_path) = ancestor_path {
        Some(Imferno::parse(imferno_core::package::read_dir(anc_path)?)?)
    } else {
        None
    };

    let report = imferno_core::package::build_report(&package, ancestor.as_ref())
        .map_err(|e| anyhow::anyhow!(e))?;

    println!("{}", serde_json::to_string_pretty(&report)?);

    Ok(())
}