"""State transition logging utilities.

Provide structured logging helpers for entity state machine transitions.
"""

from __future__ import annotations

from enum import Enum

from .config import get_logger


def log_state_transition(
    entity_type: str,
    entity_id: str,
    old_state: Enum | str | None,
    new_state: Enum | str,
    **context: str | int | float | None,
) -> None:
    """Log a state transition with structured fields.

    Emit an INFO log with entity type, ID, old state, new state, and any
    additional context. Handles enum values by extracting their `.value`.

    Args:
        entity_type: Type of entity (e.g., "meeting", "diarization_job").
        entity_id: Unique identifier for the entity.
        old_state: Previous state (None for initial creation).
        new_state: New state being transitioned to.
        **context: Additional context fields to include in log.

    Example:
        log_state_transition(
            "meeting",
            str(meeting_id),
            old_state=MeetingState.RECORDING,
            new_state=MeetingState.STOPPED,
            workspace_id=str(workspace_id),
        )

        log_state_transition(
            "diarization_job",
            str(job_id),
            old_state=None,  # Initial creation
            new_state=JobStatus.PENDING,
        )
    """
    logger = get_logger()

    # Extract enum values if applicable
    old_value: str | None
    if old_state is None:
        old_value = None
    elif isinstance(old_state, Enum):
        old_value = str(old_state.value)
    else:
        old_value = str(old_state)

    new_value = str(new_state.value) if isinstance(new_state, Enum) else str(new_state)

    # Filter out None values from context
    ctx = {k: v for k, v in context.items() if v is not None}

    logger.info(
        f"{entity_type}_state_transition",
        entity_type=entity_type,
        entity_id=entity_id,
        old_state=old_value,
        new_state=new_value,
        **ctx,
    )
