"""Base Event Model

Defines common fields and behaviors for all events
"""

from datetime import datetime, timezone
from typing import Any

from pydantic import BaseModel, ConfigDict, Field


class BaseEvent(BaseModel):
    """Base event class

    All specific event types inherit from this class, containing common fields:
    - event_name: Event name
    - timestamp: Event occurrence time (UTC)
    - session_id: Session ID (generated by frontend)
    - page_id: Page identifier
    - benchmark: Currently selected benchmark
    """

    event_name: str = Field(..., description="Event name")
    timestamp: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc),
        description="Event occurrence time (UTC)",
    )
    session_id: str = Field(..., description="Session ID")
    page_id: str = Field(default="leaderboard", description="Page identifier")
    benchmark: str | None = Field(default=None, description="Current benchmark")

    # Fields that allow free extension
    filters: dict[str, Any] | None = Field(
        default=None, description="Current filter conditions snapshot"
    )
    properties: dict[str, Any] | None = Field(
        default=None, description="Event additional properties"
    )

    model_config = ConfigDict(extra="allow")

    def to_mongo_dict(self) -> dict[str, Any]:
        """Convert to MongoDB document format

        Converts datetime to ISO format string for easier storage and querying
        """
        data = self.model_dump(exclude_none=True)
        # Convert datetime to ISO string
        if "timestamp" in data and isinstance(data["timestamp"], datetime):
            data["timestamp"] = data["timestamp"].isoformat()
        return data
