//! F7 — System monomers: MC_56–MC_63
//!
//! OS interface operations. All operations return Option or Result — no panics.

use std::env;
use std::time::{SystemTime, UNIX_EPOCH};

/// MC_56 — TIME: Current Unix timestamp in seconds.
///
/// Returns 0 if the system clock is unavailable.
///
/// ```
/// use brik64_core::mc::time_unix;
/// let t = time_unix();
/// assert!(t > 0);
/// ```
pub fn time_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// MC_57 — TIME_MS: Current Unix timestamp in milliseconds.
pub fn time_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// MC_58 — ENV: Read an environment variable.
///
/// Returns `None` if not set or not valid UTF-8.
///
/// ```
/// use brik64_core::mc::env_get;
/// let path = env_get("PATH");
/// ```
pub fn env_get(key: &str) -> Option<String> {
    env::var(key).ok()
}

/// MC_59 — ENV_SET: Set an environment variable (process-local).
pub fn env_set(key: &str, value: &str) {
    env::set_var(key, value);
}

/// MC_60 — PID: Get current process ID.
pub fn pid() -> u32 {
    std::process::id()
}

/// MC_61 — ARGS: Get command-line arguments as a Vec<String>.
pub fn args() -> Vec<String> {
    env::args().collect()
}

/// MC_62 — EXIT_CODE: Validate an exit code is in [0, 255].
///
/// Clamps to valid range — never panics.
pub fn exit_code(code: i64) -> u8 {
    code.clamp(0, 255) as u8
}

/// MC_63 — SLEEP_MS: Sleep for n milliseconds (max 60_000).
///
/// Capped at 60 seconds to preserve bounded termination.
pub fn sleep_ms(ms: u64) {
    std::thread::sleep(std::time::Duration::from_millis(ms.min(60_000)));
}
