import os
import json
from typing import Optional
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

class TCGPlayerCredentials:
    _instance = None
    _credentials_file = Path.home() / ".tcgplayer" / "credentials.json"
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(TCGPlayerCredentials, cls).__new__(cls)
            cls._instance._initialize()
        return cls._instance
    
    def _initialize(self):
        """Initialize the credentials manager"""
        self._cookie = None
        self._load_credentials()
    
    def _load_credentials(self):
        """Load credentials from the credentials file"""
        try:
            if self._credentials_file.exists():
                with open(self._credentials_file, 'r') as f:
                    data = json.load(f)
                    self._cookie = data.get('cookie')
        except Exception as e:
            logger.error(f"Error loading TCGPlayer credentials: {str(e)}")
    
    def _save_credentials(self):
        """Save credentials to the credentials file"""
        try:
            # Create directory if it doesn't exist
            self._credentials_file.parent.mkdir(parents=True, exist_ok=True)
            
            with open(self._credentials_file, 'w') as f:
                json.dump({'cookie': self._cookie}, f)
            
            # Set appropriate file permissions
            self._credentials_file.chmod(0o600)
        except Exception as e:
            logger.error(f"Error saving TCGPlayer credentials: {str(e)}")
    
    def set_cookie(self, cookie: str):
        """Set the authentication cookie"""
        self._cookie = cookie
        self._save_credentials()
    
    def get_cookie(self) -> Optional[str]:
        """Get the authentication cookie"""
        return self._cookie
    
    def clear_credentials(self):
        """Clear stored credentials"""
        self._cookie = None
        if self._credentials_file.exists():
            self._credentials_file.unlink() 