use crate::cli::{eval, ok, DEFAULT_PORT};
use anyhow::Result;
use clap::Parser;

#[derive(Parser)]
pub struct Args {
    /// Optional node name to frame on. Whole model when omitted.
    pub name: Option<String>,
    #[arg(long, default_value_t = 5)]
    pub timeout_secs: u64,
    #[arg(long, default_value_t = DEFAULT_PORT)]
    pub port: u16,
}

pub fn run(args: Args) -> Result<()> {
    let arg = match &args.name {
        Some(n) => serde_json::to_string(n).unwrap(),
        None => "null".to_string(),
    };
    let code = format!(
        "return window.adomStep ? window.adomStep.frame({}) : {{ error: 'adomStep not loaded' }};",
        arg
    );
    eval::eval_snippet(&code, args.timeout_secs, args.port, true)?;
    match args.name {
        Some(n) => ok(format!("framed {}", n)),
        None => ok("framed whole model"),
    }
    Ok(())
}