"""Channel manager for managing multiple channels"""

import asyncio
from typing import Any, Optional, Dict, List
from .channel import Channel, ChannelOptions
from .message import Message, MessageType


class ChannelManager:
    """Manager for multiple channels"""
    
    def __init__(self):
        self._channels: Dict[str, Channel] = {}
        self._default_channel: Optional[Channel] = None
        self._running = False
    
    async def create_channel(
        self,
        name: str,
        options: Optional[ChannelOptions] = None,
        auto_start: bool = True
    ) -> Channel:
        """Create a new channel"""
        if name in self._channels:
            return self._channels[name]
        
        channel = Channel(name, options)
        self._channels[name] = channel
        
        if auto_start:
            await channel.start()
        
        return channel
    
    async def get_channel(self, name: str) -> Optional[Channel]:
        """Get channel by name"""
        channel = self._channels.get(name)
        if channel is None:
            channel = await self.create_channel(name)
        return channel
    
    async def delete_channel(self, name: str) -> bool:
        """Delete a channel"""
        channel = self._channels.get(name)
        if channel:
            await channel.stop()
            del self._channels[name]
            return True
        return False
    
    async def start_all(self):
        """Start all channels"""
        self._running = True
        for channel in self._channels.values():
            await channel.start()
    
    async def stop_all(self):
        """Stop all channels"""
        self._running = False
        for channel in self._channels.values():
            await channel.stop()
    
    async def publish(self, channel_name: str, message: Message) -> bool:
        """Publish message to channel"""
        channel = self._channels.get(channel_name)
        if channel:
            return await channel.publish(message)
        return False
    
    async def send(self, channel_name: str, payload: Any, **kwargs) -> bool:
        """Send message to channel"""
        message = Message(channel=channel_name, payload=payload, **kwargs)
        return await self.publish(channel_name, message)
    
    async def broadcast(self, message: Message) -> int:
        """Broadcast message to all channels"""
        count = 0
        for channel in self._channels.values():
            if await channel.publish(message):
                count += 1
        return count
    
    def list_channels(self) -> List[str]:
        """List all channel names"""
        return list(self._channels.keys())
    
    def get_channel_info(self, name: str) -> Optional[Dict]:
        """Get channel information"""
        channel = self._channels.get(name)
        if channel:
            return {
                "name": channel.name,
                "subscriber_count": channel.subscriber_count,
                "queue_size": channel.queue_size,
                "running": channel._running
            }
        return None
    
    @property
    def channel_count(self) -> int:
        """Get number of channels"""
        return len(self._channels)


_manager: Optional[ChannelManager] = None


def get_channel_manager() -> ChannelManager:
    """Get global channel manager"""
    global _manager
    if _manager is None:
        _manager = ChannelManager()
    return _manager
