"""Agent Session API 路由 - Phase 10.3"""

from typing import Any

from fastapi import APIRouter, HTTPException

from app.agents.session.manager import AgentSession, create_agent_session, get_agent_session

router = APIRouter(prefix="/api/agent/sessions", tags=["Agent Sessions"])


@router.post("", response_model=dict[str, Any])
async def create_session(
    user_id: str | None = None,
    parent_session_id: str | None = None,
) -> dict[str, Any]:
    """创建新会话"""
    session = create_agent_session(
        user_id=user_id,
        parent_session_id=parent_session_id,
    )
    return await session.initialize()


@router.get("/{session_id}", response_model=dict[str, Any])
async def get_session(session_id: str) -> dict[str, Any]:
    """获取会话信息"""
    session = get_agent_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
    return await session.get_session_summary()


@router.post("/{session_id}/message", response_model=dict[str, str])
async def process_message(
    session_id: str,
    message: str,
    response: str,
) -> dict[str, str]:
    """处理消息"""
    session = get_agent_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
    await session.process_message(message, response)
    return {"status": "recorded", "session_id": session_id}


@router.post("/{session_id}/spawn", response_model=dict[str, Any])
async def spawn_child_session(
    session_id: str,
    user_id: str | None = None,
) -> dict[str, Any]:
    """创建子会话"""
    session = get_agent_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
    child = await session.spawn_child_session(user_id=user_id)
    return await child.get_session_summary()


@router.get("/{session_id}/history", response_model=dict[str, Any])
async def get_session_history(session_id: str) -> dict[str, Any]:
    """获取会话历史"""
    session = get_agent_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
    return {
        "session_id": session_id,
        "history": session.get_history(),
        "count": len(session._history),
    }


@router.post("/{session_id}/persist", response_model=dict[str, str])
async def persist_session(session_id: str) -> dict[str, str]:
    """持久化会话"""
    session = get_agent_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
    success = await session.persist()
    if success:
        return {"status": "persisted", "session_id": session_id}
    raise HTTPException(status_code=500, detail="Failed to persist session")


@router.post("/{session_id}/metadata", response_model=dict[str, Any])
async def set_session_metadata(
    session_id: str,
    key: str,
    value: Any,
) -> dict[str, Any]:
    """设置会话元数据"""
    session = get_agent_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
    session.add_metadata(key, value)
    await session.persist()
    return {"key": key, "value": value}


@router.get("/{session_id}/metadata/{key}", response_model=dict[str, Any])
async def get_session_metadata(
    session_id: str,
    key: str,
) -> dict[str, Any]:
    """获取会话元数据"""
    session = get_agent_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
    value = session.get_metadata(key)
    if value is None:
        raise HTTPException(status_code=404, detail=f"Metadata key '{key}' not found")
    return {"key": key, "value": value}
