"""
MongoDB store — flexible document storage, great for unstructured metadata.

Install:  pip install "clawid[mongo]"

Usage:
    store = MongoDBStore("mongodb://localhost:27017")
    store = MongoDBStore("mongodb+srv://user:pass@cluster.mongodb.net", db="myapp")
"""

import time

from .base import ClawIDStore


class MongoDBStore(ClawIDStore):

    def __init__(
        self,
        uri: str,
        db_name: str = "clawid",
        collection: str = "assets",
    ):
        try:
            from pymongo import MongoClient, ASCENDING
        except ImportError:
            raise ImportError(
                "pymongo is required for MongoDBStore.\n"
                "Install it with:  pip install 'clawid[mongo]'"
            )
        self.client = MongoClient(uri)
        self.col = self.client[db_name][collection]
        self.col.create_index("clawid", unique=True)
        self.col.create_index([("created_at", ASCENDING)])

    def save(self, clawid: str, metadata: dict) -> None:
        now = time.time()
        self.col.replace_one(
            {"clawid": clawid},
            {"clawid": clawid, "metadata": metadata, "created_at": now, "updated_at": now},
            upsert=True,
        )

    def get(self, clawid: str) -> dict | None:
        doc = self.col.find_one({"clawid": clawid}, {"_id": 0, "metadata": 1})
        return doc["metadata"] if doc else None

    def delete(self, clawid: str) -> bool:
        result = self.col.delete_one({"clawid": clawid})
        return result.deleted_count > 0

    def exists(self, clawid: str) -> bool:
        return self.col.count_documents({"clawid": clawid}, limit=1) > 0

    def close(self) -> None:
        self.client.close()
