"""
Event Type Enumeration for U-ITE
=================================
Defines all possible event types that can be generated by the system.
Each event type corresponds to a specific network condition or state change.

The enum ensures type safety and provides a single source of truth for
all valid event types. The validation function helps catch invalid event
types early in the event creation pipeline.

Event categories (implied):
- Connectivity issues: INTERNET_DOWN, ROUTER_UNREACHABLE, DNS_FAILURE
- Performance issues: HIGH_LATENCY, PACKET_LOSS_SPIKE
- Network changes: NETWORK_SWITCH, NETWORK_STATUS_CHANGE
- Service issues: WEBSITE_UNREACHABLE
- Recovery: NETWORK_RESTORED
"""

from enum import Enum


class EventType(str, Enum):
    """
    Network event types.
    
    These enums represent all possible events that can be detected by U-ITE.
    Each event type has a corresponding definition in the EventFactory that
    provides metadata like category, severity, and summary.
    
    Values:
        INTERNET_DOWN: Complete loss of internet connectivity
        HIGH_LATENCY: Latency exceeds threshold
        PACKET_LOSS_SPIKE: Sudden increase in packet loss
        NETWORK_SWITCH: Device changed to a different network
        ROUTER_UNREACHABLE: Cannot ping the default gateway
        WEBSITE_UNREACHABLE: Specific website is inaccessible
        DNS_FAILURE: DNS resolution is failing
        NETWORK_RESTORED: Internet connectivity restored after outage
        NETWORK_STATUS_CHANGE: General status change (degraded/recovered)
    
    Usage:
        >>> from uite.tracking.event_types import EventType
        >>> event_type = EventType.INTERNET_DOWN
        >>> print(event_type.value)
        'INTERNET_DOWN'
        
        >>> if event_type == EventType.INTERNET_DOWN:
        ...     print("Critical connectivity issue")
    """
    # Connectivity Issues
    INTERNET_DOWN = "INTERNET_DOWN"
    ROUTER_UNREACHABLE = "ROUTER_UNREACHABLE"
    DNS_FAILURE = "DNS_FAILURE"
    
    # Performance Issues
    HIGH_LATENCY = "HIGH_LATENCY"
    PACKET_LOSS_SPIKE = "PACKET_LOSS_SPIKE"
    
    # Service Issues
    WEBSITE_UNREACHABLE = "WEBSITE_UNREACHABLE"
    
    # Network Changes
    NETWORK_SWITCH = "NETWORK_SWITCH"
    NETWORK_STATUS_CHANGE = "NETWORK_STATUS_CHANGE"
    
    # Recovery
    NETWORK_RESTORED = "NETWORK_RESTORED"


def is_valid_event_type(value) -> bool:
    """
    Validate if a given value is a valid EventType.
    
    This function checks whether the input can be converted to an EventType
    enum member. It handles both enum instances and strings, making it useful
    for input validation throughout the system.
    
    Args:
        value: Value to check (can be EventType enum or string)
    
    Returns:
        bool: True if value is a valid EventType, False otherwise
    
    Examples:
        >>> is_valid_event_type("INTERNET_DOWN")
        True
        >>> is_valid_event_type("INVALID_TYPE")
        False
        >>> is_valid_event_type(EventType.HIGH_LATENCY)
        True
        >>> is_valid_event_type("internet_down")  # Case-sensitive
        False
    """
    try:
        EventType(value)
        return True
    except ValueError:
        return False


# ============================================================================
# Additional utility functions
# ============================================================================

def get_all_event_types() -> list[str]:
    """
    Get a list of all event type values.
    
    Returns:
        list[str]: All event type strings
        
    Example:
        >>> types = get_all_event_types()
        >>> print(types)
        ['INTERNET_DOWN', 'HIGH_LATENCY', 'PACKET_LOSS_SPIKE', ...]
    """
    return [e.value for e in EventType]


def get_event_type_descriptions() -> dict[str, str]:
    """
    Get human-readable descriptions for each event type.
    
    Returns:
        dict: Mapping of event type to description
        
    Example:
        >>> desc = get_event_type_descriptions()
        >>> print(desc['INTERNET_DOWN'])
        'Complete loss of internet connectivity'
    """
    return {
        "INTERNET_DOWN": "Complete loss of internet connectivity",
        "HIGH_LATENCY": "Network latency exceeds acceptable threshold",
        "PACKET_LOSS_SPIKE": "Sudden increase in packet loss percentage",
        "NETWORK_SWITCH": "Device switched to a different network",
        "ROUTER_UNREACHABLE": "Cannot ping or reach the default gateway",
        "WEBSITE_UNREACHABLE": "Specific website or service is inaccessible",
        "DNS_FAILURE": "DNS resolution is failing for domain names",
        "NETWORK_RESTORED": "Internet connectivity restored after outage",
        "NETWORK_STATUS_CHANGE": "General network status change (degraded/recovered)",
    }


def get_events_by_category(category: str) -> list[EventType]:
    """
    Get all event types belonging to a specific category.
    
    Args:
        category: Category name ('connectivity', 'performance', 'service', 
                 'network', 'recovery')
    
    Returns:
        list[EventType]: Event types in that category
        
    Example:
        >>> connectivity_events = get_events_by_category('connectivity')
        >>> print([e.value for e in connectivity_events])
        ['INTERNET_DOWN', 'ROUTER_UNREACHABLE', 'DNS_FAILURE']
    """
    categories = {
        'connectivity': [
            EventType.INTERNET_DOWN,
            EventType.ROUTER_UNREACHABLE,
            EventType.DNS_FAILURE,
        ],
        'performance': [
            EventType.HIGH_LATENCY,
            EventType.PACKET_LOSS_SPIKE,
        ],
        'service': [
            EventType.WEBSITE_UNREACHABLE,
        ],
        'network': [
            EventType.NETWORK_SWITCH,
            EventType.NETWORK_STATUS_CHANGE,
        ],
        'recovery': [
            EventType.NETWORK_RESTORED,
        ],
    }
    
    return categories.get(category.lower(), [])


def is_critical_event(event_type: EventType) -> bool:
    """
    Check if an event type is considered critical.
    
    Critical events typically require immediate attention:
    - Complete connectivity loss
    - Router unreachable
    - Severe performance issues
    
    Args:
        event_type: Event type to check
        
    Returns:
        bool: True if event is critical
        
    Example:
        >>> if is_critical_event(EventType.INTERNET_DOWN):
        ...     send_urgent_alert()
    """
    critical_types = [
        EventType.INTERNET_DOWN,
        EventType.ROUTER_UNREACHABLE,
    ]
    return event_type in critical_types


# Export public interface
__all__ = [
    'EventType',
    'is_valid_event_type',
    'get_all_event_types',
    'get_event_type_descriptions',
    'get_events_by_category',
    'is_critical_event'
]
