use crate::colors::get_colors;
use crate::config::get_config;
use crate::parse::PackageData;
use std::collections::HashMap;
use std::fs;
use std::process::exit;

/// Reads and deserialises `data.json` into a nested `HashMap`.
///
/// The JSON structure is `category -> package -> PackageData`.
///
/// # Exits
///
/// Exits with code 1 if the file is missing or cannot be deserialised.
fn parse_json() -> HashMap<String, HashMap<String, PackageData>> {
    let cfg = get_config();
    let color = get_colors(cfg.colors);
    let path = format!("{}/{}", cfg.repo_path, cfg.data_json);

    let Ok(content) = fs::read_to_string(&path) else {
        eprintln!(
            "{}Error:{} {} not found at {}",
            color.red, color.reset, cfg.data_json, path
        );
        eprintln!("Run 'sbpkg update' first to sync the repository");
        exit(1);
    };

    let all: HashMap<String, HashMap<String, PackageData>> = serde_json::from_str(&content)
        .unwrap_or_else(|e| {
            eprintln!(
                "{}Error:{} Failed to parse {}: {}",
                color.red, color.reset, cfg.data_json, e
            );
            exit(1);
        });
    all
}

/// Loads `data.json` and flattens it into a single `HashMap` keyed by package name.
///
/// Discards the category level for direct package lookups.
///
/// # Exits
///
/// Exits with code 1 if the file is missing or cannot be deserialised.
pub fn load_data_json() -> HashMap<String, PackageData> {
    let all = parse_json();

    let mut flat = HashMap::new();
    for (_, pkgs) in all {
        for (prgnam, data) in pkgs {
            flat.insert(prgnam, data);
        }
    }
    flat
}

/// Loads `data.json` and returns the full nested structure (`category -> package -> PackageData`).
///
/// Use this when the category grouping is needed (e.g. `--category` lookups).
///
/// # Exits
///
/// Exits with code 1 if the file is missing or cannot be deserialised.
pub fn load_data_json_nested() -> HashMap<String, HashMap<String, PackageData>> {
    parse_json()
}
