use chrono::Utc;
use serde_json;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use crate::logging::ledger::seal_unsealed_logs;
use crate::logging::schema::AuditLogEntry;
fn ensure_logs_dir() -> PathBuf {
let dir = PathBuf::from("logs");
if !dir.exists() {
fs::create_dir_all(&dir).expect("cannot create logs directory");
}
dir
}
fn today_log_path() -> PathBuf {
let logs_dir = ensure_logs_dir();
let today = Utc::now().format("%Y-%m-%d").to_string();
let log_filename = format!("audit-{}.jsonl", today);
logs_dir.join(log_filename)
}
pub fn log_event(entry: &AuditLogEntry) {
let log_path = today_log_path();
let json = serde_json::to_string(entry).expect("failed to serialize log entry");
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)
.expect("cannot open daily audit log file");
writeln!(file, "{}", json).expect("failed to write log entry");
let today = Utc::now().format("%Y-%m-%d").to_string();
seal_unsealed_logs(&PathBuf::from("logs"), &today);
}
#[allow(dead_code)]
pub fn log_and_print(entry: &AuditLogEntry, console_msg: &str) {
log_event(entry);
println!("{}", console_msg);
}