"""Components for streaming content from server-sent events (SSE)"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_streaming.ipynb.

# %% auto 0
__all__ = ['stream_script', 'StreamingContainer']

# %% ../nbs/04_streaming.ipynb 3
import fasthtml.common as fh
from .foundations import *
from fasthtml.common import Div, Script, FT

# %% ../nbs/04_streaming.ipynb 6
def stream_script():
    """
    Creates the JavaScript script tag needed to connect to SSE streams.
    This script finds all elements with a 'data-claude-stream' attribute
    and connects them to the specified SSE endpoint.
    
    Returns:
        Script: A Script component that can be added to headers
    """
    return Script("""
    document.addEventListener("DOMContentLoaded", () => {
        document.querySelectorAll('[data-stream-url]').forEach(el => {
            const streamUrl = el.getAttribute('data-stream-url');
            const evtSource = new EventSource(streamUrl);

            evtSource.addEventListener("message", (event) => {
                el.innerHTML += event.data;
            });

            evtSource.addEventListener("done", () => {
                console.log('SSE connection gracefully closed.');
                evtSource.close();
            });

            evtSource.onerror = (e) => {
                console.error('SSE connection error:', e);
                evtSource.close();
            };
        });
    });
    """)

# %% ../nbs/04_streaming.ipynb 8
def StreamingContainer(
    stream_url: str,           # URL endpoint that provides the SSE stream
    initial_content: str = "", # Initial content to display before streaming begins
    cls: str = "",             # Additional classes for the container
    id: str = None,            # Optional ID for the container (auto-generated if None)
    **kwargs                   # Additional arguments for the Div container
) -> FT:
    """
    Creates a container that displays streamed content from a server-sent events (SSE) endpoint.
    
    Args:
        stream_url: URL endpoint that provides the SSE stream
        initial_content: Initial content to display before streaming begins
        cls: Additional classes for the container
        id: Optional ID for the container (auto-generated if None)
        **kwargs: Additional arguments for the Div container
    
    Returns:
        FT: A Div component that will display the streamed content
    """
    if id is None:
        id = fh.unqid()
    
    return Div(
        initial_content,
        id=id,
        cls=stringify(cls),
        **{"data-stream-url": stream_url},
        **kwargs
    )
