// SPDX-License-Identifier: LGPL-2.1-or-later OR GPL-2.0-or-later OR MPL-2.0
// SPDX-FileCopyrightText: 2026 Gabriel Marcano <gabemarcano@yahoo.com>

use gb_cart::MetadataRead;

use std::env;
use std::fs::File;
use std::path::Path;

pub fn main() {
    let args: Vec<String> = env::args().collect();

    println!("[");
    for (i, filename) in args[1..].iter().enumerate() {
        let path = Path::new(filename);
        let mut f = File::open(path).unwrap();

        let Some(filename) = path.file_name() else {
            continue;
        };

        let cart = f.read_gb_cart();
        if let Err(ref err) = cart {
            eprintln!("Error: {err}");
            continue;
        }
        let cart = cart.unwrap();

        let computed_header_checksum = cart.header_checksum(&mut f).unwrap();
        let computed_checksum = cart.checksum(&mut f).unwrap();
        let header = &cart;

        println!("\t{{");

        println!("\t\t\"filename\": \"{}\",", filename.to_string_lossy());
        println!("\t\t\"entry point\": \"0x{:08X}\",", header.entry_point);
        println!("\t\t\"logo\":, \"");
        header.print_logo();
        println!("\",");
        println!("\t\t\"title\": \"{}\",", header.title());
        if let Some(manufacturer_code) = &header.manufacturer_code() {
            println!(
                "\t\t\"manufacturer code\": \"{}\",",
                str::from_utf8(manufacturer_code).unwrap()
            );
        }
        if let Some(cgb_flag) = &header.cgb_flag() {
            println!("\t\t\"CGB flag\": \"0x{cgb_flag:02X}\",");
        }
        if let Some(new_licensee) = &header.new_licensee() {
            println!("\t\t\"licensee\": \"{new_licensee}\",");
        } else {
            println!("\t\t\"licensee\": \"{}\",", header.licensee());
        }
        println!("\t\t\"SGB flag\": {},", header.sgb_flag);
        println!("\t\t\"cart type\": \"{}\",", header.cart_type);
        println!("\t\t\"ROM size\": \"{} KiB\",", header.rom_size);
        println!("\t\t\"RAM size\": \"{} KiB\",", header.save_ram_size);
        println!("\t\t\"region\": \"{}\",", header.region);
        println!("\t\t\"ROM version\": {},", header.rom_version);
        println!(
            "\t\t\"header checksum\": \"0x{:02X}\",",
            header.header_checksum
        );
        println!("\t\t\"checksum\": \"0x{:04X}\",", header.checksum);
        println!(
            "\t\t\"header checksum pass\": {},",
            computed_header_checksum == header.header_checksum
        );
        println!(
            "\t\t\"checksum pass\": {}",
            computed_checksum == header.checksum
        );
        if i == (args[1..].len() - 1) {
            println!("\t}}");
        } else {
            println!("\t}},");
        }
    }
    println!("]");
}
