"""
Test configuration integration with registry system.

This module tests that configuration loading from .chunkhound.json files
integrates correctly with the registry system, ensuring embedding providers
are properly registered and available to services without producing warnings.
"""

import json
import tempfile
from pathlib import Path
from unittest.mock import patch, MagicMock
import pytest
from chunkhound.core.config.config import Config
from chunkhound.registry import configure_registry


def test_embedding_config_initializes_cleanly(clean_environment):
    """
    Test that valid embedding configuration from .chunkhound.json initializes without warnings.
    
    This test validates the integration between configuration loading and registry
    initialization, ensuring that:
    - Valid embedding configs are loaded correctly from JSON files
    - Registry initialization processes the config without emitting warnings
    - Embedding providers are properly registered and available to services
    
    This is a regression test for initialization order issues where services
    were created before embedding providers were registered.
    """
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        
        # Create .chunkhound.json with valid embedding provider config
        config_path = temp_path / ".chunkhound.json" 
        db_path = temp_path / ".chunkhound" / "test.db"
        db_path.parent.mkdir(exist_ok=True)
        
        config_data = {
            "database": {
                "path": str(db_path),
                "provider": "duckdb"
            },
            "embedding": {
                "provider": "openai", 
                "base_url": "https://test-api-endpoint/v1",
                "api_key": "test-key-for-validation",
                "model": "test-embedding-model"
            }
        }
        
        with open(config_path, "w") as f:
            json.dump(config_data, f)
        
        # Change to temp directory to simulate normal usage
        original_cwd = Path.cwd()
        try:
            import os
            os.chdir(temp_path)
            
            # Load config using ChunkHound's configuration system
            config = Config()
            
            # Verify config loaded correctly
            assert config.embedding is not None
            assert config.embedding.provider == "openai"
            assert config.embedding.api_key.get_secret_value() == "test-key-for-validation"
            assert config.embedding.base_url == "https://test-api-endpoint/v1"
            assert config.embedding.model == "test-embedding-model"
            
            # Mock the provider to avoid network calls during testing
            with patch('chunkhound.providers.embeddings.openai_provider.OpenAIEmbeddingProvider') as mock_provider_class:
                mock_provider = MagicMock()
                mock_provider_class.return_value = mock_provider
                
                # Capture registry logger to check for warnings
                with patch('chunkhound.registry.logger') as mock_logger:
                    # Configure registry - this should complete without warnings
                    configure_registry(config)
                    
                    # Check for any warning calls
                    warning_calls = [call for call in mock_logger.warning.call_args_list]
                    
                    # Look for provider-related warnings that indicate initialization issues
                    provider_warnings = [
                        call for call in warning_calls 
                        if call[0] and "No embedding provider configured" in str(call[0][0])
                    ]
                    
                    # Assert no provider warnings were emitted
                    assert len(provider_warnings) == 0, (
                        f"Valid embedding config should initialize without warnings, but got: "
                        f"{[str(call[0][0]) for call in provider_warnings]}"
                    )
                    
        finally:
            os.chdir(original_cwd)


def test_config_loading_from_json_file(clean_environment):
    """
    Test that .chunkhound.json files are properly loaded and parsed.
    
    This test validates the basic configuration loading mechanism to ensure
    JSON files are correctly processed and converted to Config objects.
    """
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        
        # Create minimal valid config
        config_path = temp_path / ".chunkhound.json"
        config_data = {
            "embedding": {
                "provider": "openai",
                "api_key": "test-key",
                "model": "text-embedding-3-small"
            }
        }
        
        with open(config_path, "w") as f:
            json.dump(config_data, f)
        
        original_cwd = Path.cwd()
        try:
            import os
            os.chdir(temp_path)
            
            # Load and verify config
            config = Config()
            
            assert config.embedding is not None
            assert config.embedding.provider == "openai"
            assert config.embedding.api_key.get_secret_value() == "test-key"
            assert config.embedding.model == "text-embedding-3-small"
            
        finally:
            os.chdir(original_cwd)