// r8r: rust port of n8n.io
// Initial author: Michael Cochran <mcochran@cochranblock.org>
// Built for: Tanner Woodrum, intended cofounder
// License: Unlicense (public domain dedication, see UNLICENSE)
//
// `html` — extract elements from HTML by CSS selector via the scraper
// crate. Operations: extract (selector → array of strings).

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use scraper::{Html, Selector};
use serde_json::{json, Value};
use std::sync::Arc;

pub struct HtmlNode;

static META: NodeMetadata = NodeMetadata {
    name: "html",
    display_name: "HTML",
    version: &[1, 2],
    group: &["transform"],
    description: "Extract HTML elements by CSS selector",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

#[async_trait]
impl Node for HtmlNode {
    fn metadata(&self) -> &'static NodeMetadata { &META }

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let html = ctx.param_str("html")?;
        let selector = ctx.param_str("selector")?;
        let attribute = ctx.node_def.parameters.get("attribute")
            .and_then(|v| v.as_str()).map(|s| s.to_string());
        let field = ctx.node_def.parameters.get("output_field")
            .and_then(|v| v.as_str()).unwrap_or("matches").to_string();

        let doc = Html::parse_document(&html);
        let sel = Selector::parse(&selector)
            .map_err(|e| NodeError::Other(format!("html: bad selector: {:?}", e)))?;
        let matches: Vec<Value> = doc.select(&sel)
            .map(|el| match &attribute {
                Some(attr) => Value::String(el.value().attr(attr).unwrap_or("").to_string()),
                None => Value::String(el.text().collect::<String>().trim().to_string()),
            })
            .collect();

        let items_in = if ctx.input.is_empty() { vec![NodeItem::default()] } else { ctx.input.clone() };
        let mut out = Vec::with_capacity(items_in.len());
        for item in items_in {
            let mut new_json = if item.json.is_object() { item.json.clone() } else { json!({}) };
            new_json.as_object_mut().unwrap().insert(field.clone(), Value::Array(matches.clone()));
            out.push(NodeItem { json: new_json, ..item });
        }
        Ok(vec![out])
    }
}

inventory::submit! { NodeFactory::new("html", || Arc::new(HtmlNode)) }
