use async_trait::async_trait;
use anyhow::{Result, anyhow, Context};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::time::Duration;

use common_contracts::workflow_node::{WorkflowNode, NodeContext, NodeExecutionResult, ArtifactContent, CacheKey};
use common_contracts::data_formatting;
use crate::state::AppState;

pub struct FinnhubNode {
    state: AppState,
}

impl FinnhubNode {
    pub fn new(state: AppState) -> Self {
        Self { state }
    }
}

#[async_trait]
impl WorkflowNode for FinnhubNode {
    fn node_type(&self) -> &str {
        "finnhub"
    }

    fn get_cache_config(&self, config: &Value) -> Option<(CacheKey, Duration)> {
        let symbol = config.get("symbol").and_then(|s| s.as_str())?;
        
        let key_parts = vec![
            "finnhub",
            "company_data",
            symbol,
            "all"
        ];
        
        let cache_key = CacheKey(key_parts.join(":"));
        // Finnhub data - 24h TTL
        let ttl = Duration::from_secs(86400);

        Some((cache_key, ttl))
    }

    async fn execute(&self, _ctx: &NodeContext, config: &Value) -> Result<NodeExecutionResult> {
        let symbol = config.get("symbol").and_then(|s| s.as_str()).unwrap_or("").to_string();
        
        if symbol.is_empty() {
            return Err(anyhow!("Missing symbol in config"));
        }

        // 1. Fetch Data
        let provider = self.state.get_provider().await
            .ok_or_else(|| anyhow!("Finnhub Provider not initialized"))?;

        let (profile, financials) = provider.fetch_all_data(&symbol).await
            .context("Failed to fetch data from Finnhub")?;

        // 2. Artifacts
        let mut artifacts = HashMap::new();
        artifacts.insert("profile.json".to_string(), json!(profile).into());
        artifacts.insert("financials.json".to_string(), json!(financials).into());

        Ok(NodeExecutionResult {
            artifacts,
            meta_summary: Some(json!({
                "symbol": symbol,
                "records": financials.len()
            })),
        })
    }

    fn render_report(&self, result: &NodeExecutionResult) -> Result<String> {
        let profile_json = match result.artifacts.get("profile.json") {
             Some(ArtifactContent::Json(v)) => v,
             _ => return Err(anyhow!("Missing profile.json")),
        };
        let financials_json = match result.artifacts.get("financials.json") {
             Some(ArtifactContent::Json(v)) => v,
             _ => return Err(anyhow!("Missing financials.json")),
        };

        let symbol = profile_json["symbol"].as_str().unwrap_or("Unknown");

        let mut report_md = String::new();
        report_md.push_str(&format!("# Finnhub Data Report: {}\n\n", symbol));
        
        report_md.push_str("## Company Profile\n\n");
        report_md.push_str(&data_formatting::format_data(profile_json));
        report_md.push_str("\n\n");

        report_md.push_str("## Financial Statements\n\n");
        report_md.push_str(&data_formatting::format_data(financials_json));

        Ok(report_md)
    }
}

