# standard
import uuid
from dataclasses import dataclass, field
from typing import Optional

# third party
# custom


def _uuid() -> str:
    return str(uuid.uuid4())


@dataclass
class LogEntry:
    timestamp: str
    caller: str
    workspace: str
    module: str
    operation: str
    ok: bool = True
    item_id: Optional[str] = None
    item_title: Optional[str] = None
    args: Optional[dict] = None
    id: str = field(default_factory=_uuid)

    def to_dict(self) -> dict:
        d: dict = {
            "id": self.id,
            "timestamp": self.timestamp,
            "caller": self.caller,
            "workspace": self.workspace,
            "module": self.module,
            "operation": self.operation,
            "ok": self.ok,
        }
        if self.item_id is not None:
            d["item_id"] = self.item_id
        if self.item_title is not None:
            d["item_title"] = self.item_title
        if self.args:
            d["args"] = self.args
        return d

    def matches(self, query: str) -> bool:
        """Case-insensitive substring match across searchable fields."""
        q = query.lower()
        return any(
            q in (f or "").lower()
            for f in [
                self.id,
                self.item_title,
                self.item_id,
                self.module,
                self.operation,
                self.caller,
                self.workspace,
            ]
        )

    @classmethod
    def from_dict(cls, d: dict) -> "LogEntry":
        return cls(
            timestamp=d.get("timestamp", ""),
            caller=d.get("caller", ""),
            workspace=d.get("workspace", ""),
            module=d.get("module", ""),
            operation=d.get("operation", ""),
            ok=d.get("ok", True),
            item_id=d.get("item_id"),
            item_title=d.get("item_title"),
            args=d.get("args"),
            id=d.get("id") or _uuid(),
        )
