"""TUI handler - connects the TUI to the EmDash agent via SSE."""

import asyncio
import json
import os
from typing import AsyncIterator

import httpx


def create_agent_handler(
    model: str = "claude-sonnet-4",
    mode: str = "code",
    max_iterations: int = 100,
):
    """Create an async handler that streams agent responses.

    Args:
        model: Model name to use
        mode: Agent mode (code or plan)
        max_iterations: Maximum agent iterations

    Returns:
        Async callable that takes a message and yields events
    """
    # Get server URL from server manager
    from ..server_manager import get_server_manager

    server = get_server_manager()
    server_url = server.get_server_url()

    # Track session ID for multi-turn conversations
    session_id = None

    async def handler(message: str) -> AsyncIterator[dict]:
        """Process a message and stream events back.

        Args:
            message: User message to process

        Yields:
            Event dicts with type and data keys
        """
        nonlocal session_id

        async with httpx.AsyncClient(timeout=None) as client:
            payload = {
                "message": message,
                "model": model,
                "options": {
                    "max_iterations": max_iterations,
                    "verbose": True,
                    "mode": mode,
                },
            }

            if session_id:
                payload["session_id"] = session_id

            url = f"{server_url}/api/agent/chat"

            try:
                async with client.stream("POST", url, json=payload) as response:
                    response.raise_for_status()

                    current_event = None

                    async for line in response.aiter_lines():
                        line = line.strip()

                        if line.startswith("event: "):
                            current_event = line[7:]
                        elif line.startswith("data: "):
                            if current_event:
                                try:
                                    data = json.loads(line[6:])
                                    if data is None:
                                        data = {}

                                    # Capture session ID for multi-turn
                                    if current_event == "session_start":
                                        if data.get("session_id"):
                                            session_id = data["session_id"]

                                    yield {
                                        "type": current_event,
                                        "data": data,
                                    }
                                except json.JSONDecodeError:
                                    pass
                        elif line == ": ping":
                            # Keep-alive ping - ignore
                            pass

            except httpx.HTTPError as e:
                yield {
                    "type": "error",
                    "data": {"message": f"HTTP error: {str(e)}"},
                }
            except Exception as e:
                yield {
                    "type": "error",
                    "data": {"message": str(e)},
                }

    return handler
