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 ParseJsonNode;

impl EvalImpl for ParseJsonNode {
    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")?;
        
        // This relies on ctx.parse_json(json, path) which returns Option<String>
        let val = ctx.parse_json(&json, &path).unwrap_or_default();
        Ok(RuntimeValue::String(val))
    }
}

impl super::super::framework::NodeDescription for ParseJsonNode {
    fn description(&self) -> &str {
        "Parses JSON and extracts a value at a given path."
    }
}

fn default_params() -> NodeParams {
    NodeParams::JsonPath(String::new())
}

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> {
    ParseJsonNode.evaluate(graph, ctx, node, pin_id)
}

crate::register_node!(NodeSpec {
    id: "ParseJson",
    display_name: "Parse JSON",
    documentation: "Parses JSON and extracts a value at a given path.",
    category: NodeCategory::Network,
    library: NodeLibrary::Http,
    param_kind: ParamKind::JsonPath,
    default_params,
    pins,
    execute: None,
    evaluate: Some(eval),
});
