//! Rhai wrappers for Build Machine provisioning

use crate::kubernetes::BuildMachine;
use rhai::EvalAltResult;
use super::runtime::{get_runtime, to_rhai_err};

/// Rhai wrapper for BuildMachine
#[derive(Clone)]
pub struct BuildMachineRhai {
    machine: BuildMachine,
}

impl BuildMachineRhai {
    /// Create a new BuildMachineRhai wrapper
    pub fn new(machine: BuildMachine) -> Self {
        Self { machine }
    }

    /// Set image
    pub fn image(mut self, image: &str) -> Self {
        self.machine = self.machine.image(image);
        self
    }

    /// Set privileged mode
    pub fn privileged(mut self, privileged: bool) -> Self {
        self.machine = self.machine.privileged(privileged);
        self
    }

    /// Set memory request and limit (in MB)
    pub fn memory(mut self, requested: i64, _limit: i64) -> Self {
        self.machine = self.machine.memory(format!("{}Mi", requested));
        // Note: limit is stored as second parameter but BuildMachine only uses one memory value
        // For now we use the requested value; limit could be handled differently
        self
    }

    /// Set CPU request and limit (in millicores)
    pub fn cpu(mut self, requested: i64, _limit: i64) -> Self {
        self.machine = self.machine.cpu(format!("{}m", requested));
        // Note: limit is stored as second parameter but BuildMachine only uses one CPU value
        // For now we use the requested value; limit could be handled differently
        self
    }

    /// Provision the build machine
    pub fn provision(&self) -> Result<BuildMachineHandleRhai, Box<EvalAltResult>> {
        let machine = self.machine.clone();
        let rt = get_runtime();
        rt.block_on(async {
            machine
                .provision()
                .await
                .map_err(|e| format!("Provision error: {}", e))
        })
        .map(|handle| BuildMachineHandleRhai::new(handle))
        .map_err(|e| to_rhai_err(e))
    }
}

/// Rhai wrapper for BuildMachineHandle (result of provision)
#[derive(Clone)]
pub struct BuildMachineHandleRhai {
    handle: crate::kubernetes::BuildMachineHandle,
}

impl BuildMachineHandleRhai {
    /// Create a new BuildMachineHandleRhai wrapper
    pub fn new(handle: crate::kubernetes::BuildMachineHandle) -> Self {
        Self { handle }
    }

    /// Get namespace
    pub fn namespace(&self) -> String {
        self.handle.namespace().to_string()
    }

    /// Get pod name
    pub fn pod_name(&self) -> String {
        self.handle.pod_name().to_string()
    }

    /// Destroy the build machine
    pub fn destroy(&self) -> Result<(), Box<EvalAltResult>> {
        let handle = self.handle.clone();
        let rt = get_runtime();
        rt.block_on(async { handle.destroy().await.map_err(|e| format!("Destroy error: {}", e)) })
            .map_err(|e| to_rhai_err(e))
    }
}
