use game_audio::track::song_from_midi;
use std::{path::PathBuf, process::ExitCode};

fn main() -> ExitCode {
    let mut args = std::env::args().skip(1);
    let Some(input) = args.next().map(PathBuf::from) else {
        eprintln!("Usage: midi-import <input.mid> [output.track]");
        return ExitCode::FAILURE;
    };
    let output = args
        .next()
        .map_or_else(|| input.with_extension("track"), PathBuf::from);

    let data = match std::fs::read(&input) {
        Ok(data) => data,
        Err(error) => {
            eprintln!("Reading {}: {error}", input.display());
            return ExitCode::FAILURE;
        }
    };
    let import = match song_from_midi(&data) {
        Ok(import) => import,
        Err(error) => {
            eprintln!("Importing {}: {error}", input.display());
            return ExitCode::FAILURE;
        }
    };
    for warning in &import.warnings {
        eprintln!("Warning: {warning}");
    }

    match std::fs::write(&output, import.song.to_string()) {
        Ok(()) => {
            eprintln!(
                "Imported {} → {} ({} layers)",
                input.display(),
                output.display(),
                import.song.layers.len()
            );
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("Writing {}: {error}", output.display());
            ExitCode::FAILURE
        }
    }
}
