bambu-3mf-cli 0.1.0

Ultra-fast Bambu Studio & Orca Slicer 3MF inspection, API server, and asset extractor powered by Ferrox Framework
use anyhow::{Context, Result};
use colored::*;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use zip::ZipArchive;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FilamentUsage {
    pub id: usize,
    pub color: String,
    pub material_type: String,
    pub used_grams: f64,
    pub used_meters: f64,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PlateInfo {
    pub index: usize,
    pub name: String,
    pub print_time_seconds: u64,
    pub total_weight_grams: f64,
    pub filaments: Vec<FilamentUsage>,
    pub has_thumbnail: bool,
    pub thumbnail_path: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct B3mfAnalysis {
    pub file_name: String,
    pub file_size_bytes: u64,
    pub slicer_generator: String,
    pub plates: Vec<PlateInfo>,
    pub total_print_time_seconds: u64,
    pub total_weight_grams: f64,
    pub warnings: Vec<String>,
}

pub struct B3mfParser;

impl B3mfParser {
    pub fn parse<P: AsRef<Path>>(path: P) -> Result<B3mfAnalysis> {
        let path = path.as_ref();
        let file = File::open(path)
            .with_context(|| format!("Failed to open 3MF file: {}", path.display()))?;
        
        let metadata = file.metadata()?;
        let file_size_bytes = metadata.len();
        let file_name = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();

        let mut archive = ZipArchive::new(file)
            .with_context(|| "Failed to read 3MF file as ZIP archive")?;

        let mut slicer_generator = "Bambu Studio / Orca Slicer".to_string();
        let mut slice_info_content = String::new();
        let mut warnings = Vec::new();
        let mut thumbnail_names = Vec::new();

        // Scan ZIP contents
        for i in 0..archive.len() {
            let file = archive.by_index(i)?;
            let name = file.name().to_string();

            if name.contains("slice_info.config") || name.ends_with("slice_info.config") {
                let mut content = String::new();
                let mut file_ref = file;
                file_ref.read_to_string(&mut content)?;
                slice_info_content = content;
            } else if name.ends_with(".png") && name.contains("Metadata") {
                thumbnail_names.push(name);
            }
        }

        let mut plates = Vec::new();

        if !slice_info_content.is_empty() {
            plates = Self::parse_slice_info_xml(&slice_info_content, &thumbnail_names)?;
        } else {
            // Fallback: try parsing G-code comments if slice_info XML is missing
            warnings.push("slice_info.config not found. Falling back to G-code inspection.".to_string());
            plates = Self::fallback_parse_gcode(&mut archive)?;
        }

        if plates.is_empty() {
            warnings.push("No sliced plate configuration found in 3MF file. Ensure model was sliced before saving.".to_string());
        }

        let total_print_time_seconds = plates.iter().map(|p| p.print_time_seconds).sum();
        let total_weight_grams = plates.iter().map(|p| p.total_weight_grams).sum();

        Ok(B3mfAnalysis {
            file_name,
            file_size_bytes,
            slicer_generator,
            plates,
            total_print_time_seconds,
            total_weight_grams,
            warnings,
        })
    }

    pub fn extract_thumbnails<P: AsRef<Path>>(3mf_path: P, output_dir: P) -> Result<Vec<PathBuf>> {
        let 3mf_path = 3mf_path.as_ref();
        let output_dir = output_dir.as_ref();
        fs::create_dir_all(output_dir)?;

        let file = File::open(3mf_path)?;
        let mut archive = ZipArchive::new(file)?;
        let mut extracted_paths = Vec::new();

        for i in 0..archive.len() {
            let mut file = archive.by_index(i)?;
            let name = file.name().to_string();

            if name.ends_with(".png") && (name.contains("Metadata") || name.contains("thumbnail")) {
                let file_name = Path::new(&name).file_name().unwrap_or_default();
                let out_path = output_dir.join(file_name);
                let mut out_file = File::create(&out_path)?;
                std::io::copy(&mut file, &mut out_file)?;
                extracted_paths.push(out_path);
            }
        }

        Ok(extracted_paths)
    }

    fn parse_slice_info_xml(xml_content: &str, thumbnails: &[String]) -> Result<Vec<PlateInfo>> {
        let mut plates = Vec::new();
        let plate_regex = Regex::new(r"(?s)<plate>(.*?)</plate>")?;
        let metadata_regex = Regex::new(r#"<metadata\s+key="([^"]+)"\s+value="([^"]+)"/>"#)?;
        let filament_regex = Regex::new(r#"<filament\s+id="([^"]+)"\s+color="([^"]+)"\s+type="([^"]+)"\s+used_m="([^"]+)"\s+used_g="([^"]+)"/>"#)?;

        for (idx, cap) in plate_regex.captures_iter(xml_content).enumerate() {
            let block = &cap[1];
            let mut prediction_sec: u64 = 0;
            let mut total_weight: f64 = 0.0;
            let mut plate_name = format!("Plate {}", idx + 1);

            for meta_cap in metadata_regex.captures_iter(block) {
                let key = &meta_cap[1];
                let val = &meta_cap[2];
                match key {
                    "prediction" => prediction_sec = val.parse().unwrap_or(0),
                    "weight" => total_weight = val.parse().unwrap_or(0.0),
                    "name" => plate_name = val.to_string(),
                    _ => {}
                }
            }

            let mut filaments = Vec::new();
            for fil_cap in filament_regex.captures_iter(block) {
                let id: usize = fil_cap[1].parse().unwrap_or(0);
                let color = fil_cap[2].to_string();
                let material_type = fil_cap[3].to_string();
                let used_meters: f64 = fil_cap[4].parse().unwrap_or(0.0);
                let used_grams: f64 = fil_cap[5].parse().unwrap_or(0.0);

                filaments.push(FilamentUsage {
                    id,
                    color,
                    material_type,
                    used_grams,
                    used_meters,
                });
            }

            let thumb_name = format!("plate_{}.png", idx + 1);
            let has_thumb = thumbnails.iter().any(|t| t.contains(&thumb_name));

            plates.push(PlateInfo {
                index: idx + 1,
                name: plate_name,
                print_time_seconds: prediction_sec,
                total_weight_grams: total_weight,
                filaments,
                has_thumbnail: has_thumb,
                thumbnail_path: if has_thumb { Some(thumb_name) } else { None },
            });
        }

        Ok(plates)
    }

    fn fallback_parse_gcode(archive: &mut ZipArchive<File>) -> Result<Vec<PlateInfo>> {
        let mut gcode_content = String::new();

        for i in 0..archive.len() {
            let mut file = archive.by_index(i)?;
            if file.name().ends_with(".gcode") {
                file.read_to_string(&mut gcode_content)?;
                break;
            }
        }

        if gcode_content.is_empty() {
            return Ok(Vec::new());
        }

        let time_re = Regex::new(r";\s*total time\s*=\s*(\d+)s")?;
        let weight_re = Regex::new(r";\s*total weight\s*=\s*([\d\.]+)")?;

        let mut time_sec: u64 = 0;
        let mut weight_g: f64 = 0.0;

        if let Some(cap) = time_re.captures(&gcode_content) {
            time_sec = cap[1].parse().unwrap_or(0);
        }
        if let Some(cap) = weight_re.captures(&gcode_content) {
            weight_g = cap[1].parse().unwrap_or(0.0);
        }

        Ok(vec![PlateInfo {
            index: 1,
            name: "Plate 1 (Gcode fallback)".to_string(),
            print_time_seconds: time_sec,
            total_weight_grams: weight_g,
            filaments: vec![],
            has_thumbnail: false,
            thumbnail_path: None,
        }])
    }
}

pub fn format_duration(seconds: u64) -> String {
    let hours = seconds / 3600;
    let minutes = (seconds % 3600) / 60;
    let secs = seconds % 60;
    if hours > 0 {
        format!("{}h {}m {}s", hours, minutes, secs)
    } else if minutes > 0 {
        format!("{}m {}s", minutes, secs)
    } else {
        format!("{}s", secs)
    }
}