"""Read-only credential backend for platform-managed encrypted OAuth tokens."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Optional

from g_gremlin.autopilot.token_store import TokenStore
from g_gremlin.credentials.models import SecretSource, SecretValue
from g_gremlin.paths import resolve_gremlin_home

_METADATA_KEYS = {"stored_at", "refreshed_at", "expires_at", "_schema_version", "expires_in"}


class PlatformStoreBackend:
    """Read tokens from the platform token store (`{state_dir}/tokens/*.enc`)."""

    def __init__(self, state_dir: Path | None = None) -> None:
        if state_dir is None:
            state_dir = _resolve_state_dir_from_env()
        self.state_dir = Path(state_dir).resolve()
        self._store: TokenStore | None = None
        self._available = True
        try:
            self._store = TokenStore(self.state_dir)
        except Exception:
            self._available = False

    @property
    def source(self) -> SecretSource:
        return SecretSource.PLATFORM

    @property
    def is_available(self) -> bool:
        return self._available and self._store is not None

    @property
    def is_read_only(self) -> bool:
        return True

    def get_secret(
        self,
        integration: str,
        key: str,
        profile: str = "default",
    ) -> Optional[SecretValue]:
        if not self.is_available or self._store is None:
            return None
        payload = self._store.load_tokens(integration)
        if not payload:
            return None
        value = payload.get(key)
        if value is None:
            return None
        text_value = str(value).strip() if isinstance(value, str) else str(value)
        if text_value == "":
            return None
        return SecretValue(
            value=text_value,
            source=SecretSource.PLATFORM,
            integration=integration,
            key=key,
            profile=profile,
            metadata={"state_dir": str(self.state_dir)},
        )

    def set_secret(
        self,
        integration: str,
        key: str,
        value: str,
        profile: str = "default",
    ) -> None:
        raise NotImplementedError(
            "Platform store backend is read-only. OAuth tokens are managed by autopilot server endpoints."
        )

    def delete_secret(
        self,
        integration: str,
        key: str,
        profile: str = "default",
    ) -> bool:
        return False

    def list_secrets(
        self,
        integration: str | None = None,
        profile: str = "default",
    ) -> list[tuple[str, str]]:
        if not self.is_available or self._store is None:
            return []
        integrations = [integration] if integration else self._store.list_integrations()
        found: list[tuple[str, str]] = []
        for name in integrations:
            if not name:
                continue
            payload = self._store.load_tokens(name)
            if not payload:
                continue
            for key in payload.keys():
                if key in _METADATA_KEYS:
                    continue
                if payload.get(key) not in (None, ""):
                    found.append((name, key))
        return found


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


__all__ = ["PlatformStoreBackend"]
