// 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)
//
// `anthropic` — Messages API (claude.ai) chat completions.
// Credential: anthropic = { api_key = "sk-ant-...", base_url? = "..." }

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

pub struct AnthropicNode;

static META: NodeMetadata = NodeMetadata {
    name: "anthropic",
    display_name: "Anthropic",
    version: &[1],
    group: &["ai"],
    description: "Chat completions via the Anthropic Messages API",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "anthropic", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("api_key")?
            .as_str()
            .ok_or_else(|| NodeError::MissingCredential("anthropic.api_key".into()))?
            .to_string();
        let base_url = ctx.credential_field("base_url").ok()
            .and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string()))
            .unwrap_or_else(|| "https://api.anthropic.com".to_string());
        let model = ctx.param_opt_str("model").unwrap_or_else(|| "claude-sonnet-4-6".to_string());
        let prompt = ctx.param_str("prompt")?;
        let system = ctx.param_opt_str("system");
        let max_tokens = ctx.node_def.parameters.get("max_tokens")
            .and_then(|v| v.as_u64()).unwrap_or(1024);

        let mut body = json!({
            "model": model,
            "max_tokens": max_tokens,
            "messages": [{ "role": "user", "content": prompt }],
        });
        if let Some(sys) = system {
            body.as_object_mut().unwrap().insert("system".into(), Value::String(sys));
        }

        let resp = reqwest::Client::new()
            .post(format!("{}/v1/messages", base_url))
            .header("x-api-key", &api_key)
            .header("anthropic-version", "2023-06-01")
            .json(&body)
            .send().await
            .map_err(|e| NodeError::Http(format!("anthropic: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await
            .map_err(|e| NodeError::Http(format!("anthropic response: {}", e)))?;
        if !status.is_success() {
            return Err(NodeError::Http(format!("anthropic {}: {}", status, parsed)));
        }
        let content = parsed.get("content")
            .and_then(|c| c.get(0))
            .and_then(|c| c.get("text"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        Ok(vec![vec![NodeItem {
            json: json!({ "content": content, "raw": parsed }),
            ..Default::default()
        }]])
    }
}

inventory::submit! { NodeFactory::new("anthropic", || Arc::new(AnthropicNode)) }
