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

fn main() -> ExitCode {
    let files: Vec<PathBuf> = std::env::args().skip(1).map(PathBuf::from).collect();
    if files.is_empty() {
        eprintln!("Usage: track-fmt <file.track>… (rewrites files in canonical format)");
        return ExitCode::FAILURE;
    }
    for file in files {
        let source = match std::fs::read_to_string(&file) {
            Ok(source) => source,
            Err(error) => {
                eprintln!("Reading {}: {error}", file.display());
                return ExitCode::FAILURE;
            }
        };
        let song = match source.parse::<Song>() {
            Ok(song) => song,
            Err(error) => {
                eprintln!("Parsing {}: {error}", file.display());
                return ExitCode::FAILURE;
            }
        };
        let canonical = song.to_string();
        if canonical == source {
            continue;
        }
        if let Err(error) = std::fs::write(&file, canonical) {
            eprintln!("Writing {}: {error}", file.display());
            return ExitCode::FAILURE;
        }
        eprintln!("Reformatted {}", file.display());
    }
    ExitCode::SUCCESS
}
