//! Authoritative SVG renderer for an Altium .PcbLib footprint.
//!
//! Usage:
//!   altium-pcblib-svg <path/to/Foo.PcbLib>            # primary footprint, SVG to stdout
//!   altium-pcblib-svg <path> --all                     # primary + every alternate, stacked
//!   altium-pcblib-svg <path> -o foo.svg                # write to file
//!
//! This is the GROUND TRUTH view of what the altium-pcblib parser sees. If
//! a downstream renderer (chipsmith overlay, concur, anything else) renders
//! a footprint differently from this output, the downstream renderer is
//! the bug — not the parser.

use std::path::PathBuf;

fn main() {
    let mut args = std::env::args().skip(1);
    let mut path: Option<PathBuf> = None;
    let mut out_path: Option<PathBuf> = None;
    let mut render_all = false;

    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-h" | "--help" => { print_usage(); return; }
            "--all" => render_all = true,
            "-o" | "--out" => {
                out_path = args.next().map(PathBuf::from);
                if out_path.is_none() {
                    eprintln!("ERROR: -o requires a path");
                    std::process::exit(2);
                }
            }
            _ if path.is_none() => path = Some(PathBuf::from(arg)),
            other => {
                eprintln!("ERROR: unexpected argument: {other}");
                print_usage();
                std::process::exit(2);
            }
        }
    }

    let Some(path) = path else {
        print_usage();
        std::process::exit(2);
    };

    let parsed = match altium_pcblib::parse_altium_pcblib_path(&path) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("ERROR: parse {}: {e}", path.display());
            std::process::exit(1);
        }
    };

    let svg = if render_all {
        altium_pcblib::render_all_footprints_svg(&parsed)
    } else {
        altium_pcblib::render_footprint_svg(&parsed)
    };

    match out_path {
        Some(p) => {
            if let Err(e) = std::fs::write(&p, svg.as_bytes()) {
                eprintln!("ERROR: write {}: {e}", p.display());
                std::process::exit(1);
            }
            eprintln!("OK: wrote {} ({} bytes)", p.display(), svg.len());
        }
        None => print!("{svg}"),
    }
}

fn print_usage() {
    eprintln!("Usage: altium-pcblib-svg <path/to/Foo.PcbLib> [--all] [-o out.svg]");
    eprintln!();
    eprintln!("Renders the parser's view of the footprint as SVG. With --all,");
    eprintln!("renders every variant the .PcbLib declares (primary + alternates)");
    eprintln!("stacked vertically.");
}