use super::SignalKind;
use crate::substrate::SubstrateResult;

#[derive(Debug, Clone)]
pub struct RawSignal {
    pub program: String,
    pub args: Vec<String>,
    pub kind: SignalKind,
    pub stdout: String,
    pub stderr: String,
    pub exit_code: i32,
    pub duration_ms: u64,
}

impl RawSignal {
    pub fn from_result(
        program: impl Into<String>,
        args: Vec<String>,
        result: SubstrateResult,
    ) -> Self {
        let program = program.into();
        let kind = SignalKind::from_program(&program, &args);
        let stdout = String::from_utf8_lossy(&result.stdout).into_owned();
        let stderr = String::from_utf8_lossy(&result.stderr).into_owned();
        Self {
            program,
            args,
            kind,
            stdout,
            stderr,
            exit_code: result.exit_code,
            duration_ms: result.duration_ms,
        }
    }

    pub fn combined_output(&self) -> String {
        let mut out = self.stdout.clone();
        if !self.stderr.is_empty() {
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(&self.stderr);
        }
        out
    }

    pub fn succeeded(&self) -> bool {
        self.exit_code == 0
    }
}
