# Copyright (c) 2025, Jingrow and contributors
# For license information, please see license.txt

import jingrow
import os
import json
from jingrow.model.page import Page



class AiNode(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		node_color: DF.Color | None
		node_component: DF.Literal["GenericNode", "MultiOutputNode"]
		node_description: DF.SmallText | None
		node_group: DF.Literal["", "AI", "\u8f93\u5165", "\u8f93\u51fa", "\u63a7\u5236", "\u6570\u636e", "\u76d1\u63a7"]
		node_icon: DF.Data | None
		node_label: DF.Data | None
		node_schema: DF.JSON | None
		node_type: DF.Data | None
		status: DF.Literal["Published", "Unpublished", "Draft"]
	# end: auto-generated types
	
	def validate(self):
		"""验证 schema JSON 格式"""
		if self.node_schema:
			json.dumps(self.node_schema)
	
	def before_save(self):
		"""保存前验证"""
		self.validate()


# 独立的API端点函数
@jingrow.whitelist()
def load_node_schema(node_type):
	"""加载指定节点类型的 schema"""
	
	schema_file = jingrow.get_app_path("jingrow", "ai", "nodes", node_type, f"{node_type}.json")
	
	if not os.path.exists(schema_file):
		return None
	
	with open(schema_file, 'r', encoding='utf-8') as f:
		schema_data = json.load(f)
		jingrow.response["data"] = schema_data
		return None


@jingrow.whitelist()
def save_node_schema(node_type, schema_data):
	"""保存节点 schema 到文件"""
	# 如果是字符串，先解析为对象
	if isinstance(schema_data, str):
		schema_data = json.loads(schema_data)
	
	schema_file = jingrow.get_app_path("jingrow", "ai", "nodes", node_type, f"{node_type}.json")
	os.makedirs(os.path.dirname(schema_file), exist_ok=True)
	
	with open(schema_file, 'w', encoding='utf-8') as f:
		json.dump(schema_data, f, ensure_ascii=False, indent=2, separators=(',', ': '))




