main
Colby Knox 0.2.114: placed parts keep their models (library placement), set_models replaces only footprints, edit_footprint/librar… 500e445
//! Board pictures without a window, the EDA Bridge Standard's render_board_3d and render_board_layers on Altium:
//! Altium's own prints (the PCB 3D Print, the composite print of chosen layers) to PDF through the board's project,
//! then rendered to PNG by Windows' PDF renderer, as render_schematic does for a sheet.
use crate::{routing, support};
use serde_json::{json, Value};
use std::path::{Path, PathBuf};

fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }

/// Page `page` (negative counts from the end) of a PDF as a PNG `width` px wide.
pub fn pdf_png(pdf: &Path, png: &Path, width: i64, page: i64) -> Result<Value, String> {
    let tmp = std::env::temp_dir().join("adom-altium-render").join(format!("{}", (support::now() * 1000.0) as u64));
    std::fs::create_dir_all(&tmp).map_err(|e| e.to_string())?;
    let script = tmp.join("render.ps1");
    std::fs::write(&script, crate::schsheet::RENDER_PS).map_err(|e| e.to_string())?;
    let r = crate::schsheet::powershell(&script, &["-Pdf".into(), pdf.to_string_lossy().to_string(), "-Png".into(), png.to_string_lossy().to_string(), "-Width".into(), width.to_string(), "-PageIndex".into(), page.to_string()]);
    let _ = std::fs::remove_dir_all(&tmp);
    r
}

/// The board to draw and its project: filePath, or the board open in Altium.
fn board_and_project(args: &Value) -> Result<(String, String), Value> {
    if let Some(g) = support::need_licensed() { return Err(g); }
    let pcb = match support::s(args, "filePath") {
        Some(p) => p,
        None => { let st = routing::routing_state(&json!({})); match st["file"].as_str() { Some(f) if !f.is_empty() => f.to_string(), _ => return Err(st) } }
    };
    let Some(prj) = crate::project::project_of(&pcb) else {
        return Err(json!({"success": false, "errorCode": "no_project", "error": format!("{pcb} is in no project beside it: Altium prints a project's documents"), "_hint": "Add the board to a .PrjPcb in its folder, then run this again."}));
    };
    Ok((pcb, prj))
}

fn out_dir(args: &Value, pcb: &str) -> PathBuf {
    support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| Path::new(pcb).parent().unwrap_or(Path::new(".")).join("render"))
}

/// altium_render_board_3d {filePath?, side?, width?, outputDir?}
pub fn render_board_3d(args: &Value) -> Value {
    let (pcb, prj) = match board_and_project(args) { Ok(x) => x, Err(e) => return e };
    let side = args.get("side").and_then(|v| v.as_str()).unwrap_or("top");
    if side != "top" && side != "bottom" { return json!({"success": false, "errorCode": "not_supported", "error": format!("side {side}: Altium's 3D print looks straight down at the top or up at the bottom; left, right, front and back need a window (altium_show_3d_board)")}); }
    let width = args.get("width").and_then(|v| v.as_i64()).unwrap_or(1600).clamp(200, 8000);
    let dir = out_dir(args, &pcb);
    let _ = std::fs::create_dir_all(&dir);
    let stem = Path::new(&pcb).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("board".into());
    let pdf = dir.join(format!("{stem}-3d-{side}.pdf"));
    let ex = crate::sch::export_pdf(&json!({"projectPath": prj, "output": pdf.to_string_lossy(), "board3d": side}));
    if ex.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "print_failed", "error": "Altium's 3D print wrote no PDF", "reply": ex}); }
    let png = dir.join(format!("{stem}-3d-{side}.png"));
    let r = match pdf_png(&pdf, &png, width, -1) { Ok(r) => r, Err(e) => return json!({"success": false, "errorCode": "render_failed", "error": e}) };
    let ignored: Vec<&str> = ["height", "quality", "background", "zoom", "perspective", "format"].into_iter().filter(|k| args.get(*k).is_some()).collect();
    json!({"success": true, "image": png.to_string_lossy(), "width": r["width"], "height": r["height"], "side": side, "pdf": pdf.to_string_lossy(), "optionsNotApplied": ignored, "windowEtiquette": "background",
        "_hint": "Altium's own PCB 3D Print (its Assembly template's settings, looking straight down or up), printed to PDF and rendered by Windows: no window opens. Parts with no 3D body show as bare pads (altium_bodies lists them)."})
}

/// altium_render_board: the standard's render_board (EDA Bridge Standard #29), through render_board_3d (Altium's own
/// 3D print, no window). Altium looks straight down or up only, so left, right, front and back are refused by name,
/// and the camera options it has no way to apply are named in optionsNotApplied.
pub fn render_board(args: &Value) -> Value {
    let mut r = render_board_3d(args);
    if r.get("success").and_then(|b| b.as_bool()) != Some(true) { return r; }
    r["path"] = r["image"].clone();
    let mut ignored: Vec<String> = r["optionsNotApplied"].as_array().cloned().unwrap_or_default().iter().filter_map(|v| v.as_str().map(str::to_string)).collect();
    for k in ["refs", "marginMm", "rotate"] { if args.get(k).is_some() { ignored.push(k.to_string()); } }
    r["optionsNotApplied"] = json!(ignored);
    if args.get("refs").is_some() { r["framed"] = Value::Null; }
    r
}

/// The presets: name, what it shows, and Altium's print layers. Pure.
pub fn presets() -> Vec<(&'static str, &'static str, Vec<&'static str>)> {
    vec![
        ("all", "every outer layer: silkscreen, copper and the outline", vec!["TopOverlay", "TopLayer", "BottomLayer", "BottomOverlay", "MultiLayer", "Mechanical1"]),
        ("top_copper", "top copper and pads", vec!["TopLayer", "MultiLayer", "Mechanical1"]),
        ("bottom_copper", "bottom copper and pads", vec!["BottomLayer", "MultiLayer", "Mechanical1"]),
        ("top_silkscreen", "top silkscreen", vec!["TopOverlay", "Mechanical1"]),
        ("bottom_silkscreen", "bottom silkscreen", vec!["BottomOverlay", "Mechanical1"]),
        ("top_soldermask", "top solder mask openings", vec!["TopSolder", "Mechanical1"]),
        ("bottom_soldermask", "bottom solder mask openings", vec!["BottomSolder", "Mechanical1"]),
        ("top_paste", "top paste (the stencil)", vec!["TopPaste", "Mechanical1"]),
        ("bottom_paste", "bottom paste", vec!["BottomPaste", "Mechanical1"]),
        ("outline", "the board outline", vec!["Mechanical1", "KeepOutLayer"]),
        ("drill", "the drill drawing", vec!["DrillDrawing", "Mechanical1"]),
        ("assembly_top", "top assembly: silkscreen, pads and outline", vec!["TopOverlay", "MultiLayer", "Mechanical1"]),
        ("assembly_bottom", "bottom assembly", vec!["BottomOverlay", "MultiLayer", "Mechanical1"]),
        ("fabrication", "outline, drill drawing and pads", vec!["Mechanical1", "DrillDrawing", "MultiLayer"]),
    ]
}

/// Altium's print layer name for a layer id (as routing_state names them, or the tool's own L<n>). Pure.
pub fn print_layer(id: i64) -> Option<String> {
    Some(match id {
        1 => "TopLayer".into(), 32 => "BottomLayer".into(), 2..=31 => format!("MidLayer{}", id - 1), 39..=54 => format!("InternalPlane{}", id - 38),
        33 => "TopOverlay".into(), 34 => "BottomOverlay".into(), 35 => "TopPaste".into(), 36 => "BottomPaste".into(), 37 => "TopSolder".into(), 38 => "BottomSolder".into(),
        55 => "DrillGuide".into(), 56 => "KeepOutLayer".into(), 57..=72 => format!("Mechanical{}", id - 56), 73 => "DrillDrawing".into(), 74 => "MultiLayer".into(),
        _ => return None,
    })
}

/// altium_render_board_layers {filePath?, preset? | layers?, format?, dpi?, mirror?, outputPath?, listPresets?}
/// The box round a board's outline plus 1 mm, in Altium's internal units (10000 to the mil), from routing_state's mm.
fn outline_area(state: &Value) -> Option<[i64; 4]> {
    let pts = state["outline"].as_array()?;
    let xy: Vec<(f64, f64)> = pts.iter().filter_map(|p| Some((p[0].as_f64()?, p[1].as_f64()?))).collect();
    if xy.len() < 3 { return None; }
    let (x0, y0, x1, y1) = xy.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
    let u = |mm: f64| (mm / 25.4 * 1000.0 * 10000.0).round() as i64;
    Some([u(x0 - 1.0), u(y0 - 1.0), u(x1 + 1.0), u(y1 + 1.0)])
}

pub fn render_board_layers(args: &Value) -> Value {
    if args.get("listPresets").and_then(|v| v.as_bool()) == Some(true) {
        let p: serde_json::Map<String, Value> = presets().into_iter().map(|(n, d, l)| (n.to_string(), json!({"description": d, "altiumLayers": l}))).collect();
        return json!({"success": true, "presets": p});
    }
    if args.get("format").and_then(|v| v.as_str()) == Some("svg") { return json!({"success": false, "errorCode": "not_supported", "error": "Altium prints to PDF here and Windows renders it to PNG: svg is not made (format png)"}); }
    let (pcb, prj) = match board_and_project(args) { Ok(x) => x, Err(e) => return e };
    let (name, layers): (String, Vec<String>) = match args.get("layers").and_then(|v| v.as_array()) {
        Some(ls) => {
            // standard copper names through this board's stack (In2.Cu may be a plane), or the tool's own L<n>
            if support::must_open(&pcb, 60).is_none() { let _ = routing::routing_state(&json!({})); }
            let mut out = Vec::new();
            for l in ls {
                let id = routing::layer_id(l).or_else(|| l.as_str().and_then(|x| x.strip_prefix('L')).and_then(|n| n.parse().ok()));
                match id.and_then(print_layer) { Some(n) => out.push(n), None => return bad(format!("layer {l}: a copper name (F.Cu, In1.Cu, B.Cu) or Altium's own id (L33 is the top silkscreen)")) }
            }
            ("custom".into(), out)
        }
        None => {
            let p = args.get("preset").and_then(|v| v.as_str()).unwrap_or("all");
            match presets().into_iter().find(|x| x.0 == p) { Some((n, _, l)) => (n.into(), l.into_iter().map(str::to_string).collect()), None => return bad(format!("preset {p}: listPresets:true names them")) }
        }
    };
    let dpi = args.get("dpi").and_then(|v| v.as_i64()).unwrap_or(300).clamp(50, 1200);
    // the print fills an A4 landscape page (11.69 in wide)
    let width = ((11.69 * dpi as f64).round() as i64).clamp(200, 12000);
    let stem = Path::new(&pcb).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("board".into());
    let png = support::s(args, "outputPath").map(PathBuf::from).unwrap_or_else(|| out_dir(args, &pcb).join(format!("{stem}-{name}.png")));
    if let Some(d) = png.parent() { let _ = std::fs::create_dir_all(d); }
    let pdf = png.with_extension("pdf");
    let mirror = args.get("mirror").and_then(|v| v.as_bool()) == Some(true);
    // the board's own box, 1 mm round its outline: the design extent takes in rooms and parts left off the board
    // (a change order's room beside the default board made a one-part board a speck on the page, 2026-10-27)
    let whole = args.get("area").and_then(|v| v.as_str()) == Some("extent");
    let area = if whole || support::must_open(&pcb, 60).is_some() { None } else { outline_area(&routing::routing_state(&json!({}))) };
    let ex = crate::sch::export_pdf(&json!({"projectPath": prj, "output": pdf.to_string_lossy(), "board": true, "boardLayers": layers, "mirror": mirror, "boardArea": area}));
    if ex.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "print_failed", "error": "Altium's board print wrote no PDF", "reply": ex}); }
    let r = match pdf_png(&pdf, &png, width, -1) { Ok(r) => r, Err(e) => return json!({"success": false, "errorCode": "render_failed", "error": e}) };
    json!({"success": true, "path": png.to_string_lossy(), "format": "png", "widthPx": r["width"], "heightPx": r["height"], "dpi": dpi, "preset": name, "layers": layers, "mirror": mirror, "pdf": pdf.to_string_lossy(), "windowEtiquette": "background",
        "area": if area.is_some() { "board" } else { "extent" }, "_hint": "Altium's composite print of these layers, the board's outline plus 1 mm (area:\"extent\" prints every object), fitted to an A4 landscape page and rendered by Windows: no window opens. Inner layers appear only when listed in layers; mirror draws the board as seen from below."})
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_print_area_is_the_outline_plus_a_millimetre() {
        let a = outline_area(&json!({"outline": [[0.0, 0.0], [10.0, 0.0], [10.0, 5.0], [0.0, 5.0]]})).unwrap();
        assert_eq!(a, [-393701, -393701, 4330709, 2362205]);
        assert!(outline_area(&json!({"outline": []})).is_none());
    }

    #[test]
    fn layer_ids_map_to_print_layers() {
        assert_eq!(print_layer(1).as_deref(), Some("TopLayer"));
        assert_eq!(print_layer(3).as_deref(), Some("MidLayer2"));
        assert_eq!(print_layer(39).as_deref(), Some("InternalPlane1"));
        assert_eq!(print_layer(57).as_deref(), Some("Mechanical1"));
        assert_eq!(print_layer(33).as_deref(), Some("TopOverlay"));
        assert!(print_layer(999).is_none());
        assert!(presets().iter().any(|p| p.0 == "top_paste"));
    }
}

/// A SchLib symbol's footprint model name (its PCBLIB implementation), read from the library file. Pure over the streams.
pub fn symbol_footprint(streams: &std::collections::BTreeMap<String, Vec<u8>>, libref: &str) -> Option<String> {
    for (name, data) in streams {
        if !name.ends_with("Data") { continue; }
        let recs = crate::schdoc::records(data);
        if !recs.iter().any(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1") && r.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(libref)).unwrap_or(false)) { continue; }
        return recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("45") && r.get("MODELTYPE").map(|t| t.eq_ignore_ascii_case("PCBLIB")).unwrap_or(false))
            .and_then(|r| r.get("MODELNAME").cloned());
    }
    None
}

/// The .PcbLib beside `dir` that holds a footprint of that name (its storage is named after it).
pub(crate) fn pcblib_with(dir: &Path, footprint: &str) -> Option<String> {
    std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()).map(|e| e.path())
        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("pcblib")).unwrap_or(false))
        .find(|p| std::fs::read(p).ok().and_then(|b| crate::schdoc::cfb_streams(&b).ok()).map(|s| s.keys().any(|k| k.split('/').next().map(|t| t.eq_ignore_ascii_case(footprint)).unwrap_or(false))).unwrap_or(false))
        .map(|p| p.to_string_lossy().to_string())
}

fn save_shot(r: &Value, path: &Path) -> Result<(i64, i64), String> {
    let img = r["shot"]["image"].as_str().ok_or_else(|| r.get("error").map(|e| e.to_string()).unwrap_or_else(|| "no picture in the reply".into()))?;
    let bytes = crate::a365::b64url_decode(img).ok_or("the picture did not decode")?;
    std::fs::write(path, bytes).map_err(|e| e.to_string())?;
    Ok((r["shot"]["width"].as_i64().unwrap_or(0), r["shot"]["height"].as_i64().unwrap_or(0)))
}

/// altium_library_views {libraryPath, parts, views?, outputDir?}
pub fn library_views(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let Some(lib) = support::s(args, "libraryPath") else { return bad("libraryPath (.SchLib or .PcbLib) is required") };
    let parts: Vec<String> = args.get("parts").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();
    if parts.is_empty() { return bad("parts: [part name] is required"); }
    let is_sch = lib.to_lowercase().ends_with(".schlib");
    // the views a library of this kind has, unless the caller names them: a PcbLib has no symbol, and asking it for one
    // made the whole call fail while the footprint rendered (#42)
    let asked: Option<Vec<String>> = args.get("views").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect());
    let explicit = asked.is_some();
    let views: Vec<String> = asked.unwrap_or_else(|| if is_sch { vec!["symbol".into(), "footprint".into(), "3d".into(), "device".into()] } else { vec!["footprint".into(), "3d".into()] });
    let dir = Path::new(&lib).parent().unwrap_or(Path::new(".")).to_path_buf();
    let out = support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| dir.join("views"));
    let _ = std::fs::create_dir_all(&out);
    let sch_streams = if is_sch { std::fs::read(&lib).ok().and_then(|b| crate::schdoc::cfb_streams(&b).ok()) } else { None };
    let mut captured = Vec::new();
    for part in &parts {
        // the footprint: the part itself in a PcbLib, the symbol's footprint model from a SchLib
        let fp = if is_sch { sch_streams.as_ref().and_then(|s| symbol_footprint(s, part)) } else { Some(part.clone()) };
        let fp_lib = if is_sch { fp.as_ref().and_then(|f| pcblib_with(&dir, f)) } else { Some(lib.clone()) };
        for view in &views {
            let path = out.join(format!("{part}-{view}.png"));
            let mut row = json!({"part": part, "view": view, "path": path.to_string_lossy(), "ok": false});
            let r = match view.as_str() {
                "symbol" if is_sch => crate::surfaces::show_symbol(&json!({"libraryPath": lib, "symbolName": part})),
                "symbol" => { row["error"] = json!("a .PcbLib holds footprints only: give the .SchLib for the symbol"); row["skipped"] = json!(true); captured.push(row); continue; }
                "footprint" | "3d" => {
                    let (Some(f), Some(l)) = (fp.as_ref(), fp_lib.as_ref()) else { row["error"] = json!("no footprint found for the part (its model link, or a .PcbLib beside the library that holds it)"); captured.push(row); continue; };
                    if view == "3d" {
                        let rf = crate::project::read_footprint(&json!({"libraryPath": l, "name": f}));
                        if rf["models"].as_array().map(|m| m.is_empty()).unwrap_or(true) {
                            row["error"] = json!(format!("{f} has no 3D body: add one (altium_add_body)"));
                            if !explicit { row["skipped"] = json!(true); }
                            captured.push(row); continue;
                        }
                        crate::surfaces::show_3d_chip(&json!({"libraryPath": l, "footprintName": f}))
                    } else { crate::surfaces::show_footprint(&json!({"libraryPath": l, "footprintName": f})) }
                }
                "device" => { row["error"] = json!("Altium has no device view: the symbol-pin to footprint-pad map is altium_pin_pad_check"); row["skipped"] = json!(true); captured.push(row); continue; }
                o => { row["error"] = json!(format!("view {o}: symbol, footprint, 3d or device")); captured.push(row); continue; }
            };
            match save_shot(&r, &path) {
                Ok((w, h)) => { row["ok"] = json!(true); row["width"] = json!(w); row["height"] = json!(h); if view != "symbol" { row["footprint"] = json!(fp); } }
                Err(e) => { row["error"] = json!(e); }
            }
            captured.push(row);
        }
    }
    // a view the library cannot have is skipped, not failed; at least one picture must have come out
    let all_ok = captured.iter().all(|c| c["ok"] == json!(true) || c["skipped"] == json!(true)) && captured.iter().any(|c| c["ok"] == json!(true));
    json!({"success": all_ok, "captured": captured, "outputDir": out.to_string_lossy(), "windowEtiquette": "background",
        "_hint": "Each picture is Altium's own editor captured in the background (no foreground). The device view (symbol pins mapped to pads) is altium_pin_pad_check on Altium."})
}