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

import re
import jingrow
from jingrow.model.page import Page
from jingrow.ai.utils.utils import smart_truncate

class KnowledgeBase(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

		category: DF.Link | None
		content_type: DF.Literal["Jeditor", "Markdown Editor", "HTML Editor", "Code"]
		modified_by1: DF.Link | None
		status: DF.Literal["Draft", "Published", "Unpublished"]
		title: DF.Data | None
	# end: auto-generated types

	def on_update(self):
		"""更新后的钩子函数"""
		
		# 检查是否有需要处理的文本内容
		texts_to_process = []
		
		# 处理标题
		if self.title and self.title.strip():
			texts_to_process.append(f"标题: {self.title.strip()}")
		
		# 处理内容摘要
		if self.content and self.content.strip():
			# 提取纯文本内容（去除HTML标签）
			clean_content = re.sub(r'<[^>]+>', '', self.content.strip())
			if clean_content:
				# 智能截断到500字符，避免截断单词或汉字
				summary = smart_truncate(clean_content, 500)
				texts_to_process.append(f"内容: {summary}")
		
		# 提交异步任务：按当前记录生成/更新向量
		jingrow.enqueue(
			"jingrow.ai.utils.embedding.create_text_embeddings_task",
			pagetype=self.pagetype,
			pg_name=self.name,
		)

	def on_trash(self):
		# 删除对应的向量数据（按payload过滤整条记录：pagetype + name），异步执行
		jingrow.enqueue(
			"jingrow.ai.utils.embedding.delete_vectors_by_filter",
			collection_name="knowledge_base",
			pagetype=self.pagetype,
			name=self.name,
		)
