from collections.abc import Mapping from datetime import UTC, datetime from typing import Any from core.mongodb import get_database from models.example import AddonExampleCreateInput, AddonExampleDocument from motor.motor_asyncio import AsyncIOMotorCollection COLLECTION_NAME = "addon_examples" def utcnow() -> datetime: return datetime.now(UTC) async def collection() -> AsyncIOMotorCollection[dict[str, Any]]: database = await get_database() return database[COLLECTION_NAME] def deserialize(raw: Mapping[str, Any] | None) -> AddonExampleDocument | None: if raw is None: return None document = dict(raw) document.pop("_id", None) return AddonExampleDocument.model_validate(document) async def ensure_example_indexes() -> None: examples = await collection() await examples.create_index("id", unique=True, name="uq_addon_example_id") async def list_custom_examples() -> list[AddonExampleDocument]: examples = await collection() cursor = examples.find({}).sort("name", 1) result: list[AddonExampleDocument] = [] async for raw in cursor: example = deserialize(raw) if example is not None: result.append(example) return result async def create_custom_example( payload: AddonExampleCreateInput, ) -> AddonExampleDocument: now = utcnow() example = AddonExampleDocument( id=payload.id, name=payload.name, description=payload.description, category=payload.category, code=payload.code, source_url=payload.source_url, built_in=False, created_at=now, updated_at=now, ) examples = await collection() await examples.insert_one(example.model_dump(exclude_none=True)) return example async def delete_custom_example(example_id: str) -> bool: examples = await collection() result = await examples.delete_one({"id": example_id}) return result.deleted_count > 0