"""Manages conversation context for voice sessions, pulling data from agent-service."""

from dataclasses import dataclass, field
from typing import Optional


@dataclass
class SessionContext:
    session_id: str
    tenant_id: str
    system_prompt: str = ""
    available_tools: list = field(default_factory=list)
    standing_order_id: Optional[str] = None
    order_name: Optional[str] = None
    event_summary: Optional[str] = None
    server_context: dict = field(default_factory=dict)

    @classmethod
    async def from_agent_service(cls, agent_service_url: str, session_id: str, tenant_id: str) -> "SessionContext":
        """Fetch context from agent-service for an existing session."""
        import httpx
        async with httpx.AsyncClient() as client:
            resp = await client.get(f"{agent_service_url}/api/v1/agent/sessions/{session_id}")
            if resp.status_code == 200:
                data = resp.json()
                return cls(
                    session_id=session_id,
                    tenant_id=tenant_id,
                    system_prompt=data.get("systemPrompt", ""),
                    available_tools=data.get("allowedTools", []),
                )
        return cls(session_id=session_id, tenant_id=tenant_id)

    def build_system_prompt(self) -> str:
        base = self.system_prompt or "你是 IT0 运维智能体，通过语音与管理员交互。"
        if self.order_name:
            base += f"\n\n当前正在处理驻留指令「{self.order_name}」的升级事件。"
        if self.event_summary:
            base += f"\n事件摘要：{self.event_summary}"
        return base
