use clap::Parser;
use roto_codegen::generator::generate_protobuf_code;
use roto_codegen::google::protobuf::descriptor::FileDescriptorSet;
use std::fs;
use std::path::PathBuf;

#[derive(Parser)]
#[command(
    author,
    version,
    about = "Generates Rust accessor and builder code from a protobuf descriptor set"
)]
struct Args {
    /// Path to the descriptor set file (.desc)
    #[arg(short, long)]
    input: PathBuf,

    /// Path to the output directory
    #[arg(short, long)]
    output: PathBuf,

    /// Files to generate. If omitted, all files are generated.
    #[arg(short, long, value_delimiter = ',')]
    files: Option<Vec<String>>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();
    let data = fs::read(&args.input)?;
    let set = FileDescriptorSet::new(&data).expect("Failed to parse FileDescriptorSet");

    let files = generate_protobuf_code(&set, args.files.as_deref(), true);

    for (filename, content) in files {
        let path = args.output.join(filename);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, content)?;
    }
    Ok(())
}
