//! Library surface for `provisioning-tool` — shared between the binary and integration tests.

use anyhow::Result;
use provisioning_core::{
    Environment, Registry,
    sources::{NclCache, OrchestratorClient},
};
use provisioning_core::providers::hcloud::HcloudClient;
use std::{path::PathBuf, sync::Arc};

// ── Environment builder ───────────────────────────────────────────────────────

/// Build an `Environment` from environment variables with sensible defaults.
pub fn build_env() -> Environment {
    let orchestrator_url = std::env::var("ORCHESTRATOR_URL")
        .unwrap_or_else(|_| "http://localhost:9011".into());

    let workspaces_root = std::env::var("PROVISIONING_WORKSPACES_ROOT")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("workspaces"));

    let extensions_root = std::env::var("PROVISIONING_EXTENSIONS_ROOT")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("provisioning/extensions"));

    let ontology_root = std::env::var("PROVISIONING_ONTOLOGY_ROOT")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from(".ontology"));

    let ncl_cache_dir = std::env::var("PROVISIONING_NCL_CACHE_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            dirs::cache_dir()
                .unwrap_or_else(|| PathBuf::from("/tmp"))
                .join("provisioning")
                .join("ncl")
        });

    Environment {
        orchestrator_url,
        workspaces_root,
        extensions_root,
        ontology_root,
        ncl_cache_dir,
    }
}

/// Build the tool `Registry` from shared dependencies (no vault).
///
/// Vault tools are omitted — the binary does not manage vault lifecycle.
/// A surface that needs vault should construct the registry directly.
pub fn build_registry() -> Result<Registry> {
    let cache = Arc::new(NclCache::new());
    let orch = Arc::new(OrchestratorClient::new(
        std::env::var("ORCHESTRATOR_URL")
            .unwrap_or_else(|_| "http://localhost:9011".into()),
    ));
    let hcloud = Arc::new(HcloudClient::new());

    Registry::with_all_tools(cache, orch, hcloud, None)
        .map_err(|e| anyhow::anyhow!("registry init: {e}"))
}

// ── Output helpers ────────────────────────────────────────────────────────────

/// Print `value` to stdout, pretty or compact based on flag.
pub fn print_json(value: &serde_json::Value, compact: bool) {
    if compact {
        println!("{}", value);
    } else {
        println!("{}", serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string()));
    }
}
