-e 
# key.rs
use std::cmp::Ordering;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// `KeyDetail` represents a detailed key with multiple attributes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct KeyDetail {
    pub name: String,
    pub value: String,
    pub description: Option<String>,
    pub enabled: bool,
    pub metadata: Option<HashMap<String, String>>,
    pub last_updated: Option<String>,
    pub created_at: Option<String>,
    pub tags: Option<Vec<String>>,
}


impl Ord for KeyDetail {
    fn cmp(&self, other: &Self) -> Ordering {
        self.name.cmp(&other.name).then_with(|| self.value.cmp(&other.value))
    }
}

impl PartialOrd for KeyDetail {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// `KeyValue` represents a simple key-value pair.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct KeyValue {
    pub name: String,
    pub value: String,
}

/// `Key` is an enum that can hold different types of key representations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(untagged)]
pub enum Key {
    Value(String),
    KeyDetail(KeyDetail),
    KeyValue(KeyValue),
}

/// `KeyTransform` is a trait for transforming keys between different representations.
pub trait KeyTransform {
    fn to_key_detail(&self, name: Option<&str>) -> KeyDetail;
    fn to_key_value(&self) -> KeyValue;
    fn to_value(&self) -> String;
}

impl KeyTransform for KeyDetail {
    fn to_key_detail(&self, _name: Option<&str>) -> KeyDetail {
        self.clone()
    }

    fn to_key_value(&self) -> KeyValue {
        KeyValue {
            name: self.name.clone(),
            value: self.value.clone(),
        }
    }

    fn to_value(&self) -> String {
        self.value.clone()
    }
}

impl KeyTransform for KeyValue {
    fn to_key_detail(&self, _name: Option<&str>) -> KeyDetail {
        KeyDetail {
            name: self.name.clone(),
            value: self.value.clone(),
            description: None,
            enabled: true,
            metadata: None,
            last_updated: None,
            created_at: None,
            tags: None,
        }
    }

    fn to_key_value(&self) -> KeyValue {
        self.clone()
    }

    fn to_value(&self) -> String {
        self.value.clone()
    }
}

impl KeyTransform for Key {
    fn to_key_detail(&self, name: Option<&str>) -> KeyDetail {
        match self {
            Key::Value(value) => KeyDetail {
                name: name.unwrap_or("").to_string(),
                value: value.clone(),
                description: None,
                enabled: true,
                metadata: None,
                last_updated: None,
                created_at: None,
                tags: None,
            },
            Key::KeyDetail(detail) => detail.clone(),
            Key::KeyValue(kv) => kv.to_key_detail(None),
        }
    }

    fn to_key_value(&self) -> KeyValue {
        match self {
            Key::Value(value) => KeyValue {
                name: "".to_string(),
                value: value.clone(),
            },
            Key::KeyDetail(detail) => KeyValue {
                name: detail.name.clone(),
                value: detail.value.clone(),
            },
            Key::KeyValue(kv) => kv.clone(),
        }
    }

    fn to_value(&self) -> String {
        match self {
            Key::Value(value) => value.clone(),
            Key::KeyDetail(detail) => detail.value.clone(),
            Key::KeyValue(kv) => kv.value.clone(),
        }
    }
}
-e 
# env.rs
use async_trait::async_trait;
use std::collections::{BTreeMap, HashMap};
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::{Key, KeyDetail, KeyTransform};
use crate::file::key_collection::KeyCollection;
use std::path::PathBuf;

pub struct EnvAdapter;

#[async_trait]
impl FormatAdapter for EnvAdapter {
    fn extension(&self) -> &str {
        "env"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let contents = std::fs::read_to_string(path)?;
        let mut map = BTreeMap::new();
        let mut current_comment: Option<String> = None;

        for line in contents.lines() {
            let trimmed_line = line.trim();
            if trimmed_line.starts_with('#') {
                // Capture comment
                current_comment = Some(trimmed_line.trim_start_matches('#').trim().to_string());
            } else if !trimmed_line.is_empty() {
                // Process key-value pair
                let parts: Vec<&str> = trimmed_line.splitn(2, '=').collect();
                if parts.len() == 2 {
                    let key_name = parts[0].trim().to_string();
                    let value = parts[1].trim().to_string();
                    let key = Key::KeyDetail(KeyDetail {
                        name: key_name.clone(),
                        value: value.clone(),
                        description: current_comment.clone(),
                        enabled: true,
                        metadata: None,
                        last_updated: None,
                        created_at: None,
                        tags: None,
                    });
                    map.insert(key_name, key);
                    current_comment = None; // Reset comment after using it
                }
            }
        }

        Ok(KeyCollection::Map(map))
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        let result = keys
            .iter()
            .map(|(k, key)| match key {
                Key::Value(value) => format!("{}={}", k, value),
                Key::KeyDetail(detail) => {
                    if let Some(ref description) = detail.description {
                        format!("# {}
{}={}", description, detail.name, detail.value)
                    } else {
                        format!("{}={}", detail.name, detail.value)
                    }
                }
                Key::KeyValue(kv) => format!("{}={}", kv.name, kv.value),
            })
            .collect::<Vec<_>>()
            .join("
")
            .trim()
            .to_string();

        std::fs::write(path, result.as_bytes())?;
        Ok(())
    }
}
-e 
# key_collection.rs
use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
use crate::file::key::{Key, KeyDetail, KeyTransform, KeyValue};
use crate::file::Sort;

/// `KeyCollectionTransform` is a trait for transforming collections of keys between different representations.
pub trait KeyCollectionTransform {
    /// Transforms the implementor into a collection of `KeyDetail` mapped by key names.
    fn to_key_detail_collection(&self) -> KeyCollection;
    /// Transforms the implementor into a collection of `KeyValue` mapped by key names.
    fn to_key_value_collection(&self) -> KeyCollection;
    /// Transforms the implementor into a collection of simple string values mapped by key names.
    fn to_value_collection(&self) -> KeyCollection;
}

/// `KeyCollectionMap` is a type alias for a `HashMap` where the key is a `String` and the value is a `Key`.
pub(crate) type KeyCollectionMap = BTreeMap<String, Key>;


/// `KeyCollectionList` is a type alias for a `Vec` of `Key`.
///
///
type KeyCollectionList = Vec<Key>;

// impl Sort for KeyCollection {
//     fn sort(&mut self) {
//         match self {
//             KeyCollection::Map(map) => {
//                 let sorted_map: BTreeMap<_, _> = map.iter().collect();
//                 *map = sorted_map.into_iter().map(|(k, v)| (k.clone(), v.clone())).collect();
//             },
//             KeyCollection::List(list) => {
//                 list.sort();
//             }
//         }
//     }
// }


impl IntoIterator for KeyCollection {
    type Item = (String, Key);
    type IntoIter = Box<dyn Iterator<Item = (String, Key)>>;

    fn into_iter(self) -> Self::IntoIter {
        match self {
            KeyCollection::Map(map) => Box::new(map.into_iter()),
            KeyCollection::List(list) => Box::new(list.into_iter().enumerate().map(|(i, key)| (i.to_string(), key))),
        }
    }
}

pub struct KeyCollectionIter<'a> {
    inner: Box<dyn Iterator<Item = (String, &'a Key)> + 'a>,
}

impl<'a> Iterator for KeyCollectionIter<'a> {
    type Item = (String, &'a Key);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a> KeyCollection {
    pub fn iter(&'a self) -> KeyCollectionIter<'a> {
        match self {
            KeyCollection::Map(map) => {
                let map_iter = map.iter().map(|(k, v)| (k.clone(), v));
                KeyCollectionIter {
                    inner: Box::new(map_iter),
                }
            }
            KeyCollection::List(list) => {
                let list_iter = list.iter().enumerate().map(|(index, key)| {
                    let key_str = index.to_string();
                    (key_str, key)
                });
                KeyCollectionIter {
                    inner: Box::new(list_iter),
                }
            }
        }
    }
}

// impl PartialEq for KeyCollectionMap {
//     fn eq(&self, other: &Self) -> bool {
//         self.iter().eq(other.iter())
//     }
// }

// impl PartialEq for KeyCollection {
//     fn eq(&self, other: &Self) -> bool {
//         match (self, other) {
//             (KeyCollection::Map(map1), KeyCollection::Map(map2)) => map1 == map2,
//             (KeyCollection::List(list1), KeyCollection::List(list2)) => list1 == list2,
//             _ => false,
//         }
//     }
// }


/// `KeyCollection` is an enum that can hold different types of key collections.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
// flatten
#[serde(untagged)]
pub enum KeyCollection {
    /// A collection represented as a `HashMap`.
    Map(KeyCollectionMap),
    /// A collection represented as a `Vec`.
    List(KeyCollectionList),
}

// Eq , PartialEq , Ord and PartialOrd
// impl

impl KeyCollectionTransform for KeyCollectionMap {
    fn to_key_detail_collection(&self) -> KeyCollection {
        KeyCollection::Map(
            self.iter()
                .map(|(name, key)| (name.clone(), Key::KeyDetail(key.to_key_detail(Some(name)))))
                .collect(),
        )
    }

    fn to_key_value_collection(&self) -> KeyCollection {
        KeyCollection::Map(
            self.iter()
                .map(|(name, key)| (name.clone(), Key::KeyValue(key.to_key_value())))
                .collect(),
        )
    }

    fn to_value_collection(&self) -> KeyCollection {
        KeyCollection::Map(
            self.iter()
                .map(|(name, key)| (name.clone(), Key::Value(key.to_value())))
                .collect(),
        )
    }
}

impl KeyCollectionTransform for KeyCollectionList {
    fn to_key_detail_collection(&self) -> KeyCollection {
        KeyCollection::List(
            self.iter()
                .map(|key| Key::KeyDetail(key.to_key_detail(None)))
                .collect(),
        )
    }

    fn to_key_value_collection(&self) -> KeyCollection {
        KeyCollection::List(
            self.iter()
                .map(|key| Key::KeyValue(key.to_key_value()))
                .collect(),
        )
    }

    fn to_value_collection(&self) -> KeyCollection {
        KeyCollection::List(
            self.iter()
                .map(|key| Key::Value(key.to_value()))
                .collect(),
        )
    }
}

impl KeyCollectionTransform for KeyCollection {
    fn to_key_detail_collection(&self) -> KeyCollection {
        match self {
            KeyCollection::Map(map) => map.to_key_detail_collection(),
            KeyCollection::List(list) => list.to_key_detail_collection(),
        }
    }

    fn to_key_value_collection(&self) -> KeyCollection {
        match self {
            KeyCollection::Map(map) => map.to_key_value_collection(),
            KeyCollection::List(list) => list.to_key_value_collection(),
        }
    }

    fn to_value_collection(&self) -> KeyCollection {
        match self {
            KeyCollection::Map(map) => map.to_value_collection(),
            KeyCollection::List(list) => list.to_value_collection(),
        }
    }
}
-e 
# json.rs
use async_trait::async_trait;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::{Key, KeyDetail, KeyTransform};
use crate::file::key_collection::KeyCollection;
use serde_json;

pub struct JsonAdapter;

#[async_trait]
impl FormatAdapter for JsonAdapter {
    fn extension(&self) -> &str {
        "json"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        // Load keys from the main JSON file
        let contents = std::fs::read_to_string(path).map_err(FluxError::from)?;
        let keys: KeyCollection = serde_json::from_str(&contents).map_err(FluxError::from)?;
        Ok(keys)
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        // Save the main JSON file
        let contents = serde_json::to_string_pretty(keys).map_err(FluxError::from)?;
        let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(path)?;
        file.write_all(contents.as_bytes())?;

        // Save metadata to a separate file
        // let meta_path = PathBuf::from(path).with_extension("meta.json");
        // if let KeyCollection::Map(ref map) = keys {
        //     let meta_map: HashMap<String, KeyDetail> = map
        //         .iter()
        //         .filter_map(|(key, k)| match k {
        //             Key::KeyDetail(detail) => Some((key.clone(), detail.clone())),
        //             _ => None,
        //         })
        //         .collect();
        //     let meta_contents = serde_json::to_string_pretty(&meta_map).map_err(FluxError::from)?;
        //     let mut meta_file = OpenOptions::new().write(true).create(true).truncate(true).open(meta_path)?;
        //     meta_file.write_all(meta_contents.as_bytes())?;
        // }

        Ok(())
    }
}
-e 
# mod.rs
pub mod env;
pub mod format_adapter;
pub mod json;
pub mod toml;
pub mod yaml;
pub mod postman;
pub mod key;
pub mod key_collection;


// use crate::file::format_adapter::FormatAdapter;


use crate::file::json::JsonAdapter;
use crate::file::toml::TomlAdapter;
use crate::file::yaml::YamlAdapter;
use crate::file::postman::PostmanAdapter;
use crate::file::env::EnvAdapter;


/// Sort trait for KeyCollection
pub trait Sort {
    fn sort(&mut self);
}
-e 
# toml.rs
use async_trait::async_trait;
use std::collections::HashMap;
use std::path::PathBuf;
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::Key;
use toml;
use crate::file::key_collection::KeyCollection;

pub struct TomlAdapter;

#[async_trait]
impl FormatAdapter for TomlAdapter {
    fn extension(&self) -> &str {
        "toml"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let contents = std::fs::read_to_string(path)?;
        toml::from_str(&contents).map_err(FluxError::from)
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        let contents = toml::to_string_pretty(keys).map_err(FluxError::from)?;
        std::fs::write(path, contents.as_bytes())?;
        Ok(())
    }
}
-e 
# format_adapter.rs
use async_trait::async_trait;
use std::collections::HashMap;
use std::fs;
use std::fs::{OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use crate::error::FluxError;
use crate::file::key::Key;

extern crate toml;

use crate::file::*;
use crate::file::key_collection::KeyCollection;

/// Trait for format adapters to handle different file formats.
#[async_trait]
pub trait FormatAdapter {
    fn extension(&self) -> &str;
    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError>;
    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError>;
}

/// Manages different format adapters for loading and saving key collections.
pub struct FormatManager {
    adapters: HashMap<String, Box<dyn FormatAdapter + Send + Sync>>,
}

impl FormatManager {
    /// Creates a new `FormatManager` with registered adapters.
    pub fn new() -> Self {
        let mut adapters = HashMap::new();
        adapters.insert("env".to_string(), Box::new(EnvAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("json".to_string(), Box::new(JsonAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("yaml".to_string(), Box::new(YamlAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("yml".to_string(), Box::new(YamlAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("toml".to_string(), Box::new(TomlAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("postman_environment.json".to_string(), Box::new(PostmanAdapter) as Box<dyn FormatAdapter + Send + Sync>);

        FormatManager { adapters }
    }

    /// Retrieves the appropriate adapter based on file extension.
    pub fn get_adapter(&self, extension: &str) -> Option<&Box<dyn FormatAdapter + Send + Sync>> {
        self.adapters.get(extension)
    }

    /// Loads keys from a file using the appropriate adapter.
    pub fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let extension = Path::new(path).extension().and_then(|ext| ext.to_str()).unwrap_or("");
        let adapter = self.get_adapter(extension).ok_or_else(|| FluxError::UnsupportedFormat(extension.to_string()))?;

        // let mut file = OpenOptions::new().read(true).open(path)?;
        // let mut contents = String::new();
        // file.read_to_string(&mut contents)?;
        adapter.load_keys(path)
    }

    /// Saves keys to a file using the appropriate adapter.
    pub fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        // Debugging the current directory
        let current_dir = std::env::current_dir()?;
        println!("Current directory: {:?}", current_dir);

        let extension = Path::new(path).extension().and_then(|ext| ext.to_str()).unwrap_or("");
        let adapter = self.get_adapter(extension).ok_or_else(|| FluxError::UnsupportedFormat(extension.to_string()))?;

        // Ensure the directory exists
        if let Some(parent) = Path::new(path).parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }

        // Save the keys using the adapter
        adapter.save_keys(path, keys)?;

        Ok(())
    }
}
-e 
# combined_file.txt
-e 
# key.rs
use std::cmp::Ordering;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// `KeyDetail` represents a detailed key with multiple attributes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct KeyDetail {
    pub name: String,
    pub value: String,
    pub description: Option<String>,
    pub enabled: bool,
    pub metadata: Option<HashMap<String, String>>,
    pub last_updated: Option<String>,
    pub created_at: Option<String>,
    pub tags: Option<Vec<String>>,
}


impl Ord for KeyDetail {
    fn cmp(&self, other: &Self) -> Ordering {
        self.name.cmp(&other.name).then_with(|| self.value.cmp(&other.value))
    }
}

impl PartialOrd for KeyDetail {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// `KeyValue` represents a simple key-value pair.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct KeyValue {
    pub name: String,
    pub value: String,
}

/// `Key` is an enum that can hold different types of key representations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(untagged)]
pub enum Key {
    Value(String),
    KeyDetail(KeyDetail),
    KeyValue(KeyValue),
}

/// `KeyTransform` is a trait for transforming keys between different representations.
pub trait KeyTransform {
    fn to_key_detail(&self, name: Option<&str>) -> KeyDetail;
    fn to_key_value(&self) -> KeyValue;
    fn to_value(&self) -> String;
}

impl KeyTransform for KeyDetail {
    fn to_key_detail(&self, _name: Option<&str>) -> KeyDetail {
        self.clone()
    }

    fn to_key_value(&self) -> KeyValue {
        KeyValue {
            name: self.name.clone(),
            value: self.value.clone(),
        }
    }

    fn to_value(&self) -> String {
        self.value.clone()
    }
}

impl KeyTransform for KeyValue {
    fn to_key_detail(&self, _name: Option<&str>) -> KeyDetail {
        KeyDetail {
            name: self.name.clone(),
            value: self.value.clone(),
            description: None,
            enabled: true,
            metadata: None,
            last_updated: None,
            created_at: None,
            tags: None,
        }
    }

    fn to_key_value(&self) -> KeyValue {
        self.clone()
    }

    fn to_value(&self) -> String {
        self.value.clone()
    }
}

impl KeyTransform for Key {
    fn to_key_detail(&self, name: Option<&str>) -> KeyDetail {
        match self {
            Key::Value(value) => KeyDetail {
                name: name.unwrap_or("").to_string(),
                value: value.clone(),
                description: None,
                enabled: true,
                metadata: None,
                last_updated: None,
                created_at: None,
                tags: None,
            },
            Key::KeyDetail(detail) => detail.clone(),
            Key::KeyValue(kv) => kv.to_key_detail(None),
        }
    }

    fn to_key_value(&self) -> KeyValue {
        match self {
            Key::Value(value) => KeyValue {
                name: "".to_string(),
                value: value.clone(),
            },
            Key::KeyDetail(detail) => KeyValue {
                name: detail.name.clone(),
                value: detail.value.clone(),
            },
            Key::KeyValue(kv) => kv.clone(),
        }
    }

    fn to_value(&self) -> String {
        match self {
            Key::Value(value) => value.clone(),
            Key::KeyDetail(detail) => detail.value.clone(),
            Key::KeyValue(kv) => kv.value.clone(),
        }
    }
}
-e 
# env.rs
use async_trait::async_trait;
use std::collections::{BTreeMap, HashMap};
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::{Key, KeyDetail, KeyTransform};
use crate::file::key_collection::KeyCollection;
use std::path::PathBuf;

pub struct EnvAdapter;

#[async_trait]
impl FormatAdapter for EnvAdapter {
    fn extension(&self) -> &str {
        "env"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let contents = std::fs::read_to_string(path)?;
        let mut map = BTreeMap::new();
        let mut current_comment: Option<String> = None;

        for line in contents.lines() {
            let trimmed_line = line.trim();
            if trimmed_line.starts_with('#') {
                // Capture comment
                current_comment = Some(trimmed_line.trim_start_matches('#').trim().to_string());
            } else if !trimmed_line.is_empty() {
                // Process key-value pair
                let parts: Vec<&str> = trimmed_line.splitn(2, '=').collect();
                if parts.len() == 2 {
                    let key_name = parts[0].trim().to_string();
                    let value = parts[1].trim().to_string();
                    let key = Key::KeyDetail(KeyDetail {
                        name: key_name.clone(),
                        value: value.clone(),
                        description: current_comment.clone(),
                        enabled: true,
                        metadata: None,
                        last_updated: None,
                        created_at: None,
                        tags: None,
                    });
                    map.insert(key_name, key);
                    current_comment = None; // Reset comment after using it
                }
            }
        }

        Ok(KeyCollection::Map(map))
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        let result = keys
            .iter()
            .map(|(k, key)| match key {
                Key::Value(value) => format!("{}={}", k, value),
                Key::KeyDetail(detail) => {
                    if let Some(ref description) = detail.description {
                        format!("# {}
{}={}", description, detail.name, detail.value)
                    } else {
                        format!("{}={}", detail.name, detail.value)
                    }
                }
                Key::KeyValue(kv) => format!("{}={}", kv.name, kv.value),
            })
            .collect::<Vec<_>>()
            .join("
")
            .trim()
            .to_string();

        std::fs::write(path, result.as_bytes())?;
        Ok(())
    }
}
-e 
# key_collection.rs
use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
use crate::file::key::{Key, KeyDetail, KeyTransform, KeyValue};
use crate::file::Sort;

/// `KeyCollectionTransform` is a trait for transforming collections of keys between different representations.
pub trait KeyCollectionTransform {
    /// Transforms the implementor into a collection of `KeyDetail` mapped by key names.
    fn to_key_detail_collection(&self) -> KeyCollection;
    /// Transforms the implementor into a collection of `KeyValue` mapped by key names.
    fn to_key_value_collection(&self) -> KeyCollection;
    /// Transforms the implementor into a collection of simple string values mapped by key names.
    fn to_value_collection(&self) -> KeyCollection;
}

/// `KeyCollectionMap` is a type alias for a `HashMap` where the key is a `String` and the value is a `Key`.
pub(crate) type KeyCollectionMap = BTreeMap<String, Key>;


/// `KeyCollectionList` is a type alias for a `Vec` of `Key`.
///
///
type KeyCollectionList = Vec<Key>;

// impl Sort for KeyCollection {
//     fn sort(&mut self) {
//         match self {
//             KeyCollection::Map(map) => {
//                 let sorted_map: BTreeMap<_, _> = map.iter().collect();
//                 *map = sorted_map.into_iter().map(|(k, v)| (k.clone(), v.clone())).collect();
//             },
//             KeyCollection::List(list) => {
//                 list.sort();
//             }
//         }
//     }
// }


impl IntoIterator for KeyCollection {
    type Item = (String, Key);
    type IntoIter = Box<dyn Iterator<Item = (String, Key)>>;

    fn into_iter(self) -> Self::IntoIter {
        match self {
            KeyCollection::Map(map) => Box::new(map.into_iter()),
            KeyCollection::List(list) => Box::new(list.into_iter().enumerate().map(|(i, key)| (i.to_string(), key))),
        }
    }
}

pub struct KeyCollectionIter<'a> {
    inner: Box<dyn Iterator<Item = (String, &'a Key)> + 'a>,
}

impl<'a> Iterator for KeyCollectionIter<'a> {
    type Item = (String, &'a Key);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a> KeyCollection {
    pub fn iter(&'a self) -> KeyCollectionIter<'a> {
        match self {
            KeyCollection::Map(map) => {
                let map_iter = map.iter().map(|(k, v)| (k.clone(), v));
                KeyCollectionIter {
                    inner: Box::new(map_iter),
                }
            }
            KeyCollection::List(list) => {
                let list_iter = list.iter().enumerate().map(|(index, key)| {
                    let key_str = index.to_string();
                    (key_str, key)
                });
                KeyCollectionIter {
                    inner: Box::new(list_iter),
                }
            }
        }
    }
}

// impl PartialEq for KeyCollectionMap {
//     fn eq(&self, other: &Self) -> bool {
//         self.iter().eq(other.iter())
//     }
// }

// impl PartialEq for KeyCollection {
//     fn eq(&self, other: &Self) -> bool {
//         match (self, other) {
//             (KeyCollection::Map(map1), KeyCollection::Map(map2)) => map1 == map2,
//             (KeyCollection::List(list1), KeyCollection::List(list2)) => list1 == list2,
//             _ => false,
//         }
//     }
// }


/// `KeyCollection` is an enum that can hold different types of key collections.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
// flatten
#[serde(untagged)]
pub enum KeyCollection {
    /// A collection represented as a `HashMap`.
    Map(KeyCollectionMap),
    /// A collection represented as a `Vec`.
    List(KeyCollectionList),
}

// Eq , PartialEq , Ord and PartialOrd
// impl

impl KeyCollectionTransform for KeyCollectionMap {
    fn to_key_detail_collection(&self) -> KeyCollection {
        KeyCollection::Map(
            self.iter()
                .map(|(name, key)| (name.clone(), Key::KeyDetail(key.to_key_detail(Some(name)))))
                .collect(),
        )
    }

    fn to_key_value_collection(&self) -> KeyCollection {
        KeyCollection::Map(
            self.iter()
                .map(|(name, key)| (name.clone(), Key::KeyValue(key.to_key_value())))
                .collect(),
        )
    }

    fn to_value_collection(&self) -> KeyCollection {
        KeyCollection::Map(
            self.iter()
                .map(|(name, key)| (name.clone(), Key::Value(key.to_value())))
                .collect(),
        )
    }
}

impl KeyCollectionTransform for KeyCollectionList {
    fn to_key_detail_collection(&self) -> KeyCollection {
        KeyCollection::List(
            self.iter()
                .map(|key| Key::KeyDetail(key.to_key_detail(None)))
                .collect(),
        )
    }

    fn to_key_value_collection(&self) -> KeyCollection {
        KeyCollection::List(
            self.iter()
                .map(|key| Key::KeyValue(key.to_key_value()))
                .collect(),
        )
    }

    fn to_value_collection(&self) -> KeyCollection {
        KeyCollection::List(
            self.iter()
                .map(|key| Key::Value(key.to_value()))
                .collect(),
        )
    }
}

impl KeyCollectionTransform for KeyCollection {
    fn to_key_detail_collection(&self) -> KeyCollection {
        match self {
            KeyCollection::Map(map) => map.to_key_detail_collection(),
            KeyCollection::List(list) => list.to_key_detail_collection(),
        }
    }

    fn to_key_value_collection(&self) -> KeyCollection {
        match self {
            KeyCollection::Map(map) => map.to_key_value_collection(),
            KeyCollection::List(list) => list.to_key_value_collection(),
        }
    }

    fn to_value_collection(&self) -> KeyCollection {
        match self {
            KeyCollection::Map(map) => map.to_value_collection(),
            KeyCollection::List(list) => list.to_value_collection(),
        }
    }
}
-e 
# json.rs
use async_trait::async_trait;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::{Key, KeyDetail, KeyTransform};
use crate::file::key_collection::KeyCollection;
use serde_json;

pub struct JsonAdapter;

#[async_trait]
impl FormatAdapter for JsonAdapter {
    fn extension(&self) -> &str {
        "json"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        // Load keys from the main JSON file
        let contents = std::fs::read_to_string(path).map_err(FluxError::from)?;
        let keys: KeyCollection = serde_json::from_str(&contents).map_err(FluxError::from)?;
        Ok(keys)
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        // Save the main JSON file
        let contents = serde_json::to_string_pretty(keys).map_err(FluxError::from)?;
        let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(path)?;
        file.write_all(contents.as_bytes())?;

        // Save metadata to a separate file
        // let meta_path = PathBuf::from(path).with_extension("meta.json");
        // if let KeyCollection::Map(ref map) = keys {
        //     let meta_map: HashMap<String, KeyDetail> = map
        //         .iter()
        //         .filter_map(|(key, k)| match k {
        //             Key::KeyDetail(detail) => Some((key.clone(), detail.clone())),
        //             _ => None,
        //         })
        //         .collect();
        //     let meta_contents = serde_json::to_string_pretty(&meta_map).map_err(FluxError::from)?;
        //     let mut meta_file = OpenOptions::new().write(true).create(true).truncate(true).open(meta_path)?;
        //     meta_file.write_all(meta_contents.as_bytes())?;
        // }

        Ok(())
    }
}
-e 
# mod.rs
pub mod env;
pub mod format_adapter;
pub mod json;
pub mod toml;
pub mod yaml;
pub mod postman;
pub mod key;
pub mod key_collection;


// use crate::file::format_adapter::FormatAdapter;


use crate::file::json::JsonAdapter;
use crate::file::toml::TomlAdapter;
use crate::file::yaml::YamlAdapter;
use crate::file::postman::PostmanAdapter;
use crate::file::env::EnvAdapter;


/// Sort trait for KeyCollection
pub trait Sort {
    fn sort(&mut self);
}
-e 
# toml.rs
use async_trait::async_trait;
use std::collections::HashMap;
use std::path::PathBuf;
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::Key;
use toml;
use crate::file::key_collection::KeyCollection;

pub struct TomlAdapter;

#[async_trait]
impl FormatAdapter for TomlAdapter {
    fn extension(&self) -> &str {
        "toml"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let contents = std::fs::read_to_string(path)?;
        toml::from_str(&contents).map_err(FluxError::from)
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        let contents = toml::to_string_pretty(keys).map_err(FluxError::from)?;
        std::fs::write(path, contents.as_bytes())?;
        Ok(())
    }
}
-e 
# format_adapter.rs
use async_trait::async_trait;
use std::collections::HashMap;
use std::fs;
use std::fs::{OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use crate::error::FluxError;
use crate::file::key::Key;

extern crate toml;

use crate::file::*;
use crate::file::key_collection::KeyCollection;

/// Trait for format adapters to handle different file formats.
#[async_trait]
pub trait FormatAdapter {
    fn extension(&self) -> &str;
    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError>;
    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError>;
}

/// Manages different format adapters for loading and saving key collections.
pub struct FormatManager {
    adapters: HashMap<String, Box<dyn FormatAdapter + Send + Sync>>,
}

impl FormatManager {
    /// Creates a new `FormatManager` with registered adapters.
    pub fn new() -> Self {
        let mut adapters = HashMap::new();
        adapters.insert("env".to_string(), Box::new(EnvAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("json".to_string(), Box::new(JsonAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("yaml".to_string(), Box::new(YamlAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("yml".to_string(), Box::new(YamlAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("toml".to_string(), Box::new(TomlAdapter) as Box<dyn FormatAdapter + Send + Sync>);
        adapters.insert("postman_environment.json".to_string(), Box::new(PostmanAdapter) as Box<dyn FormatAdapter + Send + Sync>);

        FormatManager { adapters }
    }

    /// Retrieves the appropriate adapter based on file extension.
    pub fn get_adapter(&self, extension: &str) -> Option<&Box<dyn FormatAdapter + Send + Sync>> {
        self.adapters.get(extension)
    }

    /// Loads keys from a file using the appropriate adapter.
    pub fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let extension = Path::new(path).extension().and_then(|ext| ext.to_str()).unwrap_or("");
        let adapter = self.get_adapter(extension).ok_or_else(|| FluxError::UnsupportedFormat(extension.to_string()))?;

        // let mut file = OpenOptions::new().read(true).open(path)?;
        // let mut contents = String::new();
        // file.read_to_string(&mut contents)?;
        adapter.load_keys(path)
    }

    /// Saves keys to a file using the appropriate adapter.
    pub fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        // Debugging the current directory
        let current_dir = std::env::current_dir()?;
        println!("Current directory: {:?}", current_dir);

        let extension = Path::new(path).extension().and_then(|ext| ext.to_str()).unwrap_or("");
        let adapter = self.get_adapter(extension).ok_or_else(|| FluxError::UnsupportedFormat(extension.to_string()))?;

        // Ensure the directory exists
        if let Some(parent) = Path::new(path).parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }

        // Save the keys using the adapter
        adapter.save_keys(path, keys)?;

        Ok(())
    }
}
-e 
# yaml.rs
use async_trait::async_trait;
use std::collections::HashMap;
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::Key;
use serde_yaml;
use crate::file::key_collection::KeyCollection;

pub struct YamlAdapter;

#[async_trait]
impl FormatAdapter for YamlAdapter {
    fn extension(&self) -> &str {
        "yaml"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let contents = std::fs::read_to_string(path)?;
        serde_yaml::from_str(&contents).map_err(FluxError::from)
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        let contents = serde_yaml::to_string(keys).map_err(FluxError::from)?;
        std::fs::write(path, contents.as_bytes())?;
        Ok(())
    }
}
-e 
# postman.rs
use async_trait::async_trait;
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use serde_json;
use uuid::Uuid;
use chrono::Utc;
use crate::error::FluxError;
use crate::file::format_adapter::FormatAdapter;
use crate::file::key::{Key, KeyDetail, KeyTransform};
use crate::file::key_collection::{KeyCollection, KeyCollectionMap, KeyCollectionTransform};

pub struct PostmanAdapter;

#[derive(Serialize, Deserialize, Debug)]
struct PostmanEnvironment {
    id: String,
    name: String,
    values: Vec<PostmanVariable>,
    _postman_variable_scope: String,
    _postman_exported_at: String,
    _postman_exported_using: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct PostmanVariable {
    key: String,
    value: String,
    #[serde(rename = "type")]
    type_field: String,
    enabled: bool,
    description: Option<String>,
    metadata: Option<HashMap<String, String>>,
    last_updated: Option<String>,
    created_at: Option<String>,
    tags: Option<Vec<String>>,
}

#[async_trait]
impl FormatAdapter for PostmanAdapter {
    fn extension(&self) -> &str {
        "postman_environment.json"
    }

    fn load_keys(&self, path: &str) -> Result<KeyCollection, FluxError> {
        let contents = std::fs::read_to_string(path)?;
        let postman_env: PostmanEnvironment = serde_json::from_str(&contents).map_err(FluxError::from)?;
        let mut map = BTreeMap::new();
        for variable in postman_env.values {
            map.insert(variable.key.clone(), Key::KeyDetail(KeyDetail {
                name: variable.key,
                value: variable.value,
                description: variable.description,
                enabled: variable.enabled,
                metadata: variable.metadata,
                last_updated: variable.last_updated,
                created_at: variable.created_at,
                tags: variable.tags,
            }));
        }
        Ok(KeyCollection::Map(map))
    }

    fn save_keys(&self, path: &str, keys: &KeyCollection) -> Result<(), FluxError> {
        // let map: KeyCollection = match keys {
        //     KeyCollection::Map(map) => map.to_key_detail_collection(),
        //     KeyCollection::List(list) => {
        //         list.iter()
        //             .filter_map(|key| match key {
        //                 Key::KeyDetail(detail) => Some((detail.name.clone(), detail.clone())),
        //                 _ => None,
        //             })
        //             .collect()
        //     }
        // };

        let postman_env = PostmanEnvironment {
            id: Uuid::new_v4().to_string(),
            name: "Generated Environment".to_string(),
            values: keys.to_key_detail_collection().iter().map(|(name, key)| {
                let detail = key.to_key_detail(Some(&name));
                PostmanVariable {
                    key: detail.name,
                    value: detail.value,
                    type_field: "default".to_string(),
                    enabled: detail.enabled,
                    description: detail.description,
                    metadata: detail.metadata,
                    last_updated: detail.last_updated,
                    created_at: detail.created_at,
                    tags: detail.tags,
                }
            }).collect(),
            _postman_variable_scope: "environment".to_string(),
            _postman_exported_at: Utc::now().to_rfc3339(),
            _postman_exported_using: "keyflux".to_string(),
        };

        let result = serde_json::to_string_pretty(&postman_env).map_err(FluxError::from)?;
        std::fs::write(path, result.clone())?;
        Ok(())


    }
}
