//! Dump a ship's static placement + scene-graph nodes for a stage container FILE
//! (works offline from an extracted disc, no ISO needed).
//!   cargo run --release --example ship_dump -- <Stage_SNN.xpr path> <ship_id>
use sylpheed_formats::mesh::{scene_world_nodes, xbg7_resource_names, Xbg7Model};
use sylpheed_formats::ship::{assemble_ship, is_base_part, ship_id_of};
use std::collections::HashSet;

fn main() {
    let a: Vec<String> = std::env::args().collect();
    let (path, id) = (&a[1], &a[2]);
    let bytes = std::fs::read(path).unwrap();
    let names = xbg7_resource_names(&bytes);

    // Base parts + their vertex counts.
    let want: HashSet<String> = names.iter().filter(|n| is_base_part(n) && ship_id_of(n)==Some(id.as_str())).cloned().collect();
    let models = Xbg7Model::models_named(&bytes, &want, &|| false);
    println!("== base parts ({}) ==", want.len());
    for m in &models {
        let vc: usize = m.meshes.iter().map(|s| s.positions.len()).sum();
        println!("  {:20} vtx={}", m.name, vc);
    }

    // Composites present for this id.
    println!("== composites ==");
    for n in &names {
        if n.contains(&format!("rou_{id}")) && ship_id_of(n).is_none() {
            let nodes = scene_world_nodes(&bytes, n);
            println!("  {:24} {} nodes", n, nodes.len());
        }
    }

    // assemble_ship result: centroids + extent.
    for ext in [false, true] {
        let placed = assemble_ship(&bytes, id, ext);
        println!("== assemble_ship(external={ext}) -> {} parts ==", placed.len());
        let mut lo=[f32::MAX;3]; let mut hi=[f32::MIN;3];
        for p in &placed {
            let src = models.iter().find(|m| m.name==p.resource);
            let (mut c, mut n) = ([0.0f32;3], 0f32);
            if let Some(src)=src { for sub in &src.meshes { for v in &sub.positions {
                let w=p.apply(*v); for k in 0..3 { c[k]+=w[k]; lo[k]=lo[k].min(w[k]); hi[k]=hi[k].max(w[k]); } n+=1.0; }}}
            let n=n.max(1.0);
            println!("  {:20} T=[{:8.1}{:8.1}{:8.1}] centroid=[{:8.1}{:8.1}{:8.1}]",
                p.resource, p.t[0],p.t[1],p.t[2], c[0]/n,c[1]/n,c[2]/n);
        }
        if placed.iter().any(|p| models.iter().any(|m| m.name==p.resource)) {
            println!("  EXTENT=[{:.0} {:.0} {:.0}]", hi[0]-lo[0], hi[1]-lo[1], hi[2]-lo[2]);
        }
    }
}
