use super::super::framework::{EvalImpl, eval_input};
use crate::gui_builder::node_registry::{NodeSpec, ParamKind};
use crate::gui_builder::nodes::{Node, NodeCategory, NodeGraph, NodeLibrary, NodeParams, Pin, PinType};
use crate::gui_builder::runtime::{RuntimeContext, RuntimeValue};

pub struct JsonArrayLengthNode;

impl EvalImpl for JsonArrayLengthNode {
    fn evaluate(&self, graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, _pin_id: usize) -> Result<RuntimeValue, String> {
        let array_val = eval_input(graph, ctx, node.id, "array")?;
        
        let length = match array_val {
            RuntimeValue::Array(arr) => arr.len(),
            _ => 0,
        };
        
        Ok(RuntimeValue::Float(length as f32))
    }
}

impl super::super::framework::NodeDescription for JsonArrayLengthNode {
    fn description(&self) -> &str {
        "Returns the number of elements in a JSON array."
    }
}

fn default_params() -> NodeParams {
    NodeParams::None
}

fn pins(next_pin_id: &mut usize) -> Vec<Pin> {
    let mut pins = Vec::new();
    pins.push(Pin::new(*next_pin_id, PinType::Array, true, "array"));
    *next_pin_id += 1;
    pins.push(Pin::new(*next_pin_id, PinType::Float, false, "length"));
    *next_pin_id += 1;
    pins
}

fn eval(graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, pin_id: usize) -> Result<RuntimeValue, String> {
    JsonArrayLengthNode.evaluate(graph, ctx, node, pin_id)
}

crate::register_node!(NodeSpec {
    id: "JsonArrayLength",
    display_name: "JSON Array Length",
    documentation: "Returns the number of elements in a JSON array.",
    category: NodeCategory::Data,
    library: NodeLibrary::Json,
    param_kind: ParamKind::None,
    default_params,
    pins,
    execute: None,
    evaluate: Some(eval),
});
