use anyhow::Result;
use std::path::PathBuf;

pub struct Entry {
    pub mpn: String,
    pub has_step: bool,
    pub has_mod: bool,
    pub has_sym: bool,
    pub has_pdf: bool,
}

pub fn root() -> PathBuf {
    let here = std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(|p| p.to_path_buf()))
        .unwrap_or_else(|| PathBuf::from("."));
    if let Some(env) = std::env::var_os("CHIP_FETCHER_LIB") {
        return PathBuf::from(env);
    }
    let candidate = PathBuf::from("/home/adom/project/chip-fetcher/library");
    if candidate.exists() {
        return candidate;
    }
    here.join("library")
}

pub fn ensure_dir(mpn: &str) -> Result<PathBuf> {
    let dir = root().join(mpn);
    std::fs::create_dir_all(&dir)?;
    Ok(dir)
}

pub fn status(mpn: &str) -> Result<Entry> {
    let dir = root().join(mpn);
    Ok(Entry {
        mpn: mpn.to_string(),
        has_step: dir.join(format!("{mpn}.step")).exists(),
        has_mod:  dir.join(format!("{mpn}.kicad_mod")).exists(),
        has_sym:  dir.join(format!("{mpn}.kicad_sym")).exists(),
        has_pdf:  dir.join(format!("{mpn}.pdf")).exists(),
    })
}

pub fn scan() -> Result<Vec<Entry>> {
    let root = root();
    if !root.exists() { return Ok(vec![]); }
    let mut out = Vec::new();
    for entry in std::fs::read_dir(&root)? {
        let entry = entry?;
        if !entry.file_type()?.is_dir() { continue; }
        let mpn = entry.file_name().to_string_lossy().into_owned();
        out.push(status(&mpn)?);
    }
    out.sort_by(|a, b| a.mpn.cmp(&b.mpn));
    Ok(out)
}