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

import jingrow
from jingrow.model.page import Page

import json
import uuid
import logging
from typing import Optional, Dict, Any

from jingrow.services.queue import init_queue, execute_local_scheduled_job
from jingrow.services.local_job_manager import local_job_manager
from jingrow.utils.jingrow_api import get_logged_user, update_local_job

logger = logging.getLogger(__name__)


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

	pass


def create_agent_job(
	agent_id: str,
	agent_name: Optional[str] = None,
	session_cookie: Optional[str] = None,
	route: str = "jingrow/agents/execute",
	method: Optional[str] = None,
	inputs: Optional[Dict[str, Any]] = None
) -> str:
	"""
	创建智能体执行任务的通用函数
	
	Args:
		agent_id: 智能体ID
		agent_name: 智能体名称
		session_cookie: 会话Cookie
		route: 路由类型
		method: 方法名（用于定时任务）
		
	Returns:
		job_id: 创建的任务ID
	"""
	# 初始化队列
	init_queue()
	
	# 生成 job_id
	job_id = str(uuid.uuid4())
	
	# 构建执行任务载荷
	payload = {
		'target_type': 'agent',
		'agent_id': agent_id,
		'agent_name': agent_name,
		'session_cookie': session_cookie,
		'job_id': job_id,
		'route': route,
	}

	# 透传触发时的上下文输入（例如 pagetype/name）
	if inputs and isinstance(inputs, dict):
		payload['inputs'] = inputs
	
	if method:
		payload['method'] = method
	
	# 创建本地任务记录
	try:
		# 根据路由类型设置不同的任务名称格式
		if route == "jingrow/agents/execute_scheduled_agent":
			job_name = f"Scheduled Agent: {agent_name} {agent_id}"
		else:
			job_name = f"Agent: {agent_name} {agent_id}"
		
		# 创建不包含敏感信息的参数对象
		safe_arguments = {k: v for k, v in payload.items() if k != 'session_cookie'}
		
		# 获取当前用户（使用系统级认证）
		creator = get_logged_user(session_cookie) or 'system'
		
		# 创建本地任务
		local_job_manager.create_job({
			'job_id': job_id,
			'target_type': 'agent',
			'agent_id': agent_id,
			'agent_name': agent_name,
			'session_cookie': session_cookie,
			'status': 'queued',
			'queue': 'default',
			'job_name': job_name,
			'arguments': safe_arguments,
			'owner': creator,
			'modified_by': creator
		})
		
		# 立即推送到 Jingrow Local Job（使用系统级认证）
		jingrow_payload = {
			'job_id': job_id,
			'name': job_id,
			'queue': 'default',
			'job_name': job_name,
			'status': 'queued',
			'arguments': json.dumps(safe_arguments, indent=2, ensure_ascii=False),
			'owner': creator,
			'modified_by': creator,
			'session_cookie': session_cookie
		}
		update_local_job(jingrow_payload)
		
	except Exception as e:
		logger.error(f"Failed to create and push job: {e}")
		pass
	
	# 入队执行（异步）
	execute_local_scheduled_job.send(json.dumps(payload))
	
	return job_id


def validate_agent_execution(agent_id: str, session_cookie: Optional[str] = None) -> bool:
	"""
	验证智能体是否可以执行
	
	Args:
		agent_id: 智能体ID
		session_cookie: 会话Cookie
		
	Returns:
		bool: 是否可以执行
	"""
	try:
		from jingrow.utils.jingrow_api import get_agent_detail
		agent_detail = get_agent_detail(agent_id, session_cookie)
		return agent_detail is not None and agent_detail.get('agent_flow') is not None
	except Exception as e:
		logger.error(f"Failed to validate agent {agent_id}: {e}")
		return False


def get_agent_execution_status(job_id: str) -> Optional[Dict[str, Any]]:
	"""
	获取智能体执行状态
	
	Args:
		job_id: 任务ID
		
	Returns:
		Dict: 任务状态信息
	"""
	try:
		return local_job_manager.get_job(job_id)
	except Exception as e:
		logger.error(f"Failed to get job status {job_id}: {e}")
		return None


def cancel_agent_job(job_id: str) -> bool:
	"""
	取消智能体任务
	
	Args:
		job_id: 任务ID
		
	Returns:
		bool: 是否成功取消
	"""
	try:
		# 更新任务状态为取消
		local_job_manager.update_job(job_id, {
			'status': 'cancelled',
			'modified': __import__('datetime').datetime.now().isoformat()
		})
		
		# 推送到 Jingrow
		from jingrow.services.queue import _push_status_to_jingrow
		import asyncio
		asyncio.run(_push_status_to_jingrow(job_id, {'status': 'cancelled'}))
		
		return True
	except Exception as e:
		logger.error(f"Failed to cancel job {job_id}: {e}")
		return False