use std::{fs, io, path::Path};

/// Lightweight metadata stored at the layer level (`layer_meta.json`).
///
/// Written by `obilayeredmap::MphfLayer::build` alongside `mphf.bin`.
/// Read by `PersistentBitMatrix::open` to determine `n_rows` for the
/// implicit (mono-genome presence/absence) case.
pub struct LayerMeta {
    pub n: usize,
}

impl LayerMeta {
    pub const FILENAME: &'static str = "layer_meta.json";

    pub fn save(layer_dir: &Path, n: usize) -> io::Result<()> {
        fs::write(layer_dir.join(Self::FILENAME), format!("{{\"n\":{n}}}\n"))
    }

    pub fn load(layer_dir: &Path) -> io::Result<Self> {
        let s = fs::read_to_string(layer_dir.join(Self::FILENAME))?;
        Self::parse(&s)
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "bad layer_meta.json"))
    }

    fn parse(s: &str) -> Option<Self> {
        Some(Self { n: crate::meta::field(s, "n")? })
    }
}
