"""Configuration and secure token storage."""

from cryptography.fernet import Fernet
import json
from pathlib import Path

CONFIG_DIR = Path.home() / '.mcpbundles'
TOKEN_FILE = CONFIG_DIR / 'token.json'
KEY_FILE = CONFIG_DIR / '.key'
STATUS_FILE = CONFIG_DIR / 'status.json'


def get_or_create_key():
    """Get or create encryption key for token storage."""
    CONFIG_DIR.mkdir(exist_ok=True)
    if not KEY_FILE.exists():
        key = Fernet.generate_key()
        KEY_FILE.write_bytes(key)
        KEY_FILE.chmod(0o600)  # Secure file permissions
    return KEY_FILE.read_bytes()


def save_token(token_data):
    """Save token data encrypted to disk."""
    CONFIG_DIR.mkdir(exist_ok=True)
    key = get_or_create_key()
    f = Fernet(key)
    encrypted = f.encrypt(json.dumps(token_data).encode())
    TOKEN_FILE.write_bytes(encrypted)
    TOKEN_FILE.chmod(0o600)  # Secure file permissions


def load_token():
    """Load token data from disk."""
    if not TOKEN_FILE.exists():
        return None
    try:
        key = get_or_create_key()
        f = Fernet(key)
        decrypted = f.decrypt(TOKEN_FILE.read_bytes())
        return json.loads(decrypted)
    except Exception:
        # Corrupted token file
        return None


def save_status(status_data):
    """Save daemon status for status command."""
    CONFIG_DIR.mkdir(exist_ok=True)
    with open(STATUS_FILE, 'w') as f:
        json.dump(status_data, f)


def delete_token():
    """Delete stored token."""
    TOKEN_FILE.unlink(missing_ok=True)

