use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MachineIdentity {
    pub id: String,
    pub name: String,
}

impl MachineIdentity {
    pub fn load_or_create(config_dir: &Path) -> Result<Self> {
        let path = config_dir.join("machine.toml");
        if path.exists() {
            let content =
                std::fs::read_to_string(&path).context("reading machine.toml")?;
            let identity: MachineIdentity =
                toml::from_str(&content).context("parsing machine.toml")?;
            return Ok(identity);
        }
        let name = hostname::get()
            .map(|h| h.to_string_lossy().to_string())
            .unwrap_or_else(|_| "unknown".to_string());
        let identity = MachineIdentity {
            id: Uuid::new_v4().to_string(),
            name,
        };
        std::fs::create_dir_all(config_dir)
            .context("creating config directory")?;
        std::fs::write(&path, toml::to_string_pretty(&identity)?)
            .context("writing machine.toml")?;
        Ok(identity)
    }

    pub fn config_dir() -> Result<std::path::PathBuf> {
        let home = dirs::home_dir().context("cannot determine home directory")?;
        Ok(home.join(".second-brain"))
    }
}
