use std::path::PathBuf;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeeperConfig {
    /// NATS server URL (e.g., "nats://127.0.0.1:4222")
    pub nats_url: String,

    /// Workspace name (e.g., "libre-wuji") — determines OPS_PENDING/OPS_CMD stream names
    pub workspace: String,

    /// Path to the Ed25519 private key in PKCS#8 PEM format
    pub private_key_path: PathBuf,

    /// Path to the Ed25519 public key in PKCS#8 PEM format
    pub public_key_path: PathBuf,

    /// Signer identity embedded in JWT `iss` claim (e.g., "keeper-vm-primary")
    pub issuer_id: String,

    /// Path to policy.ncl file evaluated by nickel export at startup
    pub policy_path: PathBuf,

    /// JWT validity window in seconds from signing time
    pub token_validity_secs: u64,

    /// Optional NATS authentication token
    pub nats_auth_token: Option<String>,
}

impl Default for KeeperConfig {
    fn default() -> Self {
        Self {
            nats_url: "nats://127.0.0.1:4222".to_string(),
            workspace: String::new(),
            private_key_path: PathBuf::from("keeper.pem"),
            public_key_path: PathBuf::from("keeper.pub.pem"),
            issuer_id: "keeper-vm-primary".to_string(),
            policy_path: PathBuf::from("policy.ncl"),
            token_validity_secs: 3600,
            nats_auth_token: None,
        }
    }
}

impl KeeperConfig {
    pub fn from_toml(path: &std::path::Path) -> Result<Self, crate::error::KeeperError> {
        let s = std::fs::read_to_string(path)?;
        toml::from_str(&s).map_err(|e| crate::error::KeeperError::Policy(format!("config parse: {e}")))
    }
}
