//! Data directory configuration for locating DataBundle files on disk.

use std::path::{Path, PathBuf};

/// Configures where the [`Mapper`](crate::Mapper) looks for `DataBundle` files.
///
/// Bundle files follow the naming convention `edifact-data-{FV}.bin`
/// (e.g., `edifact-data-FV2504.bin`).
///
/// # Resolution order for [`DataDir::auto`]
///
/// 1. `$EDIFACT_DATA_DIR` environment variable (if set)
/// 2. `$HOME/.edifact/data` (Unix) or `%USERPROFILE%\.edifact\data` (Windows)
/// 3. `./data` (current working directory fallback)
#[derive(Debug, Clone)]
pub struct DataDir {
    path: PathBuf,
    eager_fvs: Vec<String>,
}

impl DataDir {
    /// Auto-detect the data directory from the environment.
    ///
    /// See [struct-level docs](DataDir) for resolution order.
    pub fn auto() -> Self {
        let path = if let Ok(env_dir) = std::env::var("EDIFACT_DATA_DIR") {
            PathBuf::from(env_dir)
        } else if let Some(home) = home_dir() {
            home.join(".edifact").join("data")
        } else {
            PathBuf::from("data")
        };
        Self {
            path,
            eager_fvs: vec![],
        }
    }

    /// Use an explicit path for the data directory.
    pub fn path<P: AsRef<Path>>(path: P) -> Self {
        Self {
            path: path.as_ref().to_path_buf(),
            eager_fvs: vec![],
        }
    }

    /// Mark format versions to be eagerly loaded when the [`Mapper`](crate::Mapper)
    /// is created (rather than lazy-loaded on first access).
    pub fn eager(mut self, fvs: &[&str]) -> Self {
        self.eager_fvs = fvs.iter().map(|s| s.to_string()).collect();
        self
    }

    /// The resolved data directory path.
    pub fn data_path(&self) -> &Path {
        &self.path
    }

    /// Format versions that should be eagerly loaded.
    pub fn eager_fvs(&self) -> &[String] {
        &self.eager_fvs
    }

    /// Path to the bundle file for a specific format version.
    pub fn bundle_path(&self, fv: &str) -> PathBuf {
        self.path.join(format!("edifact-data-{fv}.bin"))
    }
}

fn home_dir() -> Option<PathBuf> {
    std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .ok()
        .map(PathBuf::from)
}
