"""Tests for the public config API - works with unmodified source code."""

import os
import sys
import tempfile
from pathlib import Path
import importlib

# Add src to Python path for imports
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

# Import the public API
from inceptum.config import config

# Get the actual module to access internal state for testing
config_module = importlib.import_module('inceptum.config')


def test_basic_yaml_config():
    """Test basic YAML configuration loading."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)
        
        # Setup: Create config files
        config_file = tmp_path / "config.yaml"
        config_file.write_text("extra: []\n")
        
        test_file = tmp_path / "myapp.yaml"
        test_file.write_text("name: MyApp\nversion: 1.0.0\n")
        
        # Configure environment
        os.environ["INCEPTUM"] = str(tmp_path)
        
        # Reset loader to start fresh
        config_module._loader = None
        
        # Test: Access configuration values
        assert config("myapp.name") == "MyApp"
        assert config("myapp.version") == "1.0.0"
        
        print("✅ Basic YAML config test passed")


def test_json_config():
    """Test JSON configuration loading."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)
        
        # Setup
        config_file = tmp_path / "config.yaml"
        config_file.write_text("extra: []\n")
        
        settings_file = tmp_path / "settings.json"
        settings_file.write_text('{"debug": false, "port": 8080}')
        
        # Configure environment
        os.environ["INCEPTUM"] = str(tmp_path)
        
        # Reset loader
        config_module._loader = None
        
        # Test
        assert config("settings.debug") is False
        assert config("settings.port") == 8080
        
        print("✅ JSON config test passed")


def test_nested_config_access():
    """Test accessing nested configuration values."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)
        
        # Setup
        config_file = tmp_path / "config.yaml"
        config_file.write_text("extra: []\n")
        
        db_file = tmp_path / "database.yaml"
        db_file.write_text("""
host: localhost
port: 5432
credentials:
  username: admin
  password: secret123
""")
        
        # Configure environment
        os.environ["INCEPTUM"] = str(tmp_path)
        
        # Reset loader
        config_module._loader = None
        
        # Test nested access
        assert config("database.host") == "localhost"
        assert config("database.port") == 5432
        assert config("database.credentials.username") == "admin"
        assert config("database.credentials.password") == "secret123"
        
        print("✅ Nested config access test passed")


def test_yaml_preference_over_json():
    """Test that YAML files are preferred over JSON when both exist."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)
        
        # Setup - create both YAML and JSON files
        config_file = tmp_path / "config.yaml"
        config_file.write_text("extra: []\n")
        
        app_yaml = tmp_path / "app.yaml"
        app_yaml.write_text("environment: production\n")
        
        app_json = tmp_path / "app.json"
        app_json.write_text('{"environment": "development"}')
        
        # Configure environment
        os.environ["INCEPTUM"] = str(tmp_path)
        
        # Reset loader
        config_module._loader = None
        
        # Test - should get value from YAML, not JSON
        assert config("app.environment") == "production"
        
        print("✅ YAML preference test passed")


def test_default_values():
    """Test default value handling for missing keys."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)
        
        # Setup
        config_file = tmp_path / "config.yaml"
        config_file.write_text("extra: []\n")
        
        test_file = tmp_path / "config.yaml"  # Use main config for this test
        # config_file already has "extra: []"
        
        # Configure environment
        os.environ["INCEPTUM"] = str(tmp_path)
        
        # Reset loader
        config_module._loader = None
        
        # Test with default value
        result = config("nonexistent.key", default="default_value")
        assert result == "default_value"
        
        print("✅ Default values test passed")


def test_keyerror_for_missing_keys():
    """Test the current behavior for missing keys (returns None)."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)
        
        # Setup
        config_file = tmp_path / "config.yaml"
        config_file.write_text("before: []\nafter: []\n")
        
        test_file = tmp_path / "test.yaml"
        test_file.write_text("existing_key: value\n")
        
        # Configure environment
        os.environ["INCEPTUM"] = str(tmp_path)
        
        # Reset loader
        config_module._loader = None
        
        # Test existing key works
        assert config("test.existing_key") == "value"
        
        # Test missing key returns None (current behavior)
        result = config("test.missing_key")
        assert result is None
        
        # Test with default value
        result = config("test.missing_key", default="default_value")
        assert result == "default_value"
        
        print("✅ Missing key behavior test passed")


def test_extra_directories_merging():
    """Test configuration merging from before/after directories."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)
        
        # Setup - create after directory (equivalent to old extra)
        after_dir = tmp_path / "plugins"
        after_dir.mkdir()
        
        # Main config with after directories
        config_file = tmp_path / "config.yaml"
        config_file.write_text(f"before: []\nafter: ['{after_dir}']\n")
        
        # Base configuration
        base_config = tmp_path / "service.yaml"
        base_config.write_text("port: 8080\ntimeout: 30\n")
        
        # After configuration (should override)
        after_config = after_dir / "service.yaml"
        after_config.write_text("port: 9090\nssl: true\n")
        
        # Configure environment
        os.environ["INCEPTUM"] = str(tmp_path)
        
        # Reset loader
        config_module._loader = None
        
        # Test merging behavior
        assert config("service.port") == 9090  # Overridden by after
        assert config("service.timeout") == 30  # From base
        assert config("service.ssl") is True  # Only in after
        
        print("✅ Before/after directories merging test passed")


if __name__ == "__main__":
    test_basic_yaml_config()
    test_json_config()
    test_nested_config_access()
    test_yaml_preference_over_json()
    test_default_values()
    test_keyerror_for_missing_keys()
    test_extra_directories_merging()
    print("\n🎉 All config tests passed!")
