main
Colby Knox 0.2.85: export_pos, verb_times, prewarm, render_board (standard 0.26); xcopy_footprint lands on the origin (#29) 1ae044e
//! export_pos: the board's pick-and-place (component position, CPL) file, the standard's verb (EDA Bridge Standard
//! #29). Positions come from the board itself, from its origin, as Altium's own Pick Place output gives them; parts
//! not fitted in the variant named are left out, as are through-hole parts with smdOnly. JLCPCB's CPL is written
//! beside it on request. Altium's generator writes CSV and text; a Gerber placement file it cannot, so that format
//! is refused by name.
use serde_json::{json, Value};
use std::collections::HashSet;
use std::path::{Path, PathBuf};

/// One placed part, as bom_placement reads it.
#[derive(Clone, Debug, PartialEq)]
pub struct Placed { pub des: String, pub footprint: String, pub x: f64, pub y: f64, pub rot: f64, pub bottom: bool, pub comment: String, pub tht: bool }

pub struct Opts { pub side: String, pub ascii: bool, pub inches: bool, pub smd_only: bool, pub jlcpcb: bool, pub stem: String }

fn csv_cell(s: &str) -> String { if s.contains([',', '"', '\n']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } }
fn rot(r: f64) -> String { let r = (r.rem_euclid(360.0) * 1000.0).round() / 1000.0; format!("{}", if r >= 360.0 { 0.0 } else { r }) }

/// The parts each file carries, and the files (name, text). Pure.
pub fn files<'a>(parts: &'a [Placed], o: &Opts) -> (Vec<&'a Placed>, Vec<(String, String)>) {
    let mut keep: Vec<&Placed> = parts.iter()
        .filter(|p| match o.side.as_str() { "front" => !p.bottom, "back" => p.bottom, _ => true })
        .filter(|p| !(o.smd_only && p.tht)).collect();
    keep.sort_by_key(|p| crate::bom::natural_key(&p.des));
    let (unit, k, dec) = if o.inches { ("in", 1.0 / 25.4, 4) } else { ("mm", 1.0, 4) };
    let layer = |p: &Placed| if p.bottom { "BottomLayer" } else { "TopLayer" };
    let head = ["Designator", "Comment", "Layer", "Footprint", &format!("Center-X({unit})"), &format!("Center-Y({unit})"), "Rotation"].map(String::from);
    let rows: Vec<[String; 7]> = keep.iter().map(|p| [p.des.clone(), p.comment.clone(), layer(p).into(), p.footprint.clone(),
        format!("{:.dec$}", p.x * k), format!("{:.dec$}", p.y * k), rot(p.rot)]).collect();
    let side = match o.side.as_str() { "front" => "-front", "back" => "-back", _ => "" };
    let mut out = Vec::new();
    if o.ascii {
        // Altium's text output: columns padded to the widest cell
        let all: Vec<&[String; 7]> = std::iter::once(&head).chain(rows.iter()).collect();
        let w: Vec<usize> = (0..7).map(|c| all.iter().map(|r| r[c].chars().count()).max().unwrap_or(0)).collect();
        let mut t = format!("Pick and place, units {unit}, from the board origin\r\n\r\n");
        for r in all { t.push_str(r.iter().enumerate().map(|(c, v)| format!("{v:<w$}", w = w[c])).collect::<Vec<_>>().join("  ").trim_end()); t.push_str("\r\n"); }
        out.push((format!("{}-pos{side}.txt", o.stem), t));
    } else {
        let mut t = head.iter().map(|h| csv_cell(h)).collect::<Vec<_>>().join(",") + "\r\n";
        for r in &rows { t.push_str(&r.iter().map(|c| csv_cell(c)).collect::<Vec<_>>().join(",")); t.push_str("\r\n"); }
        out.push((format!("{}-pos{side}.csv", o.stem), t));
    }
    if o.jlcpcb {
        // JLCPCB's CPL: their headers, mm, Top/Bottom (the same columns altium_bom writes)
        let mut t = String::from("Designator,Mid X,Mid Y,Layer,Rotation\r\n");
        for p in &keep { t.push_str(&format!("{},{:.4}mm,{:.4}mm,{},{}\r\n", csv_cell(&p.des), p.x, p.y, if p.bottom { "Bottom" } else { "Top" }, rot(p.rot))); }
        out.push((format!("{}-cpl-jlcpcb{side}.csv", o.stem), t));
    }
    (keep, out)
}

/// bom_placement's row: [designator, pattern, x, y (raw from the origin), rotation (millidegrees), bottom, comment, tht]
fn placed(c: &Value) -> Placed {
    let mm = |v: &Value| (v.as_f64().unwrap_or(0.0) / 10000.0 * 0.0254 * 10000.0).round() / 10000.0;
    let s = |v: &Value| v.as_str().unwrap_or("").to_string();
    Placed { des: s(&c[0]), footprint: s(&c[1]), x: mm(&c[2]), y: mm(&c[3]), rot: c[4].as_f64().unwrap_or(0.0) / 1000.0,
        bottom: c[5].as_bool() == Some(true), comment: s(&c[6]), tht: c[7].as_bool() == Some(true) }
}

/// The project beside the board that lists it.
fn project_of(board: &Path) -> Option<PathBuf> {
    let dir = board.parent()?;
    let name = board.file_name()?.to_string_lossy().to_lowercase();
    std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path())
        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("PrjPcb")).unwrap_or(false))
        .find(|p| std::fs::read_to_string(p).map(|t| t.to_lowercase().lines().any(|l| l.starts_with("documentpath=") && l.ends_with(&name))).unwrap_or(false))
}

/// altium_export_pos {filePath, side?, format?, units?, smdOnly?, excludeDnp?, variant?, projectPath?, fab?, outputDir?}
pub fn export_pos(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let s = |k: &str| crate::support::s(args, k);
    let Some(board) = s("filePath").or_else(|| s("pcbPath")).filter(|p| p.to_lowercase().ends_with(".pcbdoc")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .PcbDoc) is required"});
    };
    let format = s("format").unwrap_or_else(|| "csv".into()).to_lowercase();
    if format == "gerber" {
        return json!({"success": false, "errorCode": "unsupported", "error": "Altium's Pick Place output writes CSV and text, not a Gerber placement file",
            "_hint": "Ask for format csv (default) or ascii."});
    }
    if format != "csv" && format != "ascii" { return json!({"success": false, "errorCode": "bad_args", "error": format!("format '{format}' is not csv, ascii or gerber")}); }
    let side = s("side").unwrap_or_else(|| "both".into()).to_lowercase();
    if !["both", "front", "back"].contains(&side.as_str()) { return json!({"success": false, "errorCode": "bad_args", "error": "side is both, front or back"}); }
    let units = s("units").unwrap_or_else(|| "mm".into()).to_lowercase();
    if units != "mm" && units != "in" { return json!({"success": false, "errorCode": "bad_args", "error": "units is mm or in"}); }
    let fab = s("fab").map(|f| f.to_lowercase());
    if let Some(f) = fab.as_deref().filter(|f| *f != "jlcpcb") { return json!({"success": false, "errorCode": "bad_args", "error": format!("fab '{f}' is not one this bridge writes (jlcpcb)")}); }
    let b = |k: &str, d: bool| args.get(k).and_then(|v| v.as_bool()).unwrap_or(d);
    if let Some(e) = crate::support::must_open(&board, 60) { return e; }
    let r = crate::agent::call("bom_placement", &[], None, crate::support::timeout_of(args, 120));
    let Some(rows) = r.get("data").filter(|d| d["ok"].as_bool() == Some(true)).and_then(|d| d["comps"].as_array()).cloned() else {
        return json!({"success": false, "errorCode": "board_read_failed", "board": board, "reply": r});
    };
    let all: Vec<Placed> = rows.iter().map(placed).filter(|p| !p.des.is_empty()).collect();
    // not fitted: in the variant named (Altium marks do-not-populate per variant)
    let bpath = PathBuf::from(board.replace('\\', "/"));
    let prj = s("projectPath").map(PathBuf::from).or_else(|| project_of(&bpath));
    let mut dnp: HashSet<String> = HashSet::new();
    let mut variant_used = Value::Null;
    if let Some(v) = s("variant").filter(|v| !v.trim().is_empty() && !v.eq_ignore_ascii_case("none")) {
        let Some(p) = &prj else { return json!({"success": false, "errorCode": "no_project", "error": "a variant needs the board's project: none beside the board lists it (pass projectPath)"}) };
        let text = String::from_utf8_lossy(&std::fs::read(p).unwrap_or_default()).to_string();
        let project = crate::bom::parse_project(&text, p.parent().unwrap_or(Path::new(".")));
        let Some((name, m)) = project.variants.iter().find(|(n, _)| n.eq_ignore_ascii_case(&v)) else {
            return json!({"success": false, "errorCode": "variant_not_found", "error": format!("no variant named {v}"), "variants": project.variants.iter().map(|(n, _)| n.clone()).collect::<Vec<_>>()});
        };
        if b("excludeDnp", true) { dnp = m.iter().filter(|(_, (kind, _))| *kind == 1).map(|(d, _)| d.to_ascii_uppercase()).collect(); }
        variant_used = json!(name);
    }
    let fitted: Vec<Placed> = all.iter().filter(|p| !dnp.contains(&p.des.to_ascii_uppercase())).cloned().collect();
    let stem = bpath.file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "board".into());
    let opts = Opts { side: side.clone(), ascii: format == "ascii", inches: units == "in", smd_only: b("smdOnly", false), jlcpcb: fab.is_some(), stem };
    let (keep, out) = files(&fitted, &opts);
    let dir = s("outputDir").map(PathBuf::from).unwrap_or_else(|| bpath.parent().unwrap_or(Path::new(".")).join("Pick Place"));
    if let Err(e) = std::fs::create_dir_all(&dir) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", dir.display())}); }
    let mut written = Vec::new();
    for (name, text) in &out {
        let p = dir.join(name);
        if let Err(e) = std::fs::write(&p, text) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", p.display())}); }
        written.push(p.to_string_lossy().replace('/', "\\"));
    }
    let front = keep.iter().filter(|p| !p.bottom).count();
    let mut dnp_left: Vec<String> = all.iter().filter(|p| dnp.contains(&p.des.to_ascii_uppercase())).map(|p| p.des.clone()).collect();
    dnp_left.sort_by_key(|d| crate::bom::natural_key(d));
    let tht_left: Vec<String> = if opts.smd_only { fitted.iter().filter(|p| p.tht).map(|p| p.des.clone()).collect() } else { vec![] };
    json!({"success": true, "files": written, "parts": {"front": front, "back": keep.len() - front, "total": keep.len()},
        "excluded": {"dnp": dnp_left, "throughHole": tht_left}, "variant": variant_used, "units": units, "format": format, "side": side,
        "_hint": "Positions are each part's reference point from the board origin, as Altium's own Pick Place output gives them. DNP is per variant in Altium: name the variant to leave its not-fitted parts out. Check rotations in the assembler's preview (JLCPCB's package orientation can differ from Altium's)."})
}

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

    fn p(d: &str, x: f64, y: f64, r: f64, bottom: bool, tht: bool) -> Placed {
        Placed { des: d.into(), footprint: "FP".into(), x, y, rot: r, bottom, comment: "10k, 1%".into(), tht }
    }

    #[test]
    fn csv_both_sides_in_designator_order() {
        let parts = vec![p("R10", 1.0, 2.0, 90.0, false, false), p("R2", 3.0, 4.0, -90.0, true, false), p("J1", 5.0, 6.0, 0.0, false, true)];
        let o = Opts { side: "both".into(), ascii: false, inches: false, smd_only: false, jlcpcb: true, stem: "b".into() };
        let (keep, out) = files(&parts, &o);
        assert_eq!(keep.iter().map(|p| p.des.as_str()).collect::<Vec<_>>(), ["J1", "R2", "R10"]);
        assert_eq!(out[0].0, "b-pos.csv");
        let lines: Vec<&str> = out[0].1.lines().collect();
        assert_eq!(lines[0], "Designator,Comment,Layer,Footprint,Center-X(mm),Center-Y(mm),Rotation");
        assert_eq!(lines[2], "R2,\"10k, 1%\",BottomLayer,FP,3.0000,4.0000,270");
        assert_eq!(out[1].0, "b-cpl-jlcpcb.csv");
        assert!(out[1].1.contains("R10,1.0000mm,2.0000mm,Top,90"));
    }

    #[test]
    fn a_side_smd_only_and_inches() {
        let parts = vec![p("U1", 25.4, 0.0, 0.0, false, false), p("J1", 0.0, 0.0, 0.0, false, true), p("C1", 0.0, 0.0, 0.0, true, false)];
        let o = Opts { side: "front".into(), ascii: false, inches: true, smd_only: true, jlcpcb: false, stem: "b".into() };
        let (keep, out) = files(&parts, &o);
        assert_eq!(keep.len(), 1);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].0, "b-pos-front.csv");
        assert!(out[0].1.contains("U1,\"10k, 1%\",TopLayer,FP,1.0000,0.0000,0"), "{}", out[0].1);
    }

    #[test]
    fn ascii_is_aligned() {
        let o = Opts { side: "both".into(), ascii: true, inches: false, smd_only: false, jlcpcb: false, stem: "b".into() };
        let (_, out) = files(&[p("U1", 1.0, 2.0, 0.0, false, false)], &o);
        assert_eq!(out[0].0, "b-pos.txt");
        assert!(out[0].1.contains("Designator  Comment  Layer     Footprint  Center-X(mm)  Center-Y(mm)  Rotation\r\nU1          10k, 1%  TopLayer  FP         1.0000"), "{}", out[0].1);
    }
}