"""Test configuration and token storage."""

import json
from pathlib import Path
import pytest
from cryptography.fernet import Fernet
from mcpbundles.config import (
    get_or_create_key,
    save_token,
    load_token,
    save_status,
    delete_token,
    CONFIG_DIR,
    TOKEN_FILE,
    KEY_FILE,
    STATUS_FILE,
)


@pytest.fixture
def temp_config_dir(tmp_path, monkeypatch):
    """Use temporary directory for config."""
    test_dir = tmp_path / ".mcpbundles"
    monkeypatch.setattr("mcpbundles.config.CONFIG_DIR", test_dir)
    monkeypatch.setattr("mcpbundles.config.TOKEN_FILE", test_dir / "token.json")
    monkeypatch.setattr("mcpbundles.config.KEY_FILE", test_dir / ".key")
    monkeypatch.setattr("mcpbundles.config.STATUS_FILE", test_dir / "status.json")
    return test_dir


def test_get_or_create_key(temp_config_dir):
    """Test encryption key generation."""
    # First call creates key
    key1 = get_or_create_key()
    assert key1 is not None
    assert len(key1) > 0
    
    # Second call returns same key
    key2 = get_or_create_key()
    assert key1 == key2
    
    # Key file exists
    key_file = temp_config_dir / ".key"
    assert key_file.exists()


def test_save_and_load_token(temp_config_dir, monkeypatch):
    """Test token encryption and decryption."""
    monkeypatch.setattr("mcpbundles.config.CONFIG_DIR", temp_config_dir)
    monkeypatch.setattr("mcpbundles.config.TOKEN_FILE", temp_config_dir / "token.json")
    monkeypatch.setattr("mcpbundles.config.KEY_FILE", temp_config_dir / ".key")
    
    token_data = {
        "access_token": "test_access_token",
        "refresh_token": "test_refresh_token",
        "expires_at": "2024-12-31T23:59:59"
    }
    
    # Save token
    save_token(token_data)
    
    # Token file should exist
    token_file = temp_config_dir / "token.json"
    assert token_file.exists()
    
    # Load token
    loaded = load_token()
    assert loaded == token_data


def test_load_token_not_exists(temp_config_dir, monkeypatch):
    """Test loading token when file doesn't exist."""
    monkeypatch.setattr("mcpbundles.config.TOKEN_FILE", temp_config_dir / "token.json")
    
    result = load_token()
    assert result is None


def test_load_token_corrupted(temp_config_dir, monkeypatch):
    """Test loading corrupted token file."""
    monkeypatch.setattr("mcpbundles.config.CONFIG_DIR", temp_config_dir)
    monkeypatch.setattr("mcpbundles.config.TOKEN_FILE", temp_config_dir / "token.json")
    monkeypatch.setattr("mcpbundles.config.KEY_FILE", temp_config_dir / ".key")
    
    temp_config_dir.mkdir(parents=True, exist_ok=True)
    token_file = temp_config_dir / "token.json"
    token_file.write_text("corrupted data")
    
    result = load_token()
    assert result is None


def test_save_status(temp_config_dir, monkeypatch):
    """Test saving daemon status."""
    monkeypatch.setattr("mcpbundles.config.CONFIG_DIR", temp_config_dir)
    monkeypatch.setattr("mcpbundles.config.STATUS_FILE", temp_config_dir / "status.json")
    
    status_data = {
        "running": True,
        "pid": 12345,
        "started_at": "2024-01-01T00:00:00"
    }
    
    save_status(status_data)
    
    status_file = temp_config_dir / "status.json"
    assert status_file.exists()
    
    with open(status_file) as f:
        loaded = json.load(f)
    
    assert loaded == status_data


def test_delete_token(temp_config_dir, monkeypatch):
    """Test token deletion."""
    monkeypatch.setattr("mcpbundles.config.CONFIG_DIR", temp_config_dir)
    monkeypatch.setattr("mcpbundles.config.TOKEN_FILE", temp_config_dir / "token.json")
    monkeypatch.setattr("mcpbundles.config.KEY_FILE", temp_config_dir / ".key")
    
    # Create token
    save_token({"access_token": "test"})
    token_file = temp_config_dir / "token.json"
    assert token_file.exists()
    
    # Delete token
    delete_token()
    assert not token_file.exists()


def test_token_encryption_secure(temp_config_dir, monkeypatch):
    """Test that tokens are actually encrypted."""
    monkeypatch.setattr("mcpbundles.config.CONFIG_DIR", temp_config_dir)
    monkeypatch.setattr("mcpbundles.config.TOKEN_FILE", temp_config_dir / "token.json")
    monkeypatch.setattr("mcpbundles.config.KEY_FILE", temp_config_dir / ".key")
    
    token_data = {
        "access_token": "super_secret_token",
        "refresh_token": "super_secret_refresh"
    }
    
    save_token(token_data)
    
    # Read raw file contents
    token_file = temp_config_dir / "token.json"
    raw_contents = token_file.read_bytes()
    
    # Should not contain plaintext tokens
    assert b"super_secret_token" not in raw_contents
    assert b"super_secret_refresh" not in raw_contents

