use std::path::{Path, PathBuf};

use uuid::Uuid;

const PEER_ID_FILE: &str = "peer_id";

pub const FEATURE_LIBRARY_DELTA: &str = "library-delta-v1";
pub const FEATURE_LIBRARY_SNAPSHOT: &str = "library-snapshot-v1";

pub fn load_or_create_peer_id(state_dir: Option<&Path>) -> eyre::Result<String> {
    let path = peer_id_path(state_dir);
    if let Ok(existing) = std::fs::read_to_string(&path) {
        let trimmed = existing.trim();
        if !trimmed.is_empty() {
            return Ok(trimmed.to_string());
        }
    }

    let peer_id = Uuid::now_v7().simple().to_string();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&path, peer_id.as_bytes())?;
    Ok(peer_id)
}

pub fn default_features() -> Vec<String> {
    vec![
        FEATURE_LIBRARY_DELTA.to_string(),
        FEATURE_LIBRARY_SNAPSHOT.to_string(),
    ]
}

fn peer_id_path(state_dir: Option<&Path>) -> PathBuf {
    if let Some(dir) = state_dir {
        return dir.join(PEER_ID_FILE);
    }

    if let Some(dir) = std::env::var_os("LANSPREAD_STATE_DIR") {
        return PathBuf::from(dir).join(PEER_ID_FILE);
    }

    if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
        return PathBuf::from(home).join(".lanspread").join(PEER_ID_FILE);
    }

    std::env::temp_dir().join("lanspread").join(PEER_ID_FILE)
}
