"""Shared helpers for import/export commands."""

from __future__ import annotations

from contextlib import contextmanager
import logging
from typing import Iterator


@contextmanager
def temporary_log_level(logger_name: str, level: int) -> Iterator[None]:
    """Temporarily set a logger's level for the duration of a block."""
    logger = logging.getLogger(logger_name)
    original_level = logger.level
    logger.setLevel(level)
    try:
        yield
    finally:
        logger.setLevel(original_level)


def log_and_print_connect_error(logger: logging.Logger, error: Exception) -> None:
    """Log and print a standard Anki Connect error message."""
    logger.error("Anki Connect error: %s", error)
    print(f"✗ Error: {error}")


def log_and_print_unexpected_error(
    logger: logging.Logger,
    error: Exception,
    context: str,
) -> None:
    """Log and print a standard unexpected error message."""
    logger.error("Unexpected error during %s: %s", context, error)
    print(f"✗ Unexpected error: {error}")
