use std::io::{self, Read, Write};
use std::process::ExitCode;

use radial_sugiyama::{
    process_go_bridge_request_with_options, BridgeRuntimeConfig, EnvConfig, GoBridgeRequest,
};

fn main() -> ExitCode {
    if let Err(error) = run() {
        eprintln!("{error}");
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let env_config = EnvConfig::from_env()?;
    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;

    let request: GoBridgeRequest = serde_json::from_str(&input)?;
    let response = process_go_bridge_request_with_options(
        request,
        BridgeRuntimeConfig {
            layout: env_config.layout,
            svg: env_config.svg,
            svg_output_path: Some(env_config.output_path()),
            canonicalize_input: true,
        },
    )?;

    let stdout = io::stdout();
    let mut handle = stdout.lock();
    serde_json::to_writer(&mut handle, &response)?;
    handle.write_all(b"\n")?;

    Ok(())
}
