"""OAuth credential storage."""

import json
from pathlib import Path
from typing import Any

from nanobot.config.schema import OAuthCredentials


class OAuthStore:
    """Stores OAuth credentials in a JSON file."""

    FILENAME = "oauth-credentials.json"

    def __init__(self, config_dir: Path):
        self.config_dir = config_dir
        self.file_path = config_dir / self.FILENAME

    def _load_all(self) -> dict[str, Any]:
        """Load all credentials from file."""
        if not self.file_path.exists():
            return {}

        with open(self.file_path, "r") as f:
            return json.load(f)

    def _save_all(self, data: dict[str, Any]) -> None:
        """Save all credentials to file."""
        self.config_dir.mkdir(parents=True, exist_ok=True)

        with open(self.file_path, "w") as f:
            json.dump(data, f, indent=2)

        # Secure permissions
        self.file_path.chmod(0o600)

    def save(self, provider: str, credentials: OAuthCredentials) -> None:
        """Save credentials for a provider."""
        data = self._load_all()
        data[provider] = credentials.model_dump()
        self._save_all(data)

    def load(self, provider: str) -> OAuthCredentials | None:
        """Load credentials for a provider."""
        data = self._load_all()
        if provider not in data:
            return None

        return OAuthCredentials(**data[provider])

    def delete(self, provider: str) -> bool:
        """Delete credentials for a provider."""
        data = self._load_all()
        if provider not in data:
            return False

        del data[provider]
        self._save_all(data)
        return True
