use std::env;
use std::fs;
use std::path::PathBuf;

const DEFAULT_BACKGROUND_BYTES: &[u8] = include_bytes!("../assets/default-background.png");
const DEFAULT_BACKGROUND_FILE_NAME: &str = "default-background.png";

pub fn ensure_default_background() -> Result<PathBuf, String> {
    let path = default_background_path()?;
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|error| {
            format!(
                "failed to create default background directory '{}': {error}",
                parent.display()
            )
        })?;
    }

    if !matches!(fs::read(&path), Ok(contents) if contents.as_slice() == DEFAULT_BACKGROUND_BYTES) {
        fs::write(&path, DEFAULT_BACKGROUND_BYTES).map_err(|error| {
            format!(
                "failed to write default background '{}': {error}",
                path.display()
            )
        })?;
    }

    Ok(path)
}

fn default_background_path() -> Result<PathBuf, String> {
    Ok(data_home()?.join("lios").join(DEFAULT_BACKGROUND_FILE_NAME))
}

fn data_home() -> Result<PathBuf, String> {
    if let Ok(data_home) = env::var("XDG_DATA_HOME") {
        if !data_home.is_empty() {
            return Ok(PathBuf::from(data_home));
        }
    }

    let home = env::var("HOME")
        .map_err(|_| "unable to determine data directory; set HOME or XDG_DATA_HOME".to_string())?;
    if home.is_empty() {
        return Err("unable to determine data directory; HOME is empty".to_string());
    }

    Ok(PathBuf::from(home).join(".local/share"))
}
