use super::super::framework::{EvalImpl, eval_input_string};
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::{ComponentContext, RuntimeContext, RuntimeValue};

pub struct JsonExtractPathNode;

impl EvalImpl for JsonExtractPathNode {
    fn evaluate(&self, graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, _pin_id: usize) -> Result<RuntimeValue, String> {
        let json = eval_input_string(graph, ctx, node.id, "json")?;
        let path = eval_input_string(graph, ctx, node.id, "path")?;
        
        // Use ctx.parse_json which handles dot-notation paths
        let val = ctx.parse_json(&json, &path).unwrap_or_default();
        Ok(RuntimeValue::String(val))
    }
}

impl super::super::framework::NodeDescription for JsonExtractPathNode {
    fn description(&self) -> &str {
        "Extracts a value from JSON using a dot-notation path (e.g., 'data.users[0].name')."
    }
}

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::String, true, "json"));
    *next_pin_id += 1;
    pins.push(Pin::new(*next_pin_id, PinType::String, true, "path"));
    *next_pin_id += 1;
    pins.push(Pin::new(*next_pin_id, PinType::String, false, "value"));
    *next_pin_id += 1;
    pins
}

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

crate::register_node!(NodeSpec {
    id: "JsonExtractPath",
    display_name: "JSON Extract Path",
    documentation: "Extracts a value from JSON using a dot-notation path (e.g., 'data.users[0].name').",
    category: NodeCategory::Data,
    library: NodeLibrary::Json,
    param_kind: ParamKind::None,
    default_params,
    pins,
    execute: None,
    evaluate: Some(eval),
});
