"""The `audits` collection: an append-only log of actions taken in the console.

Lets you review what was run, stopped, and which queries were changed — so the tool can be
driven from the UI with a trail, instead of from code.
"""
from datetime import datetime, timezone
from typing import Dict, List, Optional

from .db import get_store


def _now() -> datetime:
    return datetime.now(timezone.utc)


class AuditStore:
    def __init__(self, coll=None):
        self.coll = coll or get_store().coll.database["audits"]

    def record(self, action: str, detail: Optional[Dict] = None) -> None:
        try:
            self.coll.insert_one({"at": _now(), "action": action, "detail": detail or {}})
        except Exception:  # noqa: BLE001 — auditing must never break the action it records
            pass

    def list(self, limit: int = 50) -> List[Dict]:
        out = []
        for d in self.coll.find().sort("at", -1).limit(limit):
            d.pop("_id", None)
            if isinstance(d.get("at"), datetime):
                d["at"] = d["at"].isoformat()
            out.append(d)
        return out
