"""
Merge Streams - Processes two async streams sequentially
"""
import asyncio
from typing import AsyncGenerator, Any


async def merge_streams(
    app_stream_response: AsyncGenerator[Any, None],
    ads4gpts_stream_response: AsyncGenerator[Any, None],
    is_interrupted: bool = False
) -> AsyncGenerator[Any, None]:
    """
    Merge two streams - processes first stream, then second stream.
    
    This function collects the ads4gpts stream in the background while
    processing the app stream first. After the app stream completes,
    it yields all collected ads4gpts stream chunks.
    
    Args:
        app_stream_response: The primary application stream to process first
        ads4gpts_stream_response: The ads4gpts stream to collect and process second
        is_interrupted: If True, skips processing the app stream
        
    Yields:
        Chunks from app_stream_response first, then ads4gpts_stream_response
        
    Example:
```python
        async def app_stream():
            for i in range(3):
                yield f"app_{i}"
                
        async def ads_stream():
            for i in range(3):
                yield f"ads_{i}"
                
        async for chunk in merge_streams(app_stream(), ads_stream()):
            print(chunk)
        # Output: app_0, app_1, app_2, ads_0, ads_1, ads_2
```
    """
    # Collect ads4gpts stream into array
    ads4gpts_stream: list[Any] = []
    
    async def collect_ads4gpts_stream():
        """Collect the ads4gpts stream chunks into array"""
        async for chunk in ads4gpts_stream_response:
            ads4gpts_stream.append(chunk)
    
    # Start collecting ads4gpts stream in background
    ads4gpts_task = asyncio.create_task(collect_ads4gpts_stream())
    
    # Process the App stream response first (if not interrupted)
    if not is_interrupted:
        async for chunk in app_stream_response:
            yield chunk
    
    # Wait for ads4gpts stream collection to complete
    await ads4gpts_task
    
    # Process the ads4gpts stream
    for chunk in ads4gpts_stream:
        yield chunk
