use crate::colors::get_colors;
use crate::config::get_config;
use crate::load_data::load_data_json;
use crate::options::Options;
use crate::utils::{package_exists, prepare_packages, read_and_print};

/// Prints detailed metadata for each requested package from the repository index.
///
/// If `--read-file` is given, reads and prints the specified file from the
/// package directory (e.g. `README` or `pkg.SlackBuild`) and returns immediately.
///
/// Otherwise, prints the full metadata for each package.
/// Duplicate package names are silently removed before processing.
///
/// # Exits
///
/// Exits with code 1 if a requested package is not found in the repository,
/// or if the file specified by `--read-file` does not exist.
pub fn info(packages: &[String], options: &Options) {
    let packages = package_exists(packages);
    let packages = prepare_packages(&packages);

    let cfg = get_config();
    let color = get_colors(cfg.colors);
    let repo = load_data_json();

    if let Some(file) = &options.read_file {
        for pkg in &packages {
            if let Some(pkg_data) = repo.get(pkg) {
                let filename = format!("{}/{}/{}/{}", cfg.repo_path, pkg_data.category, pkg, file);
                read_and_print(&filename, None);
            }
        }
        return;
    }

    println!("{}Package(s) information:{}\n", color.bold, color.reset);
    for pkg in &packages {
        if let Some(pkg_data) = repo.get(pkg) {
            println!("Name:            {}", pkg_data.prgnam);
            println!("Version:         {}", pkg_data.version);
            println!("Build:           {}", pkg_data.build);
            println!("Category:        {}", pkg_data.category);
            println!("Arch:            {}", pkg_data.arch);
            println!("Homepage:        {}", pkg_data.homepage);
            println!("Download:        {}", pkg_data.download);
            println!("md5sum:          {}", pkg_data.md5sum);
            println!("Download x86_64: {}", pkg_data.download_x86_64);
            println!("md5sum x86_64:   {}", pkg_data.md5sum_x86_64);
            println!("Requires:        {}", pkg_data.requires);
            println!("Maintainer:      {}", pkg_data.maintainer);
            println!("Email:           {}", pkg_data.email);
        }
        if packages.len() > 1 {
            println!();
        }
    }
}
