//! DAG 定义 — 可序列化/反序列化，用于持久化和模板

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// DAG 定义 — 可序列化/反序列化，用于持久化和模板
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct DagDef {
    pub nodes: HashMap<String, NodeDef>,
    pub edges: Vec<EdgeDef>,
}

/// 节点定义
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NodeDef {
    pub id: String,
    pub node_type: String,
    pub config: serde_json::Value,
    #[serde(default)]
    pub label: Option<String>,
}

/// 边定义
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct EdgeDef {
    pub source: String,
    pub target: String,
    #[serde(default)]
    pub condition: Option<String>,
}

impl DagDef {
    /// 创建空的 DAG 定义
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            edges: Vec::new(),
        }
    }

    /// 添加节点定义
    pub fn add_node(&mut self, id: impl Into<String>, node_type: impl Into<String>, config: serde_json::Value) {
        let id = id.into();
        self.nodes.insert(id.clone(), NodeDef {
            id,
            node_type: node_type.into(),
            config,
            label: None,
        });
    }

    /// 添加边定义
    pub fn add_edge(&mut self, source: impl Into<String>, target: impl Into<String>) {
        self.edges.push(EdgeDef {
            source: source.into(),
            target: target.into(),
            condition: None,
        });
    }

    /// 添加带条件的边定义
    pub fn add_edge_with_condition(
        &mut self,
        source: impl Into<String>,
        target: impl Into<String>,
        condition: impl Into<String>,
    ) {
        self.edges.push(EdgeDef {
            source: source.into(),
            target: target.into(),
            condition: Some(condition.into()),
        });
    }
}

impl Default for DagDef {
    fn default() -> Self {
        Self::new()
    }
}
