pub fn base_part(mpn: &str) -> String {
    let s = mpn.trim_end_matches(|c: char| c == 'R' || c == 'T');
    let chars: Vec<char> = s.chars().collect();
    let n = chars.len();
    let mut i = n;
    while i > 0 && chars[i - 1].is_ascii_digit() { i -= 1; }
    let after_digits = i;
    while i > 0 && chars[i - 1].is_ascii_alphabetic() { i -= 1; }
    let after_alpha = i;
    if after_alpha < after_digits && after_alpha > 0 && chars[after_alpha - 1].is_ascii_digit() {
        chars[..after_alpha].iter().collect()
    } else {
        s.to_string()
    }
}

pub fn product_url(mpn: &str) -> String {
    format!("https://www.ti.com/product/{}", base_part(mpn))
}

/// Land on the TI product page anchored to the CAD section.
/// User clicks "CAD/CAE Symbols & Footprints" → UL opens with the right part pre-loaded.
/// TI.com's part picker is much better than UL's search.
pub fn cad_url(mpn: &str) -> String {
    format!("https://www.ti.com/product/{}#cad-cae-symbols", base_part(mpn))
}

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

    #[test]
    fn strips_package_and_reel() {
        assert_eq!(base_part("TPS62840DLCR"), "TPS62840");
        assert_eq!(base_part("INA226AIDGSR"), "INA226");
        assert_eq!(base_part("LM358DR"), "LM358");
        assert_eq!(base_part("LM358"), "LM358");
        assert_eq!(base_part("MSP430G2553IPW20"), "MSP430G2553");
        assert_eq!(base_part("DRV8825PWPR"), "DRV8825");
        assert_eq!(base_part("ADS1115IDGSR"), "ADS1115");
        assert_eq!(base_part("ADS1115"), "ADS1115");
    }
}