"""
Comprehensive unit tests for the enhanced configuration system with Pydantic validation.
"""

import pytest

pytestmark = pytest.mark.config
import tempfile
import yaml
import shutil
from pathlib import Path
from unittest.mock import patch, mock_open
from typing import Dict, Any
from pydantic_core._pydantic_core import ValidationError

# Import the enhanced config system
from siege_utilities.config.enhanced_config import (
    UserProfile, ClientProfile, SiegeConfig,
    load_user_profile, save_user_profile,
    load_client_profile, save_client_profile,
    list_client_profiles, get_download_directory,
    export_config_yaml, import_config_yaml
)
from siege_utilities.config.models.client_profile import ContactInfo # Added import
from siege_utilities.config.models.branding_config import BrandingConfig # Added import
from siege_utilities.config.models.report_preferences import ReportPreferences # Added import


class TestUserProfile:
    """Test UserProfile Pydantic model."""
    
    def test_user_profile_defaults(self):
        """Test UserProfile with default values."""
        profile = UserProfile()
        
        assert profile.username == ""
        assert profile.email == ""
        assert profile.full_name == ""
        assert profile.preferred_download_directory == Path.home() / "Downloads" / "siege_utilities"
        assert profile.default_output_format == "pptx"
        assert profile.default_dpi == 300
        assert profile.enable_logging is True
        assert profile.log_level == "INFO"
    
    def test_user_profile_validation(self):
        """Test UserProfile field validation."""
        # Test valid values
        profile = UserProfile(
            username="testuser",
            email="test@example.com",
            default_output_format="pptx",
            default_dpi=150,
            log_level="DEBUG"
        )
        
        assert profile.username == "testuser"
        assert profile.email == "test@example.com"
        assert profile.default_output_format == "pptx"
        assert profile.default_dpi == 150
        assert profile.log_level == "DEBUG"
    
    def test_user_profile_invalid_values(self):
        """Test UserProfile validation with invalid values."""
        # Test invalid output format
        with pytest.raises(ValueError, match="String should match pattern"):
            UserProfile(default_output_format="invalid")
        
        # Test invalid DPI
        with pytest.raises(ValueError, match="Input should be greater than or equal to 72"):
            UserProfile(default_dpi=50)
        
        with pytest.raises(ValueError, match="Input should be less than or equal to 600"):
            UserProfile(default_dpi=800)
        
        # Test invalid log level
        with pytest.raises(ValueError, match="String should match pattern"):
            UserProfile(log_level="INVALID")
    
    def test_user_profile_path_validation(self):
        """Test UserProfile Path object validation."""
        profile = UserProfile(preferred_download_directory="/tmp/test")
        
        assert isinstance(profile.preferred_download_directory, Path)
        assert str(profile.preferred_download_directory) == "/tmp/test"


class TestClientProfile:
    """Test ClientProfile Pydantic model."""
    
    def test_client_profile_required_fields(self):
        """Test ClientProfile with required fields."""
        profile = ClientProfile(
            client_id="test-client",
            client_name="Test Client",
            client_code="TCLI",  # Changed from "TEST" (reserved)
            contact_info=ContactInfo(email="test@example.com", phone="1234567890"),
            industry="Testing",
            project_count=0,
            status="active",
            branding_config=BrandingConfig(
                primary_color="#1f77b4",
                secondary_color="#ff7f0e",
                accent_color="#2ca02c",
                text_color="#000000",
                background_color="#ffffff",
                primary_font="Arial",
                secondary_font="Helvetica"
            ),
            report_preferences=ReportPreferences() # Use default ReportPreferences
        )
        
        assert profile.client_name == "Test Client"
        assert profile.client_code == "TCLI"
        assert profile.contact_info.email == "test@example.com"
        assert profile.industry == "Testing"
        assert profile.project_count == 0
        assert profile.status == "active"
    
    def test_client_profile_full(self):
        """Test ClientProfile with all fields."""
        profile = ClientProfile(
            client_name="Acme Corp",
            client_code="ACME",
            client_id="acme-001",
            industry="Technology",
            project_count=10,
            status="active",
            contact_info=ContactInfo(email="contact@acme.com", phone="1234567890"), # Valid 10-digit phone
            branding_config=BrandingConfig(
                primary_color="#FF0000",
                secondary_color="#ff7f0e",
                accent_color="#2ca02c",
                text_color="#000000",
                background_color="#ffffff",
                primary_font="Arial",
                secondary_font="Helvetica"
            ), # Example, using default with one field
            report_preferences=ReportPreferences(default_format="pptx") # Example, using default with one field
        )
        
        assert profile.client_name == "Acme Corp"
        assert profile.client_code == "ACME"
        assert profile.client_id == "acme-001"
        assert profile.industry == "Technology"
        assert profile.project_count == 10
        assert profile.status == "active"
        assert profile.contact_info.email == "contact@acme.com"
        assert profile.contact_info.phone == "1234567890"
        assert profile.branding_config.primary_color == "#FF0000"
        assert profile.report_preferences.default_format == "pptx"
    
    def test_client_profile_validation(self):
        """Test ClientProfile field validation."""
        # Test valid base profile to use in invalid cases
        base_profile_args = {
            "client_id": "valid-id",
            "client_name": "Valid Client",
            "client_code": "VALCL",
            "contact_info": ContactInfo(email="valid@example.com", phone="1234567890"),
            "industry": "Tech",
            "project_count": 1,
            "status": "active",
            "branding_config": BrandingConfig(
                primary_color="#1f77b4",
                secondary_color="#ff7f0e",
                accent_color="#2ca02c",
                text_color="#000000",
                background_color="#ffffff",
                primary_font="Arial",
                secondary_font="Helvetica"
            ),
            "report_preferences": ReportPreferences()
        }

        # Test invalid status
        invalid_status_args = base_profile_args.copy()
        del invalid_status_args["status"]
        with pytest.raises(ValidationError, match="String should match pattern '\\^\\(active\\|inactive\\|archived\\)\\$'"):
            ClientProfile(**invalid_status_args, status="invalid")

        # Test negative project count
        invalid_project_count_args = base_profile_args.copy()
        del invalid_project_count_args["project_count"]
        with pytest.raises(ValidationError, match="Input should be greater than or equal to 0"):
            ClientProfile(**invalid_project_count_args, project_count=-1)

        # Test reserved client code
        invalid_client_code_args = base_profile_args.copy()
        del invalid_client_code_args["client_code"]
        with pytest.raises(ValidationError, match="Client code TEST is reserved"):
            ClientProfile(**invalid_client_code_args, client_code="TEST")
    
    def test_client_profile_path_validation(self):
        """Test ClientProfile Path object validation."""
        # For Pydantic v2, download_directory is no longer a field on ClientProfile
        # The test itself needs to be updated to reflect that such a field does not exist.
        # Since the `extra="forbid"` is set, passing unexpected fields will raise ValidationError.
        
        # Test that passing a non-existent field like download_directory raises an error
        base_profile_args = {
            "client_id": "valid-id-2",
            "client_name": "Valid Client 2",
            "client_code": "VCL2",
            "contact_info": ContactInfo(email="valid2@example.com", phone="1234567891"),
            "industry": "Finance",
            "project_count": 2,
            "status": "active",
            "branding_config": BrandingConfig(
                primary_color="#1f77b4",
                secondary_color="#ff7f0e",
                accent_color="#2ca02c",
                text_color="#000000",
                background_color="#ffffff",
                primary_font="Arial",
                secondary_font="Helvetica"
            ),
            "report_preferences": ReportPreferences()
        }
        with pytest.raises(ValidationError, match="Extra inputs are not permitted"):
            ClientProfile(**base_profile_args, download_directory="/tmp/client")


class TestConfigFunctions:
    """Test configuration management functions."""
    
    @pytest.fixture
    def temp_config_dir(self):
        """Create a temporary configuration directory for testing."""
        temp_dir = tempfile.mkdtemp()
        config_dir = Path(temp_dir) / "config"
        config_dir.mkdir(parents=True)
        yield config_dir
        shutil.rmtree(temp_dir)
    
    def test_load_user_profile_default(self, temp_config_dir):
        """Test loading user profile with defaults."""
        user_profile = UserProfile(username="default_test_user")
        user_dir = temp_config_dir / "users"
        user_dir.mkdir(parents=True, exist_ok=True)
        save_user_profile(user_profile, user_profile.username, user_dir) # Save a default profile

        profile = load_user_profile(user_profile.username, user_dir)
            
        assert isinstance(profile, UserProfile)
        assert profile.username == "default_test_user"
        assert profile.email == ""
        assert profile.full_name == ""
        assert profile.preferred_download_directory == Path.home() / "Downloads" / "siege_utilities"
    
    def test_save_and_load_user_profile(self, temp_config_dir):
        """Test saving and loading user profile."""
        # Create a user profile
        original_profile = UserProfile(
            username="testuser",
            email="test@example.com",
            full_name="Test User",
            preferred_download_directory="/tmp/test",
            default_output_format="pptx",
            default_dpi=150
        )
        
        # Save the profile
        user_dir = temp_config_dir / "users"
        user_dir.mkdir(parents=True, exist_ok=True)
        save_user_profile(original_profile, original_profile.username, user_dir)
        
        # Load the profile
        loaded_profile = load_user_profile(original_profile.username, user_dir)
        
        # Verify the loaded profile matches the original
        assert loaded_profile.username == "testuser"
        assert loaded_profile.email == "test@example.com"
        assert loaded_profile.full_name == "Test User"
        assert str(loaded_profile.preferred_download_directory) == "/tmp/test"
        assert loaded_profile.default_output_format == "pptx"
        assert loaded_profile.default_dpi == 150
    
    def test_save_and_load_client_profile(self, temp_config_dir):
        """Test saving and loading client profile."""
        # Create a client profile
        original_profile = ClientProfile(
            client_id="test-client-01",
            client_name="Test Client",
            client_code="TCLI01", # Not reserved
            contact_info=ContactInfo(email="client01@example.com", phone="1234567890"),
            industry="Finance",
            project_count=5,
            status="active",
            branding_config=BrandingConfig(
                primary_color="#1f77b4",
                secondary_color="#ff7f0e",
                accent_color="#2ca02c",
                text_color="#000000",
                background_color="#ffffff",
                primary_font="Arial",
                secondary_font="Helvetica"
            ),
            report_preferences=ReportPreferences()
        )
        
        # Save the profile
        client_dir = temp_config_dir / "clients"
        client_dir.mkdir(parents=True, exist_ok=True)
        save_client_profile(original_profile, client_dir)
        
        # Load the profile
        loaded_profile = load_client_profile("TCLI01", client_dir)
        
        # Verify the loaded profile matches the original
        assert loaded_profile is not None
        assert loaded_profile.client_id == "test-client-01"
        assert loaded_profile.client_name == "Test Client"
        assert loaded_profile.client_code == "TCLI01"
        assert loaded_profile.contact_info.email == "client01@example.com"
        assert loaded_profile.industry == "Finance"
        assert loaded_profile.project_count == 5
        assert loaded_profile.status == "active"
    
    def test_load_nonexistent_client_profile(self, temp_config_dir):
        """Test loading a non-existent client profile."""
        profile = load_client_profile("NONEXISTENT", temp_config_dir)
        assert profile is None
    
    def test_list_client_profiles(self, temp_config_dir):
        """Test listing client profiles."""
        # Create multiple client profiles
        client_dir = temp_config_dir / "clients"
        client_dir.mkdir(parents=True, exist_ok=True)
        clients = [
            ClientProfile(client_id="client1-id", client_name="Client 1", client_code="CLI01", contact_info=ContactInfo(email="cli1@example.com"), industry="Retail", project_count=1, status="active",                 branding_config=BrandingConfig(
                    primary_color="#1f77b4", secondary_color="#ff7f0e", accent_color="#2ca02c",
                    text_color="#000000", background_color="#ffffff", primary_font="Arial",
                    secondary_font="Helvetica"
                ), report_preferences=ReportPreferences()),
            ClientProfile(client_id="client2-id", client_name="Client 2", client_code="CLI02", contact_info=ContactInfo(email="cli2@example.com"), industry="Tech", project_count=2, status="active",                 branding_config=BrandingConfig(
                    primary_color="#1f77b4", secondary_color="#ff7f0e", accent_color="#2ca02c",
                    text_color="#000000", background_color="#ffffff", primary_font="Arial",
                    secondary_font="Helvetica"
                ), report_preferences=ReportPreferences()),
            ClientProfile(client_id="client3-id", client_name="Client 3", client_code="CLI03", contact_info=ContactInfo(email="cli3@example.com"), industry="Healthcare", project_count=3, status="active",                 branding_config=BrandingConfig(
                    primary_color="#1f77b4", secondary_color="#ff7f0e", accent_color="#2ca02c",
                    text_color="#000000", background_color="#ffffff", primary_font="Arial",
                    secondary_font="Helvetica"
                ), report_preferences=ReportPreferences())
        ]
        
        for client in clients:
            save_client_profile(client, client_dir)
        
        # List profiles
        profile_list = list_client_profiles(client_dir)
        
        assert len(profile_list) == 3
        assert "CLI01" in profile_list
        assert "CLI02" in profile_list
        assert "CLI03" in profile_list
    
    def test_get_download_directory_hierarchy(self, temp_config_dir):
        """Test download directory resolution based on existing get_download_directory function."""
        user_dir = temp_config_dir / "users"
        user_dir.mkdir(parents=True, exist_ok=True)

        # 1. Test when user profile has a preferred_download_directory
        user_profile_with_pref = UserProfile(
            username="user_with_pref",
            preferred_download_directory="/tmp/user/preferred"
        )
        save_user_profile(user_profile_with_pref, "user_with_pref", user_dir)

        download_dir = get_download_directory(username="user_with_pref", config_dir=user_dir)
        assert str(download_dir) == "/tmp/user/preferred"

        # 2. Test when user profile does NOT have a preferred_download_directory (fallback to default)
        user_profile_no_pref = UserProfile(username="user_no_pref")
        save_user_profile(user_profile_no_pref, "user_no_pref", user_dir)

        download_dir_no_pref = get_download_directory(username="user_no_pref", config_dir=user_dir)
        assert download_dir_no_pref == Path.home() / "Downloads" / "siege_utilities"

        # 3. Test for non-existent user (should fall back to default)
        download_dir_non_existent = get_download_directory(username="non_existent_user", config_dir=user_dir)
        assert download_dir_non_existent == Path.home() / "Downloads" / "siege_utilities"
    
    def test_export_config_yaml(self, temp_config_dir):
        """Test configuration export to YAML."""
        # Create user profile
        user_profile = UserProfile(
            username="testuser",
            email="test@example.com",
            preferred_download_directory="/tmp/user"
        )
        # Save user profile (to users subdirectory)
        user_dir = temp_config_dir / "users"
        user_dir.mkdir(parents=True, exist_ok=True)
        save_user_profile(user_profile, user_profile.username, user_dir)
        
        # Create client profiles (to clients subdirectory)
        client_dir = temp_config_dir / "clients"
        client_dir.mkdir(parents=True, exist_ok=True)
        clients = [
            ClientProfile(
                client_id="client1-id",
                client_name="Client 1",
                client_code="CLI01", # Not reserved
                contact_info=ContactInfo(email="cli1@example.com", phone="1234567890"),
                industry="Retail",
                project_count=1,
                status="active",
                                branding_config=BrandingConfig(
                    primary_color="#1f77b4", secondary_color="#ff7f0e", accent_color="#2ca02c",
                    text_color="#000000", background_color="#ffffff", primary_font="Arial",
                    secondary_font="Helvetica"
                ),
                report_preferences=ReportPreferences()
            ),
            ClientProfile(
                client_id="client2-id",
                client_name="Client 2",
                client_code="CLI02", # Not reserved
                contact_info=ContactInfo(email="cli2@example.com", phone="1234567891"),
                industry="Tech",
                project_count=2,
                status="active",
                                branding_config=BrandingConfig(
                    primary_color="#1f77b4", secondary_color="#ff7f0e", accent_color="#2ca02c",
                    text_color="#000000", background_color="#ffffff", primary_font="Arial",
                    secondary_font="Helvetica"
                ),
                report_preferences=ReportPreferences()
            )
        ]
        
        for client in clients:
            save_client_profile(client, client_dir)
        
        # Load the saved profiles to create the config_data dictionary
        loaded_user_profile = load_user_profile(user_profile.username, user_dir)
        
        loaded_clients = {}
        for client in clients: # Iterate over the original clients list
            loaded_clients[client.client_code] = load_client_profile(client.client_code, client_dir)

        config_data_to_export = {
            'user': loaded_user_profile.model_dump(),
            'clients': {code: profile.model_dump() for code, profile in loaded_clients.items()}
        }

        # Export configuration
        export_path = temp_config_dir / "export.yaml"
        export_config_yaml(config_data_to_export, export_path)
        
        # Verify export file exists and has content
        assert export_path.exists()
        assert export_path.stat().st_size > 0
        
        # Verify YAML content
        with open(export_path, 'r') as f:
            data = yaml.safe_load(f)
        
        assert 'user' in data
        assert 'clients' in data
        assert data['user']['username'] == "testuser"
        assert data['user']['email'] == "test@example.com"
        assert data['user']['preferred_download_directory'] == "/tmp/user"
        assert 'CLI01' in data['clients']
        assert 'CLI02' in data['clients']
        assert data['clients']['CLI01']['client_name'] == "Client 1"
        # Assert that download_directory is NOT present or is None if it was optional
        assert 'download_directory' not in data['clients']['CLI01'] or data['clients']['CLI01']['download_directory'] is None
    
    def test_import_config_yaml(self, temp_config_dir):
        """Test configuration import from YAML."""
        # Create test YAML data
        test_data = {
            'user': {
                'username': 'importuser',
                'email': 'import@example.com',
                'full_name': 'Import User', # Added required field
                'preferred_download_directory': '/tmp/import_user',
                'default_output_format': 'html',
                'default_dpi': 200,
                'enable_logging': True, # Added required field
                'log_level': 'INFO' # Added required field
            },
            'clients': {
                'IMPCLI': { # Changed client_code to be valid
                    'client_id': 'import-client-id', # Added required field
                    'client_name': 'Import Client',
                    'client_code': 'IMPCLI',
                    'contact_info': {'email': 'imp@example.com', 'phone': '1234567890'}, # Added required field
                    'industry': 'Finance', # Added required field
                    'project_count': 7, # Added required field
                    'status': 'active', # Added required field
                    'branding_config': BrandingConfig(
                        primary_color="#1f77b4", secondary_color="#ff7f0e", accent_color="#2ca02c",
                        text_color="#000000", background_color="#ffffff", primary_font="Arial",
                        secondary_font="Helvetica"
                    ).model_dump(), # Added required field, using default
                    'report_preferences': ReportPreferences().model_dump(), # Added required field, using default
                }
            }
        }
        
        # Write test YAML file
        import_path = temp_config_dir / "import.yaml"
        with open(import_path, 'w') as f:
            yaml.dump(test_data, f, default_flow_style=False)
        
        # Import configuration
        imported_config_data = import_config_yaml(import_path)
        
        assert imported_config_data is not None
        assert 'user' in imported_config_data
        assert 'clients' in imported_config_data

        user_data = imported_config_data['user']
        clients_data = imported_config_data['clients']

        # Verify user profile was imported and saved
        user_profile_imported = UserProfile(**user_data)
        user_dir = temp_config_dir / "users"
        user_dir.mkdir(parents=True, exist_ok=True)
        save_user_profile(user_profile_imported, user_profile_imported.username, user_dir)
        
        loaded_user = load_user_profile(user_profile_imported.username, user_dir)
        assert loaded_user.username == "importuser"
        assert loaded_user.email == "import@example.com"
        assert str(loaded_user.preferred_download_directory) == "/tmp/import_user"
        assert loaded_user.default_output_format == "html"
        assert loaded_user.default_dpi == 200
        
        # Verify client profiles were imported and saved
        client_dir = temp_config_dir / "clients"
        client_dir.mkdir(parents=True, exist_ok=True)
        imported_client_codes = []
        for client_code, client_data in clients_data.items():
            client_profile_imported = ClientProfile(**client_data)
            save_client_profile(client_profile_imported, client_dir)
            imported_client_codes.append(client_code)

        imported_clients = list_client_profiles(client_dir)
        assert len(imported_clients) == 1
        assert "IMPCLI" in imported_clients # Changed assertion
        
        loaded_client = load_client_profile("IMPCLI", client_dir) # Changed client code
        assert loaded_client is not None
        assert loaded_client.client_name == "Import Client"
        assert loaded_client.client_code == "IMPCLI" # Changed assertion
        assert loaded_client.industry == "Finance"
        assert loaded_client.project_count == 7


class TestConfigIntegration:
    """Integration tests for the complete config system."""
    
    @pytest.fixture
    def temp_config_dir(self):
        """Create a temporary configuration directory for testing."""
        temp_dir = tempfile.mkdtemp()
        config_dir = Path(temp_dir) / "config"
        config_dir.mkdir(parents=True)
        yield config_dir
        shutil.rmtree(temp_dir)
    
        def test_complete_config_workflow(self, temp_config_dir):
    
            """Test complete configuration workflow."""
    
            # Step 1: Create and save user profile
    
            user_profile = UserProfile(
    
                username="workflowuser",
    
                email="workflow@example.com",
    
                full_name="Workflow User",
    
                preferred_download_directory="/tmp/workflow/user"
    
            )
    
            user_dir = temp_config_dir / "users"
    
            user_dir.mkdir(parents=True, exist_ok=True)
    
            save_user_profile(user_profile, user_profile.username, user_dir)
    
            
    
            # Step 2: Create and save multiple client profiles (to clients subdirectory)
    
            client_dir = temp_config_dir / "clients"
    
            client_dir.mkdir(parents=True, exist_ok=True)
    
            clients_data = [
    
                ("Acme Corp", "ACME", "/tmp/workflow/acme", "Technology", 10),
    
                ("Beta Inc", "BETA", "/tmp/workflow/beta", "Manufacturing", 5),
    
                ("Gamma LLC", "GAMMA", None, "Finance", 3)  # No specific directory
    
            ]
    
            
    
            created_client_profiles = []
    
            for name, code, directory, industry, projects in clients_data:
    
                client = ClientProfile(
    
                    client_name=name,
    
                    client_code=code,
    
                    download_directory=directory,
    
                    industry=industry,
    
                    project_count=projects
    
                )
    
                save_client_profile(client, client_dir)
    
                created_client_profiles.append(client)
    
            
    
            # Step 3: Test download directory resolution (using simplified get_download_directory)
    
            # Note: get_download_directory only supports user-level preferred_download_directory.
    
            # It does not resolve client-specific directories or a hierarchical path.
    
            
    
            # Get user's download directory (should be /tmp/workflow/user)
    
            user_download_dir = get_download_directory(username="workflowuser", config_dir=user_dir)
    
            assert str(user_download_dir) == "/tmp/workflow/user"
    
            
    
            # Test for a client with no specific download directory (should fallback to user's)
    
            gamma_download_dir = get_download_directory(username="workflowuser", config_dir=user_dir)
    
            assert str(gamma_download_dir) == "/tmp/workflow/user"
    
    
    
            # Step 4: Export configuration
    
            export_path = temp_config_dir / "workflow_export.yaml"
    
            
    
            # Load the saved profiles to create the config_data dictionary for export
    
            loaded_user_profile_for_export = load_user_profile(user_profile.username, user_dir)
    
            loaded_clients_for_export = {}
    
            for client in created_client_profiles:
    
                loaded_clients_for_export[client.client_code] = load_client_profile(client.client_code, client_dir)
    
    
    
            config_data_to_export = {
    
                'user': loaded_user_profile_for_export.model_dump(),
    
                'clients': {code: profile.model_dump() for code, profile in loaded_clients_for_export.items()}
    
            }
    
            export_config_yaml(config_data_to_export, export_path)
    
            
    
            # Step 5: Verify export contains all data
    
            with open(export_path, 'r') as f:
    
                exported_data = yaml.safe_load(f)
    
            
    
            assert exported_data['user']['username'] == "workflowuser"
    
            assert len(exported_data['clients']) == 3
    
            assert exported_data['clients']['ACME']['industry'] == "Technology"
    
            assert exported_data['clients']['BETA']['industry'] == "Manufacturing"
    
            assert exported_data['clients']['GAMMA']['industry'] == "Finance"
    
            
    
            # Step 6: Test import into new config directory
    
            new_config_dir = temp_config_dir.parent / "new_config"
    
            new_config_dir.mkdir()
    
            
    
            imported_config_data = import_config_yaml(export_path)
    
            assert imported_config_data is not None
    
            
    
            # Save imported user profile
    
            new_user_dir = new_config_dir / "users"
    
            new_user_dir.mkdir(parents=True, exist_ok=True)
    
            imported_user_profile = UserProfile(**imported_config_data['user'])
    
            save_user_profile(imported_user_profile, imported_user_profile.username, new_user_dir)
    
            
    
            # Save imported client profiles
    
            new_client_dir = new_config_dir / "clients"
    
            new_client_dir.mkdir(parents=True, exist_ok=True)
    
            for client_code, client_data in imported_config_data['clients'].items():
    
                imported_client_profile = ClientProfile(**client_data)
    
                save_client_profile(imported_client_profile, new_client_dir)
    
            
    
            # Step 7: Verify imported data
    
            imported_user = load_user_profile("workflowuser", new_user_dir)
    
            assert imported_user.username == "workflowuser"
    
            
    
            imported_clients = list_client_profiles(new_client_dir)
    
            assert len(imported_clients) == 3
    
            assert "ACME" in imported_clients
    
            assert "BETA" in imported_clients
    
            assert "GAMMA" in imported_clients
    
            
    
            # Clean up
    
            shutil.rmtree(new_config_dir)


class TestConfigErrorHandling:
    """Test error handling in configuration system."""
    
    @pytest.fixture
    def temp_config_dir(self):
        """Create a temporary configuration directory for testing."""
        temp_dir = tempfile.mkdtemp()
        config_dir = Path(temp_dir) / "config"
        config_dir.mkdir(parents=True)
        yield config_dir
        shutil.rmtree(temp_dir)
    
    def test_invalid_yaml_handling(self, temp_config_dir):
        """Test handling of invalid YAML files."""
        # Create invalid YAML file in the expected user profile directory
        user_dir = temp_config_dir / "users"
        user_dir.mkdir(parents=True, exist_ok=True)
        invalid_file = user_dir / "invaliduser.yaml"
        with open(invalid_file, 'w') as f:
            f.write("invalid: yaml: content: [")
        
        # Should not crash, should return None from load_user_profile due to parsing error
        profile = load_user_profile("invaliduser", user_dir)
        assert profile is None
    
    def test_missing_config_directory(self, temp_config_dir):
        """Test handling of missing user profile directory (should return None)."""
        # Define the expected user directory
        user_dir = temp_config_dir / "users"
        
        # Ensure the directory does not exist
        if user_dir.exists():
            shutil.rmtree(user_dir)
        
        # Should return None if the user profile directory is missing and cannot be created (if load_user_profile attempts to find a file there)
        # load_user_profile will warn if the file is not found, and return None.
        profile = load_user_profile("testuser", user_dir)
        assert profile is None
        # Assert that the user_dir was NOT created by load_user_profile itself if file is not found
        assert not user_dir.exists()
    
    def test_permission_errors(self, temp_config_dir):
        """Test handling of permission errors."""
        user_dir = temp_config_dir / "users"
        user_dir.mkdir(parents=True, exist_ok=True)
        # Make directory read-only
        user_dir.chmod(0o444)
        
        try:
            # Should handle permission error gracefully by returning False
            result = save_user_profile(UserProfile(username="test"), "test", user_dir)
            assert result is False
        finally:
            # Restore permissions for cleanup
            user_dir.chmod(0o755)
