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

import jingrow
from jingrow.model.page import Page


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

		agent_flow: DF.JSON | None
		agent_name: DF.Data
		ai_repeat: DF.Int
		condition: DF.SmallText | None
		enabled: DF.Check
		event_type: DF.Literal["", "on_update", "after_insert", "on_submit", "on_cancel", "on_trash"]
		exclude_prompts: DF.Text | None
		progress: DF.Percent
		status: DF.Literal["", "\u8349\u7a3f", "\u5f85\u6267\u884c", "\u8fdb\u884c\u4e2d", "\u672a\u5b8c\u6210", "\u5df2\u5b8c\u6210"]
		target_module: DF.Link | None
		target_pagetype: DF.Link | None
		trigger_mode: DF.Literal["Manual Trigger", "Event Trigger", "Scheduled Trigger"]
	# end: auto-generated types
	
	def validate(self):
		if getattr(self, "agent_flow", None) in (None, ""):
			self.agent_flow = None
	
	def on_update(self):
		"""更新时管理定时任务"""
		self._manage_scheduled_job()
	
	def after_insert(self):
		"""插入记录后的处理"""
		self._manage_scheduled_job()
	
	def on_trash(self):
		"""删除时清理定时任务"""
		self._manage_scheduled_job()
	
	def _manage_scheduled_job(self):
		"""管理定时Ai Agent的定时任务，根据当前状态创建、更新或删除定时任务
		参考 Jingrow 系统的 Ai Agent._manage_scheduled_job 实现
		"""
		agent_id = self.name
		cron = getattr(self, "trigger_time", None) or getattr(self, "cron_format", None)
		method_name = f"jingrow/agents/execute_scheduled_agent:{agent_id}"
		
		# 检查是否存在对应的定时任务
		job = jingrow.db.exists("Local Scheduled Job", {"method": method_name})
		
		# 判断是否需要定时任务的条件
		needs_scheduled_job = (
			self.enabled and 
			self.trigger_mode == "Scheduled Trigger" and 
			cron and 
			cron.strip()
		)
		
		if needs_scheduled_job:
			# 需要定时任务：创建或更新
			if job:
				# 更新现有定时任务
				pg = jingrow.get_pg("Local Scheduled Job", job)
				pg.cron_format = cron
				pg.frequency = "Cron"
				pg.method = method_name
				pg.save()
			else:
				# 创建新的定时任务
				pg = jingrow.new_pg(
					"Local Scheduled Job",
					method=method_name,
					cron_format=cron,
					frequency="Cron"
				)
				pg.insert()
		else:
			# 不需要定时任务：删除已存在的定时任务
			if job:
				jingrow.delete_pg("Local Scheduled Job", job)
