from __future__ import annotations

import os
from pathlib import Path

from relationalai.util.persistent_kv import PersistentKeyValueFile


def default_token_cache_path() -> Path:
    # Store SDK-managed DA tokens under `~/.rai/` by default.
    # Allow tests/CI to override the location via env var.
    return Path(os.environ.get("RAI_TOKEN_CACHE_FILE", os.path.expanduser("~/.rai/tokens.json")))


class TokenCacheFile(PersistentKeyValueFile):
    """Simple JSON file cache for DA tokens with owner-only POSIX permissions."""

    def __init__(self, path: Path | None = None):
        # Persist tokens with owner-only permissions on POSIX systems.
        super().__init__(path or default_token_cache_path(), file_mode=0o600, dir_mode=0o700)


def mk_key(*, namespace: str, account: str, user: str, role: str, extra: str | None = None) -> str:
    x = f"{namespace}:{account}:{user}:{role}"
    if extra:
        x += f":{extra}"
    return x


__all__ = ["TokenCacheFile", "mk_key"]

