master
Colby Knox v2.1.11: A part request is answered in the thread that asked, not by email (the wiki thread's handoff; John's report th… 6752e69
//! The Adom wiki is the ONLY source (Ray, 2026-11-04: "I'm going to make the wiki search the sole endpoint for
//! adom-parts-search and that way we're not burning Mouser and DigiKey API calls. If someone asks the wiki for
//! something, either we have it, or we will make it quickly."). A part with a component page has ready-made CAD
//! (symbol, footprint, 3D, STEP, an Eagle .lbr), often a Verified record, its distributor numbers, the stock the wiki
//! has cached, and for Adom's own parts the Adom part number and stock. A part without one is recorded as a search
//! miss and can be requested; Adom's factory builds the page. No distributor is asked on a person's search: the
//! wiki's stock route serves its cache only.
//!
//! Auth is the wiki CLI's own (ADOM_WIKI_TOKEN, else ~/.config/adom-wiki/token or its config.json, else the Adom
//! container key at /var/run/adom/api-key), so a signed-in
//! user also sees the private pages they may see and nothing else; without a token the search is anonymous and only
//! public pages come back.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};

pub const DEFAULT_WIKI: &str = "https://wiki.adom.inc";
/// Pages read in full per search (page.json + verification each). The search itself returns more.
const DETAIL_PAGES: usize = 5;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Cad {
    pub symbol: bool,
    pub footprint: bool,
    #[serde(rename = "3d")]
    pub model_3d: bool,
    pub step: bool,
    pub lbr: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WikiHit {
    /// owner/slug
    pub r#ref: String,
    pub url: String,
    pub title: String,
    pub mpn: String,
    pub manufacturer: String,
    pub visibility: String,
    /// The page's component MPN (or slug) is exactly the query.
    pub exact: bool,
    pub cad: Cad,
    /// "verified" (a current record), "stale" (a pinned file changed since), or "none".
    pub verified: String,
    /// component.adom: Adom's own part number and stock label, on Adom-made and Adom basic parts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adom: Option<Value>,
    /// The maker's lifecycle when the page records it (preview, active, nrnd, ...).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lifecycle: Option<String>,
    /// component.distributor_links: the distributor part numbers (a string), or false where a distributor was
    /// checked and does not carry the part.
    #[serde(default)]
    pub distributor_links: Value,
    /// GET /api/pages/<ref>/stock: the wiki's cached vendor numbers ({mouser, digikey, lcsc}, each null when not
    /// cached) and when they were read. Never a live lookup.
    #[serde(default)]
    pub stock: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub datasheet_url: Option<String>,
    #[serde(default)]
    pub package: String,
    #[serde(default)]
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WikiBlock {
    pub ok: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub skipped: bool,
    pub error: Option<String>,
    /// True when an exact page exists: the part has ready-made CAD on the Adom wiki.
    pub ready_made: bool,
    pub hits: Vec<WikiHit>,
    /// No exact page: how to have the factory build one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request: Option<Value>,
    /// The orderable part numbers behind the query (GET /api/part-request/candidates), each with its page when one
    /// exists, its lifecycle (a "preview" tag) and the maker's page.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<Value>,
    /// The search was recorded as a miss (POST /api/part-search-miss): enough searchers queue the part even when no
    /// one clicks Request, and the counts are Adom's market signal.
    #[serde(default)]
    pub miss_recorded: bool,
    /// Why a miss was not recorded, when it was not (the wiki takes misses from its own search page today:
    /// PART_SEARCH_MISS_CROSS_SITE).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub miss_note: Option<String>,
    pub signed_in: bool,
    pub elapsed_ms: u64,
}

pub fn norm(s: &str) -> String { s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_uppercase() }

/// The Adom container key: in a Hydrogen local workspace or an Adom cloud container this is the identity the wiki CLI
/// signs in with when nothing else is set (`adom-wiki auth token` reports `container:/var/run/adom/api-key`).
pub const CONTAINER_KEY: &str = "/var/run/adom/api-key";

fn read_trimmed(path: &str) -> Option<String> {
    std::fs::read_to_string(path).ok().map(|t| t.trim().to_string()).filter(|t| !t.is_empty())
}

/// The identity the wiki CLI uses, in the CLI's order: ADOM_WIKI_TOKEN, then the stored token
/// (~/.config/adom-wiki/token, else that folder's config.json api_token), then the container key. Before 2.1.5 the
/// container key was never tried, so `request` said "not signed in" in a workspace where adom-wiki was signed in
/// (adom/adom-parts-search#12).
fn token() -> Option<String> {
    token_from(std::env::var("ADOM_WIKI_TOKEN").ok(), &format!("{}/.config/adom-wiki", std::env::var("HOME").unwrap_or_default()), CONTAINER_KEY)
}

fn token_from(env: Option<String>, dir: &str, container_key: &str) -> Option<String> {
    if let Some(t) = env.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) { return Some(t); }
    if let Some(t) = read_trimmed(&format!("{}/token", dir)) { return Some(t); }
    let cfg = read_trimmed(&format!("{}/config.json", dir)).and_then(|c| serde_json::from_str::<Value>(&c).ok());
    if let Some(t) = cfg.as_ref().and_then(|c| c.get("api_token")).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()) {
        return Some(t.to_string());
    }
    read_trimmed(container_key)
}

#[cfg(test)]
mod token_tests {
    use super::token_from;

    fn scratch(name: &str) -> String {
        let d = std::env::temp_dir().join(format!("ps-token-{}-{}", name, std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d.to_string_lossy().into_owned()
    }

    /// adom/adom-parts-search#12: nothing but the container key, as in a Hydrogen local workspace.
    #[test]
    fn the_container_key_signs_in_when_nothing_else_is_set() {
        let d = scratch("container");
        let key = format!("{}/api-key", d);
        std::fs::write(&key, "container-key\n").unwrap();
        assert_eq!(token_from(None, &format!("{}/nowhere", d), &key).as_deref(), Some("container-key"));
        assert_eq!(token_from(Some("  ".into()), &format!("{}/nowhere", d), &key).as_deref(), Some("container-key"));
    }

    #[test]
    fn the_cli_order_holds_env_then_stored_then_container() {
        let d = scratch("order");
        let key = format!("{}/api-key", d);
        std::fs::write(&key, "container-key").unwrap();
        std::fs::write(format!("{}/config.json", d), r#"{"api_token": "config-token"}"#).unwrap();
        assert_eq!(token_from(None, &d, &key).as_deref(), Some("config-token"));
        std::fs::write(format!("{}/token", d), "stored-token\n").unwrap();
        assert_eq!(token_from(None, &d, &key).as_deref(), Some("stored-token"));
        assert_eq!(token_from(Some("env-token".into()), &d, &key).as_deref(), Some("env-token"));
    }

    #[test]
    fn no_identity_anywhere_is_signed_out() {
        let d = scratch("none");
        assert_eq!(token_from(None, &d, &format!("{}/missing", d)), None);
        std::fs::write(format!("{}/api-key", d), "  \n").unwrap();
        assert_eq!(token_from(None, &d, &format!("{}/api-key", d)), None);
    }
}

/// Where the distributor search goes (Ray, 2026-11-04: through the wiki, which forwards to Component Ocean).
/// The public route by default; ADOM_PARTS_SEARCH_URL (with ADOM_PARTS_SEARCH_KEY and ADOM_PARTS_SEARCH_USER) points
/// it elsewhere for testing until the wiki route ships (adom/wiki#261).
pub struct Route { pub url: String, pub via: &'static str, headers: Vec<(String, String)> }

pub fn parts_search_route() -> Route {
    if let Ok(u) = std::env::var("ADOM_PARTS_SEARCH_URL") {
        if !u.trim().is_empty() {
            let mut headers = vec![];
            if let Ok(k) = std::env::var("ADOM_PARTS_SEARCH_KEY") { headers.push(("X-Adom-Request-Key".into(), k.trim().to_string())); }
            headers.push(("X-Adom-User".into(), std::env::var("ADOM_PARTS_SEARCH_USER").unwrap_or_else(|_| "anon".into())));
            if std::env::var("ADOM_PARTS_SEARCH_USER").is_err() { headers.push(("X-Adom-Anon-Ip".into(), "127.0.0.1".into())); }
            return Route { url: u.trim().to_string(), via: "test-route", headers };
        }
    }
    let headers = token().map(|t| vec![("Authorization".to_string(), format!("Bearer {}", t))]).unwrap_or_default();
    Route { url: format!("{}/api/parts-search", DEFAULT_WIKI), via: "wiki", headers }
}

pub fn post_route(r: &Route, body: Value) -> Result<Value, String> {
    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(60)).build();
    netlog("POST", &r.url);
    let mut req = agent.post(&r.url).set("Content-Type", "application/json")
        .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION"))).set("X-Adom-Client", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")));
    req = crate::host::tag(req);
    for (k, v) in &r.headers { req = req.set(k, v); }
    match req.send_json(body) {
        Ok(x) => x.into_json().map_err(|e| format!("JSON: {}", e)),
        Err(ureq::Error::Status(404, _)) if r.via == "wiki" => Err("http 404 the wiki's parts-search route is not live yet (adom/wiki#261)".into()),
        Err(ureq::Error::Status(code, x)) => Err(format!("http {} {}", code, x.into_string().unwrap_or_default().chars().take(200).collect::<String>())),
        Err(e) => Err(format!("{}", e)),
    }
}

/// ADOM_PARTS_SEARCH_NETLOG=1: print every outbound request (method, host, path) to stderr, so a test can show which
/// hosts a search touches (the wiki only).
pub fn netlog(method: &str, url: &str) {
    if std::env::var("ADOM_PARTS_SEARCH_NETLOG").map(|v| v == "1").unwrap_or(false) {
        let u = url.split('?').next().unwrap_or(url);
        eprintln!("NET {} {}", method, u);
    }
}

/// Signed in to the wiki (the wiki CLI's token is present).
pub fn signed_in() -> bool { token().is_some() }

fn get(base: &str, path: &str, tok: &Option<String>, secs: u64) -> Result<Value, String> {
    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(secs)).build();
    netlog("GET", &format!("{}{}", base.trim_end_matches('/'), path));
    let mut req = agent.get(&format!("{}{}", base.trim_end_matches('/'), path))
        .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")))
        .set("X-Adom-Caller", "parts-search");
    req = crate::host::tag(req);
    if let Some(t) = tok { req = req.set("Authorization", &format!("Bearer {}", t)); }
    match req.call() {
        Ok(r) => r.into_json().map_err(|e| format!("JSON: {}", e)),
        Err(ureq::Error::Status(code, _)) => Err(format!("http {}", code)),
        Err(e) => Err(format!("{}", e)),
    }
}

fn post(base: &str, path: &str, body: Value, tok: &Option<String>, secs: u64) -> Result<Value, String> {
    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(secs)).build();
    netlog("POST", &format!("{}{}", base.trim_end_matches('/'), path));
    let mut req = agent.post(&format!("{}{}", base.trim_end_matches('/'), path))
        .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")))
        .set("X-Adom-Caller", "parts-search").set("Content-Type", "application/json");
    req = crate::host::tag(req);
    if let Some(t) = tok { req = req.set("Authorization", &format!("Bearer {}", t)); }
    match req.send_json(body) {
        Ok(r) => r.into_json().map_err(|e| format!("JSON: {}", e)),
        Err(ureq::Error::Status(code, r)) => Err(format!("http {}: {}", code, r.into_string().unwrap_or_default().chars().take(300).collect::<String>())),
        Err(e) => Err(format!("{}", e)),
    }
}

/// Where part requests go: the wiki, or ADOM_PARTS_SEARCH_WIKI (a test wiki or a local mock) when set.
pub fn request_base() -> String {
    std::env::var("ADOM_PARTS_SEARCH_WIKI").ok().map(|u| u.trim().trim_end_matches('/').to_string())
        .filter(|u| !u.is_empty()).unwrap_or_else(|| DEFAULT_WIKI.to_string())
}

/// How a request is answered. `notify: None` leaves it to the wiki, which answers a signed-in (token) request in the
/// thread that asked: no email, a status to follow and a deadline. `Some("email")` asks for the email instead.
#[derive(Debug, Clone, Default)]
pub struct RequestOpts { pub notify: Option<String>, pub deadline_minutes: Option<u32> }

/// Have Adom's factory build a page for this part, through the wiki's own request flow (the "Request this part"
/// button posts the same call). The answer carries the request, its status link, `status_api`, `notify` and
/// `deadline_at` (wikis from 2026-12-04 on), and its position or ETA.
pub fn request(mpn: &str, urgency: &str, opts: &RequestOpts) -> Result<Value, String> {
    let tok = token();
    if tok.is_none() { return Err("not signed in to the wiki: run `adom-wiki auth login` (or set ADOM_WIKI_TOKEN), then request again".into()); }
    let base = request_base();
    let mut body = serde_json::json!({"mpn": mpn.trim(), "urgency": urgency});
    if let Some(n) = &opts.notify { body["notify"] = Value::String(n.clone()); }
    if let Some(m) = opts.deadline_minutes { body["deadline_minutes"] = Value::from(m); }
    let mut r = post(&base, "/api/part-request", body, &tok, 60)?;
    // the wiki answers site-relative links; a CLI or another app needs the full ones
    for k in ["status_url", "status_api"] {
        if let Some(u) = r.get(k).and_then(|v| v.as_str()).filter(|u| u.starts_with('/')).map(String::from) {
            r[k] = Value::String(format!("{}{}", base, u));
        }
    }
    Ok(r)
}

/// Where a request stands now (GET /api/part-request/status/<id>). With `wait`, the wiki holds the answer (at most
/// 55 s) until the state moves on from `since`, the deadline passes, or the wait runs out.
pub fn request_status(id: &str, wait: Option<(u64, Option<&str>)>) -> Result<Value, String> {
    let mut path = format!("/api/part-request/status/{}", urlencode(id));
    let mut secs = 20;
    if let Some((w, since)) = wait {
        let w = w.min(55);
        path.push_str(&format!("?wait={}", w));
        if let Some(s) = since { path.push_str(&format!("&since={}", urlencode(s))); }
        secs = w + 20;
    }
    get(&request_base(), &path, &token(), secs)
}

/// Whether adom/<slug> exists and carries a verification record (checked before an AI builds a late part itself).
#[derive(Debug, Clone, PartialEq)]
pub enum PageState { Missing, Exists { verified: bool }, Unknown(String) }

pub fn page_state(owner: &str, slug: &str, base: Option<&str>) -> PageState {
    let base = base.unwrap_or(DEFAULT_WIKI);
    let tok = token();
    match get(base, &format!("/api/pages/{}/{}", owner, slug), &tok, 10) {
        Err(e) if e == "http 404" => PageState::Missing,
        Err(e) => PageState::Unknown(e),
        Ok(_) => {
            let ver = get(base, &format!("/api/pages/{}/{}/verification", owner, slug), &tok, 10).unwrap_or(Value::Null);
            PageState::Exists { verified: has_verification(&ver) }
        }
    }
}

/// A verification record that stands: an entry verified by someone (the parts factory's publish record counts) or current.
pub fn has_verification(ver: &Value) -> bool {
    ver.pointer("/verification/entries").and_then(|v| v.as_array()).map(|a| a.iter().any(|e|
        e.get("status").and_then(|s| s.as_str()) == Some("verified") || e.get("state").and_then(|s| s.as_str()) == Some("current")))
        .unwrap_or(false)
}

/// What one page carries: CAD from component.parts, component.adom, lifecycle, and its verification state.
pub fn hit_from(r: &Value, page: &Value, verification: &Value, base: &str, query: &str) -> WikiHit {
    let owner = r.get("owner").and_then(|v| v.as_str()).unwrap_or("");
    let slug = r.get("slug").and_then(|v| v.as_str()).unwrap_or("");
    let c = page.get("component").cloned().unwrap_or(Value::Null);
    let parts = c.get("parts").cloned().unwrap_or(Value::Null);
    let has = |k: &str| parts.get(k).and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false);
    let mpn = c.get("mpn").and_then(|v| v.as_str()).unwrap_or("").to_string();
    let q = norm(query);
    let entries = verification.get("verification").and_then(|v| v.get("entries")).and_then(|v| v.as_array()).cloned().unwrap_or_default();
    let verified = if entries.iter().any(|e| e.get("state").and_then(|s| s.as_str()) == Some("current")) { "verified" }
        else if !entries.is_empty() { "stale" } else { "none" };
    let lifecycle = c.pointer("/distributor_check/manufacturer/lifecycle").and_then(|v| v.as_str()).map(String::from)
        .or_else(|| c.get("lifecycle").and_then(|v| v.as_str()).map(String::from));
    WikiHit {
        r#ref: format!("{}/{}", owner, slug),
        url: format!("{}/{}/{}", base.trim_end_matches('/'), owner, slug),
        title: r.get("title").and_then(|v| v.as_str()).unwrap_or(slug).to_string(),
        manufacturer: c.get("manufacturer").and_then(|v| v.as_str()).unwrap_or("").to_string(),
        visibility: r.get("visibility").and_then(|v| v.as_str()).unwrap_or("public").to_string(),
        exact: !q.is_empty() && (norm(&mpn) == q || norm(slug) == q),
        cad: Cad { symbol: has("symbol"), footprint: has("footprint"), model_3d: has("model_3d") || has("model_3d_plain"),
                   step: has("model_3d_step") || has("model_3d_step_plain"), lbr: has("lbr") },
        verified: verified.into(),
        adom: c.get("adom").cloned().filter(|v| v.is_object()),
        lifecycle,
        distributor_links: c.get("distributor_links").cloned().unwrap_or(Value::Null),
        stock: Value::Null,
        datasheet_url: c.get("datasheet").and_then(|v| v.get("url").or(Some(v))).and_then(|v| v.as_str()).map(String::from),
        package: c.get("package").and_then(|v| v.as_str()).unwrap_or("").to_string(),
        description: page.get("description").or_else(|| r.get("brief")).and_then(|v| v.as_str()).unwrap_or("").to_string(),
        mpn,
    }
}

/// The wiki's component pages for this query: search, then each of the top pages in full, in parallel.
pub fn search(query: &str, base: Option<&str>) -> WikiBlock {
    let base = base.unwrap_or(DEFAULT_WIKI).to_string();
    let t0 = Instant::now();
    let tok = token();
    let mut block = WikiBlock { signed_in: tok.is_some(), ..Default::default() };
    let q = urlencode(query);
    let found = match get(&base, &format!("/api/search?q={}&type=component&limit=12", q), &tok, 12) {
        Ok(v) => v,
        Err(e) => { block.error = Some(format!("wiki search failed: {}", e)); block.elapsed_ms = t0.elapsed().as_millis() as u64; return block; }
    };
    let mut results: Vec<Value> = found.get("results").and_then(|v| v.as_array()).cloned().unwrap_or_default();
    // exact slugs first, so the page for the part itself is always read in full
    let qn = norm(query);
    results.sort_by_key(|r| if norm(r.get("slug").and_then(|v| v.as_str()).unwrap_or("")) == qn { 0 } else { 1 });
    results.truncate(DETAIL_PAGES);
    let (tx, rx) = mpsc::channel::<(usize, WikiHit)>();
    for (i, r) in results.iter().cloned().enumerate() {
        let (tx, base, tok, query) = (tx.clone(), base.clone(), tok.clone(), query.to_string());
        thread::spawn(move || {
            let owner = r.get("owner").and_then(|v| v.as_str()).unwrap_or("").to_string();
            let slug = r.get("slug").and_then(|v| v.as_str()).unwrap_or("").to_string();
            let page = get(&base, &format!("/api/pages/{}/{}/files/page.json", owner, slug), &tok, 10).unwrap_or(Value::Null);
            let ver = get(&base, &format!("/api/pages/{}/{}/verification", owner, slug), &tok, 10).unwrap_or(Value::Null);
            let mut h = hit_from(&r, &page, &ver, &base, &query);
            // the cache only: this route never asks a distributor (refresh "declined" for a non-widget read)
            if h.cad.footprint || h.exact { h.stock = get(&base, &format!("/api/pages/{}/{}/stock", owner, slug), &tok, 10).unwrap_or(Value::Null); }
            let _ = tx.send((i, h));
        });
    }
    drop(tx);
    let mut hits: Vec<(usize, WikiHit)> = rx.iter().collect();
    hits.sort_by_key(|(i, h)| (if h.exact { 0 } else { 1 }, *i));
    block.hits = hits.into_iter().map(|(_, h)| h).filter(|h| h.cad.footprint || h.cad.symbol || h.exact).collect();
    block.ok = true;
    block.ready_made = block.hits.iter().any(|h| h.exact && (h.cad.symbol || h.cad.footprint));
    if !block.ready_made && looks_like_mpn(query) {
        block.request = Some(request_offer(query));
        // the orderable numbers behind it (Component Ocean answers this behind the wiki), and the miss recorded
        if let Ok(v) = get(&base, &format!("/api/part-request/candidates?q={}", q), &tok, 20) {
            block.candidates = v.get("candidates").and_then(|c| c.as_array()).cloned().unwrap_or_default();
            block.candidates.truncate(10);
        }
        match post(&base, "/api/part-search-miss", serde_json::json!({"mpn": query.trim()}), &tok, 10) {
            Ok(_) => block.miss_recorded = true,
            Err(e) => block.miss_note = Some(if e.contains("PART_SEARCH_MISS_CROSS_SITE") {
                "not recorded: the wiki accepts search misses from its own search page only (an API route is pending on the wiki side)".to_string()
            } else { format!("not recorded: {}", e.chars().take(160).collect::<String>()) }),
        }
    }
    block.elapsed_ms = t0.elapsed().as_millis() as u64;
    block
}

/// How to have Adom's factory build the page: the wiki CLI, or Component Ocean's request endpoint (the wiki's own
/// "Request this part" button posts there too).
pub fn request_offer(mpn: &str) -> Value {
    serde_json::json!({
        "mpn": mpn,
        "message": format!("No Adom wiki page for {} yet. Request it and Adom's factory builds one (symbol, footprint, 3D, datasheet).", mpn),
        "cli": format!("adom-parts-search request {}", mpn),
        "web": format!("{}/search?q={}", DEFAULT_WIKI, urlencode(mpn)),
    })
}

/// One token, letters and digits with at least one digit: a part number, not a phrase like "10k 0603 resistor".
pub fn looks_like_mpn(q: &str) -> bool {
    let q = q.trim();
    !q.is_empty() && !q.contains(char::is_whitespace) && q.chars().any(|c| c.is_ascii_digit()) && q.chars().any(|c| c.is_ascii_alphabetic())
}

pub fn urlencode(s: &str) -> String {
    s.bytes().map(|b| match b {
        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
        _ => format!("%{:02X}", b),
    }).collect()
}

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

    #[test]
    fn a_page_reports_its_cad_verification_stock_and_exact_match() {
        let r = json!({"owner": "adom", "slug": "lm358dr", "title": "LM358DR", "visibility": "public"});
        let page = json!({"component": {"mpn": "LM358DR", "manufacturer": "Texas Instruments",
            "parts": {"symbol": "lm358dr.kicad_sym", "footprint": "lm358dr.kicad_mod", "model_3d": "lm358dr-etched.glb",
                      "model_3d_step": "lm358dr-etched.step", "lbr": "lm358dr.lbr"},
            "adom": {"part_number": "LM358DR", "kind": "adom-basic", "stock": "1k+"},
            "distributor_check": {"manufacturer": {"lifecycle": "preview"}}}});
        let ver = json!({"verification": {"entries": [{"state": "current"}]}});
        let h = hit_from(&r, &page, &ver, DEFAULT_WIKI, "lm358dr");
        assert!(h.exact);
        assert!(h.cad.symbol && h.cad.footprint && h.cad.model_3d && h.cad.step && h.cad.lbr);
        assert_eq!(h.verified, "verified");
        assert_eq!(h.adom.unwrap()["stock"], "1k+");
        assert_eq!(h.lifecycle.as_deref(), Some("preview"));
        assert_eq!(h.url, "https://wiki.adom.inc/adom/lm358dr");
    }

    #[test]
    fn a_family_page_is_not_an_exact_match_and_an_old_record_is_stale() {
        let r = json!({"owner": "adom", "slug": "lm358drg"});
        let page = json!({"component": {"mpn": "LM358DRG", "parts": {"footprint": "x.kicad_mod"}}});
        let h = hit_from(&r, &page, &json!({"verification": {"entries": [{"state": "superseded"}]}}), DEFAULT_WIKI, "LM358DR");
        assert!(!h.exact);
        assert_eq!(h.verified, "stale");
        assert!(!h.cad.symbol && h.cad.footprint);
        assert_eq!(hit_from(&r, &page, &json!({"verification": null}), DEFAULT_WIKI, "x").verified, "none");
    }

    #[test]
    fn only_part_numbers_get_a_request_offer() {
        assert!(looks_like_mpn("LM2903L-Q1"));
        assert!(!looks_like_mpn("10k 0603 resistor"));
        assert!(!looks_like_mpn("resistor"));
        assert_eq!(request_offer("LM2903L-Q1")["cli"], "adom-parts-search request LM2903L-Q1");
    }
}