limavel 1.0.0

A tool for creating virtualized development environments for Laravel in macOS
use anyhow::{Context, Result};
use dialoguer::Select;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::error::LimavelError;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LimavelConfig {
    pub name: String,
    pub memory: u32,
    pub cpus: u32,
    #[serde(default = "default_disk")]
    pub disk: u32,
    pub image: String,
    pub arch: String,
    pub authorize: String,
    pub keys: Vec<String>,
    pub folders: Vec<FolderMap>,
    pub sites: Vec<SiteMap>,
    pub databases: Vec<String>,
    pub database: DatabaseConfig,
    pub features: Features,
    pub ports: Vec<PortMap>,
    #[serde(default = "default_nodejs")]
    pub nodejs: String,
    #[serde(default)]
    pub bootstrap: Option<String>,
    #[serde(default)]
    pub playbooks: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FolderMap {
    pub map: String,
    pub to: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SiteMap {
    pub map: String,
    pub to: String,
    pub php: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DatabaseConfig {
    #[serde(rename = "type")]
    pub db_type: String,
    pub version: String,
    pub password: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Features {
    #[serde(default)]
    pub ohmyzsh: bool,
    #[serde(default)]
    pub webdriver: bool,
    #[serde(default)]
    pub mailpit: bool,
    #[serde(default)]
    pub mongodb: bool,
    #[serde(default)]
    pub valkey: bool,
    #[serde(default)]
    pub meilisearch: bool,
    #[serde(flatten, default)]
    pub extra: HashMap<String, serde_yml::Value>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PortMap {
    pub send: u16,
    pub to: u16,
}

fn default_disk() -> u32 {
    50
}

/// Heuristic: a YAML file is considered a limavel config attempt if it has
/// any of the limavel-specific top-level keys.
fn looks_like_limavel_config(content: &str) -> bool {
    let Ok(value) = serde_yml::from_str::<serde_yml::Value>(content) else {
        return false;
    };
    let Some(map) = value.as_mapping() else {
        return false;
    };
    ["sites", "folders", "authorize"]
        .iter()
        .any(|key| map.contains_key(serde_yml::Value::String(key.to_string())))
}

fn default_nodejs() -> String {
    "24".to_string()
}

impl LimavelConfig {
    /// Returns the config file path for a given instance name: `{name}.yaml`
    pub fn config_path(name: &str) -> PathBuf {
        if name.ends_with(".yaml") || name.ends_with(".yml") {
            return PathBuf::from(name);
        }
        PathBuf::from(format!("{}.yaml", name))
    }

    /// Scan the current directory for valid limavel config files.
    /// Returns filenames (without extension) of files that parse as LimavelConfig.
    pub fn discover() -> Vec<String> {
        let Ok(entries) = fs::read_dir(".") else {
            return Vec::new();
        };

        let mut configs: Vec<String> = entries
            .filter_map(|e| e.ok())
            .filter_map(|entry| {
                let path = entry.path();
                let ext = path.extension()?.to_str()?;
                if ext != "yaml" && ext != "yml" {
                    return None;
                }
                let content = fs::read_to_string(&path).ok()?;
                if let Err(e) = serde_yml::from_str::<LimavelConfig>(&content) {
                    // Only warn about files that look like limavel configs;
                    // unrelated YAML files (docker-compose.yml, etc.) are
                    // skipped silently.
                    if looks_like_limavel_config(&content) {
                        eprintln!(
                            "{} Skipping {}: {}",
                            console::style("âš ").yellow(),
                            path.display(),
                            e
                        );
                    }
                    return None;
                }
                Some(path.file_stem()?.to_str()?.to_string())
            })
            .collect();

        configs.sort();
        configs
    }

    /// Resolve the config name: use the explicit name if given, otherwise auto-detect.
    pub fn resolve(name: Option<String>) -> Result<String> {
        if let Some(n) = name {
            return Ok(n);
        }

        let configs = Self::discover();

        match configs.len() {
            0 => Err(LimavelError::NoConfigFound.into()),
            1 => Ok(configs.into_iter().next().unwrap()),
            _ => {
                let selection = Select::new()
                    .with_prompt("Multiple config files found. Select one")
                    .items(&configs)
                    .default(0)
                    .interact()?;
                Ok(configs[selection].clone())
            }
        }
    }

    pub fn exists(name: &str) -> bool {
        Self::config_path(name).exists()
    }

    pub fn load(name: &str) -> Result<Self> {
        let path = Self::config_path(name);
        if !path.exists() {
            return Err(LimavelError::ConfigNotFound(path.display().to_string()).into());
        }
        let content = fs::read_to_string(&path)
            .with_context(|| format!("Failed to read {}", path.display()))?;
        let config: LimavelConfig =
            serde_yml::from_str(&content).with_context(|| format!("Failed to parse {}", path.display()))?;
        Ok(config)
    }

    pub fn resolve_path(path: &str) -> String {
        shellexpand::tilde(path).to_string()
    }

    pub fn read_ssh_pubkey(&self) -> Result<String> {
        let path = Self::resolve_path(&self.authorize);
        let p = Path::new(&path);
        if !p.exists() {
            return Err(LimavelError::SshKeyNotFound(self.authorize.clone()).into());
        }
        let content = fs::read_to_string(p)
            .with_context(|| format!("Failed to read SSH key: {}", path))?;
        Ok(content.trim().to_string())
    }

    pub fn validate_folders(&self) -> Result<()> {
        let missing: Vec<String> = self
            .folders
            .iter()
            .filter_map(|f| {
                let expanded = shellexpand::tilde(&f.map).to_string();
                let path = Path::new(&expanded);
                if !path.exists() {
                    Some(format!("  - {} ({})", f.map, expanded))
                } else {
                    None
                }
            })
            .collect();

        if !missing.is_empty() {
            return Err(LimavelError::FoldersNotFound(missing.join("\n")).into());
        }

        Ok(())
    }

    /// Returns the Lima VM instance name from the `name` field.
    pub fn instance_name(&self) -> &str {
        &self.name
    }

    pub fn php_versions(&self) -> Vec<String> {
        let mut versions: Vec<String> = self.sites.iter().map(|s| s.php.clone()).collect();
        versions.sort();
        versions.dedup();
        versions
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fixture() -> LimavelConfig {
        let yaml = include_str!("../../templates/default.yaml").replace("{{ name }}", "testbox");
        serde_yml::from_str(&yaml).unwrap()
    }

    #[test]
    fn default_template_parses() {
        let config = fixture();
        assert_eq!(config.name, "testbox");
        assert_eq!(config.memory, 2048);
        assert_eq!(config.cpus, 2);
        assert_eq!(config.disk, 50);
        assert_eq!(config.arch, "aarch64");
        assert_eq!(config.database.db_type, "mariadb");
        assert_eq!(config.databases, vec!["limavel"]);
        assert_eq!(config.sites.len(), 1);
        assert_eq!(config.sites[0].php, "8.3");
        assert!(config.features.ohmyzsh);
        assert!(!config.features.webdriver);
        assert_eq!(config.ports.len(), 2);
        assert_eq!(config.ports[0].send, 33060);
        assert_eq!(config.ports[0].to, 3306);
    }

    #[test]
    fn missing_optional_fields_use_defaults() {
        let yaml = r#"
name: mini
memory: 1024
cpus: 1
image: img
arch: aarch64
authorize: ~/.ssh/id_rsa.pub
keys: []
folders: []
sites: []
databases: []
database:
  type: mariadb
  version: "11"
  password: secret
features: {}
ports: []
"#;
        let config: LimavelConfig = serde_yml::from_str(yaml).unwrap();
        assert_eq!(config.disk, 50);
        assert_eq!(config.nodejs, "24");
        assert!(config.bootstrap.is_none());
        assert!(config.playbooks.is_none());
        assert!(config.features.extra.is_empty());
    }

    #[test]
    fn custom_feature_flags_land_in_extra() {
        let mut config = fixture();
        let yaml = r#"
ohmyzsh: true
worker_count: 4
"#;
        config.features = serde_yml::from_str(yaml).unwrap();
        assert!(config.features.ohmyzsh);
        assert_eq!(
            config.features.extra.get("worker_count").and_then(|v| v.as_u64()),
            Some(4)
        );
    }

    #[test]
    fn config_path_appends_yaml_extension() {
        assert_eq!(LimavelConfig::config_path("dev"), PathBuf::from("dev.yaml"));
        assert_eq!(LimavelConfig::config_path("dev.yaml"), PathBuf::from("dev.yaml"));
        assert_eq!(LimavelConfig::config_path("dev.yml"), PathBuf::from("dev.yml"));
    }

    #[test]
    fn php_versions_are_sorted_and_deduped() {
        let mut config = fixture();
        let site = config.sites[0].clone();
        config.sites.push(SiteMap { php: "8.2".into(), ..site.clone() });
        config.sites.push(SiteMap { php: "8.3".into(), ..site });
        assert_eq!(config.php_versions(), vec!["8.2", "8.3"]);
    }

    #[test]
    fn limavel_like_yaml_is_recognized() {
        assert!(looks_like_limavel_config("name: dev\nsites: []\n"));
        assert!(looks_like_limavel_config("folders:\n  - map: ~/x\n    to: /y\n"));
        assert!(looks_like_limavel_config("authorize: ~/.ssh/id_rsa.pub\n"));
    }

    #[test]
    fn unrelated_yaml_is_not_recognized() {
        assert!(!looks_like_limavel_config("services:\n  app:\n    image: nginx\n"));
        assert!(!looks_like_limavel_config("- just\n- a\n- list\n"));
        assert!(!looks_like_limavel_config("not: [valid"));
    }
}