"""Optional session lifecycle callbacks for platform integration.

When running as a managed agent (e.g. on the RoohAI platform), the platform
sets these env vars so the framework reports session start/end events:

  ROOHAI_SESSION_START_URL  – POST on WebSocket/WebRTC session open
  ROOHAI_SESSION_END_URL    – POST on WebSocket/WebRTC session close
  ROOHAI_SESSION_HEADERS    – Extra headers as JSON (e.g. {"X-Agent-Id": "..."})

When the env vars are not set, all functions are silent no-ops — the framework
works exactly the same as a standalone open-source project.
"""

import json
import logging
import os

import aiohttp

logger = logging.getLogger(__name__)

_session: aiohttp.ClientSession | None = None


async def _get_session() -> aiohttp.ClientSession:
    global _session
    if _session is None or _session.closed:
        _session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5))
    return _session


def _get_headers() -> dict[str, str]:
    raw = os.environ.get("ROOHAI_SESSION_HEADERS", "")
    if raw:
        try:
            return json.loads(raw)
        except (json.JSONDecodeError, TypeError):
            logger.warning("Invalid JSON in ROOHAI_SESSION_HEADERS, ignoring")
    return {}


async def notify_session_start(session_id: str) -> None:
    """Notify the platform that a voice session has started."""
    url = os.environ.get("ROOHAI_SESSION_START_URL")
    if not url:
        return
    try:
        session = await _get_session()
        headers = _get_headers()
        async with session.post(url, json={"session_id": session_id}, headers=headers) as resp:
            if resp.status >= 400:
                logger.warning("Session start callback returned %d", resp.status)
    except Exception:
        logger.debug("Session start callback failed", exc_info=True)


async def notify_session_end(session_id: str) -> None:
    """Notify the platform that a voice session has ended."""
    url = os.environ.get("ROOHAI_SESSION_END_URL")
    if not url:
        return
    try:
        session = await _get_session()
        headers = _get_headers()
        async with session.post(url, json={"session_id": session_id}, headers=headers) as resp:
            if resp.status >= 400:
                logger.warning("Session end callback returned %d", resp.status)
    except Exception:
        logger.debug("Session end callback failed", exc_info=True)


async def shutdown() -> None:
    """Close the shared HTTP session. Called on server shutdown."""
    global _session
    if _session and not _session.closed:
        await _session.close()
        _session = None
