//! Read access to the device navdata store the tools share.

use aerocontext_core::NavDataSnapshot;
use chrono::{NaiveDate, Utc};

use crate::error::ToolError;

/// Decode the store blob effective today (UTC), from
/// `$AEROCONTEXT_NAVDATA_STORE` else `~/.aerocontext/navdata`.
pub(crate) async fn load_current_snapshot() -> Result<NavDataSnapshot, ToolError> {
    load_snapshot_for(Utc::now().date_naive()).await
}

/// Decode the store blob effective on `date` — the ETD's date for a
/// departure-anchored brief.
pub(crate) async fn load_snapshot_for(date: NaiveDate) -> Result<NavDataSnapshot, ToolError> {
    let store = aerocontext_navdata::sync::default_store();
    let path = aerocontext_navdata::sync::current_blob(&store, date)
        .await?
        .ok_or_else(|| ToolError::StoreEmpty {
            store: store.display().to_string(),
            date,
        })?;
    let bytes = tokio::fs::read(&path)
        .await
        .map_err(|cause| ToolError::BlobRead {
            path: path.display().to_string(),
            cause,
        })?;
    aerocontext_navdata::blob::decode(&bytes).map_err(|cause| ToolError::BlobDecode {
        path: path.display().to_string(),
        cause,
    })
}
