// 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)
//
// `openai` — chat completions via the OpenAI REST API.
// Credential: openai = { api_key = "sk-...", base_url? = "https://api.openai.com/v1" }
// Operation: chat (default). Returns the assistant message + raw response.

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

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

#[async_trait]
impl Node for OpenAiNode {
    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("openai.api_key".into()))?
            .to_string();
        let base_url = ctx.credential_field("base_url").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .unwrap_or_else(|| "https://api.openai.com/v1".to_string());
        let model = ctx.param_opt_str("model").unwrap_or_else(|| "gpt-4o-mini".to_string());
        let prompt = ctx.param_str("prompt")?;
        let system = ctx.param_opt_str("system");
        let temperature = ctx.node_def.parameters.get("temperature")
            .and_then(|v| v.as_f64()).unwrap_or(0.7);

        let mut messages = Vec::new();
        if let Some(sys) = system {
            messages.push(json!({ "role": "system", "content": sys }));
        }
        messages.push(json!({ "role": "user", "content": prompt }));

        let body = json!({
            "model": model,
            "messages": messages,
            "temperature": temperature,
        });

        let client = reqwest::Client::new();
        let resp = client.post(format!("{}/chat/completions", base_url.trim_end_matches('/')))
            .bearer_auth(&api_key)
            .json(&body)
            .send().await
            .map_err(|e| NodeError::Http(format!("openai: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await
            .map_err(|e| NodeError::Http(format!("openai response: {}", e)))?;
        if !status.is_success() {
            return Err(NodeError::Http(format!("openai {}: {}", status, parsed)));
        }
        let assistant = parsed.get("choices")
            .and_then(|c| c.get(0))
            .and_then(|c| c.get("message"))
            .and_then(|m| m.get("content"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let item = NodeItem {
            json: json!({ "content": assistant, "raw": parsed }),
            ..Default::default()
        };
        Ok(vec![vec![item]])
    }
}

inventory::submit! { NodeFactory::new("openai", || Arc::new(OpenAiNode)) }
