"""SSE streaming клиент для /browser/chat/stream."""

from __future__ import annotations

import json
from typing import Any, AsyncGenerator

import httpx

from acl_cli.client import ACLClient


async def process_with_ai(
    text: str,
    user_id: str,
    client: ACLClient,
    session_id: str | None = None,
    site_url: str | None = None,
) -> AsyncGenerator[tuple[str, Any], None]:
    """
    Стримит события с ACL сервера.
    Yields: (event_type, event_data)
    event_type: tool_start | tool_done | response | error | done
    """
    payload: dict[str, Any] = {"message": text}
    if session_id:
        payload["session_id"] = session_id
    if site_url:
        payload["site_url"] = site_url

    async with httpx.AsyncClient(timeout=120) as http:
        async with http.stream(
            "POST",
            f"{client.base_url}/browser/chat/stream",
            json=payload,
            headers={
                "Authorization": f"Bearer {client.api_key}",
                "X-User-ID": user_id,
                "Accept": "text/event-stream",
            },
        ) as response:
            if response.status_code != 200:
                yield ("error", {"message": f"HTTP {response.status_code}"})
                return

            async for line in response.aiter_lines():
                if line.startswith("data: "):
                    raw = line[6:].strip()
                    if not raw:
                        continue
                    try:
                        event = json.loads(raw)
                        event_type = event["type"]
                        if event_type == "need_credentials":
                            yield ("need_credentials", event)
                        else:
                            yield (event_type, event)
                    except json.JSONDecodeError:
                        continue
