import jingrow
import json
import os
from typing import Dict, List

def get_schema_file_path(node_type: str) -> str:
    """获取Schema文件路径：nodes/{node_type}/{node_type}.json"""
    base_path = jingrow.get_app_path("jingrow")
    return os.path.join(
        base_path, "ai", "nodes",
        f"{node_type}/{node_type}.json"
    )



@jingrow.whitelist()
def get_node_schema(node_type: str) -> Dict:
    """
    获取节点Schema配置
    约定路径：nodes/{node_type}/{node_type}.json
    """
    if not node_type:
        jingrow.throw("参数错误", "node_type不能为空")
    
    file_path = get_schema_file_path(node_type)
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        jingrow.throw("Schema加载失败", f"节点 {node_type}: {str(e)}")

@jingrow.whitelist()
def get_node_schema_fields(node_type: str) -> List[Dict]:
    """
    获取节点可用字段列表
    返回格式：[{"name": "field_name", "label": "显示名称", "type": "字段类型", "description": "描述"}]
    """
    if not node_type:
        jingrow.throw("参数错误", "node_type不能为空")
    
    try:
        schema = get_node_schema(node_type)
        if not schema or 'properties' not in schema:
            return []
        
        fields = []
        for name, config in schema['properties'].items():
            fields.append({
                'name': name,
                'label': config.get('title', name),
                'type': config.get('type', 'string'),
                'description': config.get('description', '')
            })
        
        return fields
    except Exception as e:
        jingrow.log_error(f"获取节点{node_type}字段失败", str(e))
        return [] 





