# retoor <retoor@molodetz.nl>

from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any

logger = logging.getLogger("devii.behavior.store")

TABLE = "devii_behavior"


def _now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


class BehaviorStore:
    def __init__(self, db: Any, owner_kind: str, owner_id: str) -> None:
        self._db = db
        self._owner_kind = owner_kind
        self._owner_id = owner_id
        self._ensure_indexes()

    def _ensure_indexes(self) -> None:
        if TABLE not in self._db.tables:
            return
        self._db[TABLE].create_index(["owner_kind", "owner_id"])

    @property
    def _table(self) -> Any:
        return self._db[TABLE]

    @property
    def _scope(self) -> dict[str, str]:
        return {"owner_kind": self._owner_kind, "owner_id": self._owner_id}

    def text(self) -> str:
        if TABLE not in self._db.tables:
            return ""
        row = self._table.find_one(**self._scope)
        return (row.get("behavior") or "") if row else ""

    def set(self, behavior: str) -> None:
        self._table.upsert(
            {**self._scope, "behavior": behavior, "updated_at": _now_iso()},
            ["owner_kind", "owner_id"],
        )
        logger.info("Behavior updated owner=%s/%s", self._owner_kind, self._owner_id)
