import time
from enum import Enum

import rerun as rr
from pydantic import Field

from common.message.message import Message


class LogLevel(str, Enum):
    """
    Log level.

    Example:
        ```python
        from common.message import LogLevel

        level = LogLevel.INFO
        if level == LogLevel.ERROR:
            print("Error occurred")
        ```
    """

    DEBUG = "debug"
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"


class Log(Message):
    """
    Structured log entry.

    Example:
        ```python
        from common.message import Log, LogLevel

        log = Log(
            let_us=1000000,
            level=LogLevel.INFO,
            message="Robot initialized successfully",
        )
        ```
    """

    _type = "antioch/log"
    timestamp_us: int = Field(default_factory=lambda: int(time.time_ns() // 1000), description="Wall clock timestamp in microseconds")
    let_us: int = Field(description="Logical event time in microseconds")
    level: LogLevel = Field(description="Log severity level")
    message: str | None = Field(default=None, description="Log message text")

    def to_rerun(self) -> rr.TextLog:
        """
        Convert to Rerun TextLog.

        :return: Rerun TextLog archetype.
        """

        level_map = {
            LogLevel.DEBUG: rr.TextLogLevel.DEBUG,
            LogLevel.INFO: rr.TextLogLevel.INFO,
            LogLevel.WARNING: rr.TextLogLevel.WARN,
            LogLevel.ERROR: rr.TextLogLevel.ERROR,
        }
        return rr.TextLog(
            self.message or "",
            level=level_map[self.level],
        )
