use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::LazyLock;
use std::time::Instant;

use crate::BString;
use crate::bstr;

pub struct Vars {
    simple: HashMap<BString, BString>,
    magic: HashMap<BString, fn() -> BString>,
    all: HashSet<BString>,
    export: HashSet<BString>,
}

impl Vars {
    fn new(
        mut simple: HashMap<BString, BString>,
        magic: HashMap<BString, fn() -> BString>,
    ) -> Self {
        for (var, val) in std::env::vars_os() {
            simple.insert(var.into_encoded_bytes(), val.into_encoded_bytes());
        }
        let all = simple
            .keys()
            .cloned()
            .chain(magic.keys().cloned())
            .collect();
        let export = std::env::vars_os()
            .map(|x| x.0.into_encoded_bytes())
            .collect();
        Self {
            simple,
            magic,
            all,
            export,
        }
    }

    pub fn set(&mut self, var: BString, val: BString) {
        self.simple.insert(var.clone(), val);
        self.all.insert(var);
    }

    pub fn lookup<'a>(&'a self, var: &bstr) -> Option<Cow<'a, bstr>> {
        if let Some(fun) = self.magic.get(var) {
            return Some(Cow::Owned(fun()));
        }

        if let Some(val) = self.simple.get(var) {
            return Some(Cow::Borrowed(val));
        }

        None
    }

    pub fn allow_export(&mut self, var: &bstr, allow: bool) {
        if allow {
            self.export.insert(var.to_vec());
        } else {
            self.export.remove(var);
        }
    }

    pub fn export<'a>(&'a self) -> HashMap<&'a bstr, Cow<'a, bstr>> {
        self.export
            .iter()
            .filter_map(|var| {
                let val = self.lookup(var)?;
                Some((var.as_ref(), val))
            })
            .collect()
    }

    pub fn vars(&self) -> &HashSet<BString> {
        &self.all
    }
}

macro_rules! map {
    ($($key:expr => $val:expr),* $(,)?) => {{
        let mut map = HashMap::<BString, _, _>::new();
        $(map.insert($key.into(), $val);)*
        map
    }};
}

impl Default for Vars {
    fn default() -> Self {
        let simple = map! {
            b"PISH_VERSION" => crate::consts::PISH_VERSION.as_bytes().to_vec(),
            b"PISH_COMMIT" => crate::consts::PISH_COMMIT.as_bytes().to_vec(),
            b"PISH_DIRTY" => vec![crate::consts::PISH_DIRTY as u8 + b'0'],
        };

        let magic = map! {
            b"CWD_PRETTY" => crate::pretty_cwd as _,
            b"SECONDS" => seconds_since_startup as _,
        };

        // call it once such that lazylock gets initialized
        seconds_since_startup();

        Self::new(simple, magic)
    }
}

static START: LazyLock<Instant> = LazyLock::new(Instant::now);

fn seconds_since_startup() -> BString {
    format!("{}", START.elapsed().as_secs_f64() as u64).into_bytes()
}
