//
// Syd: rock-solid application kernel
// src/utils/syd-utc.rs: Print UTC date and time in JSON format
//
// Copyright (c) 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::{
    io::{stdout, Write},
    process::ExitCode,
};

use serde_json::json;
use syd::log::{now, Tm};

// Set global allocator to GrapheneOS allocator.
#[cfg(all(
    not(coverage),
    not(feature = "prof"),
    not(target_os = "android"),
    not(target_arch = "riscv64"),
    target_page_size_4k,
    target_pointer_width = "64"
))]
#[global_allocator]
static GLOBAL: hardened_malloc::HardenedMalloc = hardened_malloc::HardenedMalloc;

// Set global allocator to tcmalloc if profiling is enabled.
#[cfg(feature = "prof")]
#[global_allocator]
static GLOBAL: tcmalloc::TCMalloc = tcmalloc::TCMalloc;

syd::main! {
    syd::set_sigpipe_dfl()?;

    if std::env::args().len() != 1 {
        help();
        return Ok(ExitCode::FAILURE);
    }

    let ts: i64 = now().try_into()?;
    let tm: Tm = ts.try_into()?;
    #[expect(clippy::disallowed_methods)]
    let dt = json!({
        "year": tm.year(),
        "month": tm.month(),
        "day": tm.day(),
        "hour": tm.hour(),
        "minute": tm.minute(),
        "second": tm.second(),
        "dt": tm.to_string(),
        "ts": ts,
        "tz": "UTC",
    });

    #[expect(clippy::disallowed_methods)]
    let mut dt = serde_json::to_string(&dt).expect("JSON");
    dt.push('\n');
    stdout().write_all(dt.as_bytes())?;

    Ok(ExitCode::SUCCESS)
}

fn help() {
    println!("Usage: syd-utc");
    println!("Print UTC date and time in JSON format.");
}
