"""
Auth Storage
Manages ~/.promptbridge/auth.json file
"""

import json
import os
from pathlib import Path
from typing import Optional, Dict, Any
from datetime import datetime


class AuthStorage:
    """Authentication information storage"""

    def __init__(self):
        self.config_dir = Path.home() / ".promptbridge"
        self.auth_file = self.config_dir / "auth.json"

    def _ensure_dir(self):
        """Create directory"""
        self.config_dir.mkdir(parents=True, exist_ok=True)

    def save(self, data: Dict[str, Any]):
        """Save authentication info"""
        self._ensure_dir()

        # Add save timestamp
        data["saved_at"] = datetime.utcnow().isoformat()

        with open(self.auth_file, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

        # Restrict file permissions (owner read/write only)
        os.chmod(self.auth_file, 0o600)

    def load(self) -> Optional[Dict[str, Any]]:
        """Load authentication info"""
        if not self.auth_file.exists():
            return None

        try:
            with open(self.auth_file, "r", encoding="utf-8") as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return None

    def get_token(self) -> Optional[str]:
        """Return JWT token"""
        data = self.load()
        if not data:
            return None
        return data.get("access_token")

    def get_user(self) -> Optional[Dict[str, Any]]:
        """Return user info"""
        data = self.load()
        if not data:
            return None
        return data.get("user")

    def get_server_url(self) -> str:
        """Return server URL"""
        data = self.load()
        if data and data.get("server_url"):
            return data["server_url"]
        # Default
        return os.environ.get("PB_SERVER_URL", "https://promptbridge.store-art.com")

    def clear(self):
        """Delete authentication info (logout)"""
        if self.auth_file.exists():
            self.auth_file.unlink()

    def is_logged_in(self) -> bool:
        """Check login status"""
        return self.get_token() is not None
