# retoor <retoor@molodetz.nl>

from __future__ import annotations

from typing import Any

INHERIT = -1
FIELD_DEFAULT = "devii_interactions_default"
FIELD_LEGACY = "devii_interactions_enabled"


def _truthy(raw: Any, default: bool = True) -> bool:
    if raw is None:
        return default
    if isinstance(raw, bool):
        return raw
    if isinstance(raw, (int, float)):
        return raw != 0
    text = str(raw).strip().lower()
    if text in ("",):
        return default
    return text not in ("0", "false", "off", "no")


def admin_default() -> bool:
    try:
        from devplacepy.database import get_setting

        raw = get_setting(FIELD_DEFAULT, "")
        if raw == "" or raw is None:
            raw = get_setting(FIELD_LEGACY, "1")
        return _truthy(raw, True)
    except Exception:
        return True


def _coerce_user_pref(raw: Any) -> int | None:
    if raw is None:
        return None
    try:
        value = int(raw)
    except (TypeError, ValueError):
        return None
    if value == INHERIT:
        return None
    if value in (0, 1):
        return value
    return None


def user_pref_raw(user: dict[str, Any] | None) -> int | None:
    if not user:
        return None
    return _coerce_user_pref(user.get("interactions_enabled"))


def effective_for_user(user: dict[str, Any] | None) -> bool:
    pref = user_pref_raw(user)
    if pref is None:
        return admin_default()
    return bool(pref)


def effective_for(owner_kind: str, owner_id: str = "") -> bool:
    if owner_kind != "user" or not owner_id:
        return admin_default()
    try:
        from devplacepy.database import get_table

        user = get_table("users").find_one(uid=owner_id)
    except Exception:
        return admin_default()
    return effective_for_user(user)


def snapshot(owner_kind: str, owner_id: str = "", user: dict[str, Any] | None = None) -> dict[str, Any]:
    default = admin_default()
    if owner_kind != "user":
        return {
            "enabled": default,
            "source": "default",
            "default": default,
            "override": None,
        }
    if user is None and owner_id:
        try:
            from devplacepy.database import get_table

            user = get_table("users").find_one(uid=owner_id)
        except Exception:
            user = None
    pref = user_pref_raw(user)
    if pref is None:
        return {
            "enabled": default,
            "source": "default",
            "default": default,
            "override": None,
        }
    return {
        "enabled": bool(pref),
        "source": "user",
        "default": default,
        "override": bool(pref),
    }


def set_user_pref(user_uid: str, enabled: bool | None) -> dict[str, Any]:
    from devplacepy.database import get_table
    from devplacepy.utils import clear_user_cache

    value = INHERIT if enabled is None else (1 if enabled else 0)
    get_table("users").update(
        {"uid": user_uid, "interactions_enabled": value},
        ["uid"],
    )
    clear_user_cache(user_uid)
    user = get_table("users").find_one(uid=user_uid) or {"uid": user_uid}
    return snapshot("user", user_uid, user)
