"""Secure token storage for Platform-MCP."""

import json
import logging
import os
from pathlib import Path

from .models import TokenData

logger = logging.getLogger(__name__)

DEFAULT_STORAGE_PATH = "~/.platform-mcp/tokens.json"


class TokenStorage:
    """Secure token storage with file-based persistence.

    Stores tokens at ~/.platform-mcp/tokens.json with 0o600 permissions
    (owner read/write only) for security.
    """

    def __init__(self, storage_path: str = DEFAULT_STORAGE_PATH):
        """Initialize token storage.

        Args:
            storage_path: Path to store tokens (default: ~/.platform-mcp/tokens.json)
        """
        self.path = Path(storage_path).expanduser()

    def _ensure_directory(self) -> None:
        """Ensure the storage directory exists with proper permissions."""
        self.path.parent.mkdir(parents=True, exist_ok=True)
        # Set directory permissions to 0o700 (owner only)
        os.chmod(self.path.parent, 0o700)

    def _set_file_permissions(self) -> None:
        """Set secure file permissions (0o600 - owner read/write only)."""
        if self.path.exists():
            os.chmod(self.path, 0o600)

    def save(self, tokens: TokenData) -> None:
        """Save tokens to disk securely.

        Args:
            tokens: TokenData to persist
        """
        self._ensure_directory()
        self.path.write_text(json.dumps(tokens.to_dict(), indent=2))
        self._set_file_permissions()
        logger.debug(f"Tokens saved to {self.path}")

    def load(self) -> TokenData | None:
        """Load tokens from disk.

        Returns:
            TokenData if valid tokens exist, None otherwise
        """
        if not self.path.exists():
            logger.debug("No stored tokens found")
            return None

        try:
            data = json.loads(self.path.read_text())
            tokens = TokenData.from_dict(data)
            logger.debug("Tokens loaded from storage")
            return tokens
        except (json.JSONDecodeError, KeyError, ValueError) as e:
            logger.warning(f"Failed to load tokens: {e}")
            return None

    def clear(self) -> None:
        """Remove stored tokens."""
        if self.path.exists():
            self.path.unlink()
            logger.debug("Tokens cleared")

    def exists(self) -> bool:
        """Check if tokens file exists."""
        return self.path.exists()
