from __future__ import annotations

import os
from pathlib import Path
from typing import Any, Mapping

from g_gremlin.autopilot.token_store import TokenStore
from g_gremlin.paths import resolve_gremlin_home


def _resolve_state_dir() -> Path:
    raw = os.getenv("G_GREMLIN_STATE_DIR", "").strip()
    if raw:
        return Path(os.path.expanduser(os.path.expandvars(raw))).resolve()
    return (resolve_gremlin_home() / "autopilot").resolve()


class ServerSessionStore:
    """Canonical read/write access for server-managed integration sessions."""

    def __init__(self, state_dir: Path | None = None) -> None:
        self.state_dir = Path(state_dir).resolve() if state_dir else _resolve_state_dir()
        self._store = TokenStore(self.state_dir)

    def load_session(self, integration: str) -> dict[str, Any] | None:
        try:
            return self._store.load_tokens(integration)
        except Exception:
            return None

    def save_session(self, integration: str, payload: Mapping[str, Any]) -> None:
        self._store.save_tokens(integration, dict(payload))

    def delete_session(self, integration: str) -> bool:
        try:
            return self._store.delete_tokens(integration)
        except Exception:
            return False
