"""Utility functions for logging, file validation, and data normalization."""

import logging
import os
import sys
from pathlib import Path

from rich.logging import RichHandler

from gettopology.models import SubscriptionInput


def setup_logging(log_level: str = "INFO") -> None:
    """Configure logging with Rich handler.
    
    Args:
        log_level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
    """
    level = getattr(logging, log_level.upper(), logging.INFO)
    logging.basicConfig(
        level=level,
        format="%(message)s",
        datefmt="[%X]",
        handlers=[RichHandler(rich_tracebacks=True, show_path=True)],
    )
    
    # Reduce Azure SDK HTTP logging verbosity
    # Azure SDK uses 'azure' and 'azure.core' loggers for HTTP requests/responses
    # Set them to WARNING to suppress INFO-level HTTP logs
    azure_logger = logging.getLogger("azure")
    azure_logger.setLevel(logging.WARNING)
    
    azure_core_logger = logging.getLogger("azure.core")
    azure_core_logger.setLevel(logging.WARNING)
    
    # Also suppress urllib3 and requests if they're being used
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("requests").setLevel(logging.WARNING)


def validate_file_path(file_path: str) -> Path:
    """Validate that a file path exists, is a file, and is readable.
    
    Args:
        file_path: Path to the file to validate
    
    Returns:
        Path object if valid
    
    Exits:
        sys.exit(1) if file is invalid, not found, or not readable
    """
    path = Path(file_path)
    
    if not path.exists():
        logging.error(f"File not found: {file_path}")
        sys.exit(1)
    
    if not path.is_file():
        logging.error(f"Path is not a file: {file_path}")
        sys.exit(1)
    
    # Cross-platform readability check using os.access
    if not os.access(path, os.R_OK):
        logging.error(f"File is not readable: {file_path}")
        sys.exit(1)
    
    return path


def normalize_subscription_ids(sub_ids: list[str]) -> tuple[list[str], list[str]]:
    """Trim whitespace and validate subscription IDs using regex pattern.
    
    This is a convenience wrapper around SubscriptionInput.normalize_subscription_ids().
    
    Args:
        sub_ids: List of subscription ID strings to normalize and validate
    
    Returns:
        tuple: (valid_ids, invalid_ids)
    """
    return SubscriptionInput.normalize_subscription_ids(sub_ids)

