from fastapi import APIRouter, HTTPException, Request
from typing import Dict, Any
import json
import logging

from jingrow.ai.pagetype.local_ai_agent.local_ai_agent import create_agent_job, validate_agent_execution
from jingrow.utils.jingrow_api import get_agent_detail

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post("/jingrow/agents/execute")
async def execute_agent(request: Request, request_data: Dict[str, Any]):
    """
    异步执行智能体（参考 Jingrow 的触发逻辑）
    当智能体状态为待执行时，入队执行
    """
    try:
        agent_id = request_data.get('agent_id')
        agent_name = request_data.get('agent_name')
        
        if not agent_id:
            raise HTTPException(status_code=400, detail="agent_id is required")
        
        logger.info(f"Executing agent: {agent_id}, name: {agent_name}")
        
        # 获取用户的 session cookie
        session_cookie = request.cookies.get('sid')
        if not session_cookie:
            logger.warning("No session cookie found, using system authentication")
        
        # 使用 AgentService 创建任务
        job_id = create_agent_job(agent_id, agent_name, session_cookie, "jingrow/agents/execute")
        
        logger.info(f"Agent {agent_id} queued for execution")
        
        return {
            "success": True,
            "message": "Agent execution queued successfully",
            "agent_id": agent_id,
            "job_id": job_id,
        }
        
    except Exception as e:
        logger.error(f"Failed to execute agent {agent_id}: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/jingrow/agents/execute_scheduled_agent")
async def execute_scheduled_agent(request: Request, request_data: Dict[str, Any]):
    """
    定时任务统一入口，执行指定的智能体
    解析并执行 jingrow/agents/execute_scheduled_agent:agent_id 格式的路由
    参考 Jingrow 的 execute_scheduled_agents 函数实现
    """
    try:
        # 从请求数据中获取方法名，格式为: jingrow/agents/execute_scheduled_agent:agent_id
        method = request_data.get('method', '')
        
        if not method:
            raise HTTPException(status_code=400, detail="method is required")
        
        # 解析方法名，提取 agent_id
        if not method.startswith('jingrow/agents/execute_scheduled_agent:'):
            raise HTTPException(status_code=400, detail="Invalid method format, expected: jingrow/agents/execute_scheduled_agent:agent_id")
        
        agent_id = method.split(':', 1)[1] if ':' in method else ''
        
        if not agent_id:
            raise HTTPException(status_code=400, detail="agent_id is required in method")
        
        logger.info(f"Executing scheduled agent: {agent_id}")
        
        # 获取用户的 session cookie
        session_cookie = request.cookies.get('sid')
        if not session_cookie:
            logger.warning("No session cookie found for scheduled agent execution, using system authentication")
        
        # 根据 agent_id 获取 agent_name
        agent_name = None
        try:
            agent_detail = get_agent_detail(agent_id, session_cookie)
            if agent_detail:
                agent_name = agent_detail.get('agent_name')
                logger.info(f"Found agent_name: {agent_name} for agent_id: {agent_id}")
        except Exception as e:
            logger.warning(f"Failed to get agent_name for {agent_id}: {e}")
        
        # 使用 AgentService 创建任务
        job_id = create_agent_job(agent_id, agent_name, session_cookie, "jingrow/agents/execute_scheduled_agent", method)
        
        logger.info(f"Scheduled agent {agent_id} queued for execution")
        
        return {
            "success": True,
            "message": "Scheduled agent execution queued successfully",
            "agent_id": agent_id,
            "agent_name": agent_name,
            "job_id": job_id,
            "method": method
        }
        
    except Exception as e:
        logger.error(f"Failed to execute scheduled agent: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))