bambu-3mf-cli 0.1.0

Ultra-fast Bambu Studio & Orca Slicer 3MF inspection, API server, and asset extractor powered by Ferrox Framework
mod parser;
mod server;

use anyhow::Result;
use clap::{Parser, Subcommand};
use colored::*;
use parser::{format_duration, B3mfParser};
use server::start_ferrox_server;
use std::path::PathBuf;

#[derive(Parser)]
#[command(
    name = "bambu-3mf",
    author = "AI-Autistic-Intelligence <info@ferrox-rust.dev>",
    version = "0.1.0",
    about = "⚡ Ultra-fast Bambu Studio & Orca Slicer 3MF Inspector, API Server & Asset Extractor powered by Ferrox Framework",
    long_about = None
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Inspect a .3mf file and display print time, filament weights, and plate details
    Inspect {
        /// Path to the .3mf file
        file: PathBuf,

        /// Cost per kg of filament (e.g. 20.0 for $20/kg) to calculate total print cost
        #[arg(short = 'c', long, default_value_t = 25.0)]
        filament_cost_per_kg: f64,

        /// Output format as formatted JSON
        #[arg(short, long)]
        json: bool,
    },

    /// Extract plate thumbnail PNGs from the .3mf file
    ExtractThumbnails {
        /// Path to the .3mf file
        file: PathBuf,

        /// Output directory to extract PNG thumbnails to
        #[arg(short, long, default_value = "./thumbnails")]
        output: PathBuf,
    },

    /// Start a Ferrox Framework HTTP API server for remote 3MF inspection and integration
    Serve {
        /// Port to bind the Ferrox HTTP server to
        #[arg(short, long, default_value_t = 3000)]
        port: u16,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Inspect {
            file,
            filament_cost_per_kg,
            json,
        } => {
            let start = std::time::Instant::now();
            let analysis = B3mfParser::parse(&file)?;
            let elapsed = start.elapsed();

            if json {
                println!("{}", serde_json::to_string_pretty(&analysis)?);
                return Ok(());
            }

            println!("\n{}", "============================================================".bright_blue());
            println!("  🚀 {} {}", "Bambu 3MF File Analysis:".bold().white(), analysis.file_name.yellow().bold());
            println!("{}\n", "============================================================".bright_blue());

            println!("📦  {:<24} {:.2} MB", "File Size:".bold(), analysis.file_size_bytes as f64 / (1024.0 * 1024.0));
            println!("⏱️   {:<24} {}", "Total Estimated Time:".bold(), format_duration(analysis.total_print_time_seconds).green().bold());
            println!("⚖️   {:<24} {:.2} g", "Total Filament Weight:".bold(), analysis.total_weight_grams);

            let estimated_cost = (analysis.total_weight_grams / 1000.0) * filament_cost_per_kg;
            println!("💵  {:<24} ${:.2} (at ${:.2}/kg)", "Estimated Filament Cost:".bold(), estimated_cost, filament_cost_per_kg);
            println!("⚙️   {:<24} {}", "Slicer Generator:".bold(), analysis.slicer_generator.cyan());

            if !analysis.warnings.is_empty() {
                println!("\n⚠️  {}", "Warnings / Notices:".bright_yellow().bold());
                for w in &analysis.warnings {
                    println!("   • {}", w.yellow());
                }
            }

            println!("\n{}", "--- 🍽️ Plate Details ---".bold().magenta());
            for p in &analysis.plates {
                println!("\n📌 {} {}", "Plate #".bold(), p.index);
                println!("   • Name:                 {}", p.name.bold());
                println!("   • Plate Print Time:     {}", format_duration(p.print_time_seconds).green());
                println!("   • Plate Weight:         {:.2} g", p.total_weight_grams);

                if !p.filaments.is_empty() {
                    println!("   • Filament Usage (AMS Slots):");
                    for f in &p.filaments {
                        println!(
                            "     └─ [Slot {}] {} (Type: {}, Color: {}) - {:.2} g ({:.2} m)",
                            f.id,
                            f.material_type.bold().bright_cyan(),
                            f.material_type,
                            f.color,
                            f.used_grams,
                            f.used_meters
                        );
                    }
                }
            }

            println!("\n{}", "============================================================".bright_blue());
            println!("⚡ Inspection completed in {:.2?}", elapsed);
            println!("============================================================\n");
        }

        Commands::ExtractThumbnails { file, output } => {
            println!("🖼️  Extracting thumbnails from {}...", file.display().to_string().yellow());
            let paths = B3mfParser::extract_thumbnails(&file, &output)?;

            if paths.is_empty() {
                println!("⚠️  No PNG thumbnails found inside the 3MF file.");
            } else {
                println!("✅ Extracted {} thumbnails to {}:", paths.len(), output.display().to_string().cyan());
                for p in paths {
                    println!("   • {}", p.display());
                }
            }
        }

        Commands::Serve { port } => {
            println!("⚡ Ferrox Framework integration starting...");
            start_ferrox_server(port).await.map_err(|e| anyhow::anyhow!(e))?;
        }
    }

    Ok(())
}