// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later

use std::fmt::Write as _;
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

fn generate_asset_manifest() {
    let manifest_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("manifest dir"));
    let generated_dir = manifest_dir.join("assets/web/generated");
    println!("cargo:rerun-if-changed={}", generated_dir.display());

    let mut filenames = fs::read_dir(&generated_dir)
        .expect("read generated frontend assets")
        .map(|entry| entry.expect("read generated asset entry"))
        .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file()))
        .map(|entry| {
            entry
                .file_name()
                .into_string()
                .expect("UTF-8 asset filename")
        })
        .collect::<Vec<_>>();
    filenames.sort();

    let mut output = String::from(
        "// Generated by build.rs from committed frontend output.\n\
         pub const GENERATED_ASSETS: &[(&str, &[u8])] = &[\n",
    );
    for filename in filenames {
        assert!(
            filename
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)),
            "unsupported generated asset filename: {filename}"
        );
        writeln!(
            output,
            "    ({filename:?}, include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/assets/web/generated/\", {filename:?}))),"
        )
        .expect("write asset manifest");
    }
    output.push_str("];\n");

    let output_path =
        PathBuf::from(std::env::var_os("OUT_DIR").expect("out dir")).join("generated_assets.rs");
    fs::write(output_path, output).expect("write generated asset manifest");
}

fn utc_ymd_from_unix_secs(secs: i64) -> (i32, u32, u32) {
    let days = secs.div_euclid(86_400);
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let mut y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = mp + if mp < 10 { 3 } else { -9 };
    y += if m <= 2 { 1 } else { 0 };
    (y as i32, m as u32, d as u32)
}

fn main() {
    generate_asset_manifest();
    let secs = match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(d) => d.as_secs() as i64,
        Err(_) => 0,
    };
    let (y, m, d) = utc_ymd_from_unix_secs(secs);
    println!("cargo:rustc-env=TRX_CLIENT_BUILD_DATE={y:04}-{m:02}-{d:02}");
}
