// Copyright (c) 2025 shibedrill
// SPDX-License-Identifier: MIT

use crate::boot::modules::FILE_REQUEST;
use crate::memory::alloc;
use alloc::string::String;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use limine::request::ExecutableFileResponse;

lazy_static! {
    pub static ref EXECUTABLE_FILE_RESPONSE: &'static ExecutableFileResponse = FILE_REQUEST
        .response()
        .expect("Bootloader did not return executable data");
    pub static ref PARAMS: KernelParameters = get_kernel_params(
        EXECUTABLE_FILE_RESPONSE
            .executable_file()
            .cmdline()
            .as_bytes()
    );
}

pub type KernelParameters = alloc::collections::BTreeMap<String, String>;

// This parsing is godawful.
pub fn get_kernel_params(cmdline: &[u8]) -> KernelParameters {
    let cmd_str = String::from_utf8_lossy(cmdline).into_owned();
    let args: Vec<&str> = cmd_str.split_ascii_whitespace().collect();
    let mut local_params: alloc::collections::BTreeMap<String, String> =
        alloc::collections::BTreeMap::new();
    for arg in args {
        let split: Vec<&str> = arg.split('=').collect();
        if let Some(first) = split.first() {
            if split.len() > 1 {
                local_params.insert(String::from(*first), split[1..].join("="));
            } else {
                local_params.insert(String::from(*first), String::new());
            }
        }
    }
    local_params
}
