"""
Factory functions for creating test instances of AgentVault models.
"""
import logging
import uuid
from typing import Any, Dict, Optional, List, Union
import copy # Import copy for deep copying defaults

# Import core types from the agentvault library with fallback
try:
    from agentvault.models import (
        AgentCard, AgentProvider, AgentCapabilities, AgentAuthentication, AgentSkill
    )
    # --- MODIFIED: Import specific ValidationError ---
    from pydantic_core import ValidationError
    # --- END MODIFIED ---
    _MODELS_AVAILABLE = True
except ImportError:
    logging.getLogger(__name__).warning("Core agentvault models not found. Factory will return basic dicts.")
    # Define placeholders if import fails
    class AgentCard: pass # type: ignore
    class AgentProvider: pass # type: ignore
    class AgentCapabilities: pass # type: ignore
    class AgentAuthentication: pass # type: ignore
    class AgentSkill: pass # type: ignore
    # --- MODIFIED: Define placeholder error ---
    class ValidationError(Exception): pass # type: ignore
    # --- END MODIFIED ---
    _MODELS_AVAILABLE = False


logger = logging.getLogger(__name__)

def create_test_agent_card(**overrides: Any) -> Union[AgentCard, Dict[str, Any]]:
    """
    Creates a test AgentCard instance with sensible defaults, allowing overrides.

    Args:
        **overrides: Keyword arguments to override default values. Nested dictionaries
                     (like provider, capabilities) will be deeply merged if the override
                     value is also a dictionary. Otherwise, the override replaces the
                     entire nested structure.

    Returns:
        An AgentCard Pydantic model instance if models are available, otherwise
        a dictionary representing the card data.

    Raises:
        ValidationError: If the final merged data fails Pydantic validation
                         (and core models are available).
    """
    default_card_data: Dict[str, Any] = {
        "schemaVersion": "1.0",
        "humanReadableId": f"test-org/factory-agent-{uuid.uuid4().hex[:6]}",
        "agentVersion": "0.1.0-test",
        "name": "Factory Test Agent",
        "description": "An agent generated by the test factory.",
        "url": "https://factory.example.com/a2a",
        "provider": {
            "name": "Factory Provider Inc.",
            "url": None,
            "support_contact": None,
        },
        "capabilities": {
            "a2aVersion": "1.0",
            "mcpVersion": None,
            "supportedMessageParts": ["text"],
            "teeDetails": None,
            "supportsPushNotifications": False,
        },
        "authSchemes": [
            {"scheme": "none", "description": "No authentication required."}
        ],
        "skills": [],
        "tags": ["test", "factory-generated"],
        "privacyPolicyUrl": None,
        "termsOfServiceUrl": None,
        "iconUrl": None,
        "lastUpdated": None,
    }

    # Deep merge overrides into defaults
    merged_data = copy.deepcopy(default_card_data)
    for key, value in overrides.items():
        if isinstance(value, dict) and isinstance(merged_data.get(key), dict):
            merged_data[key].update(value)
        else:
            merged_data[key] = value

    logger.debug(f"Creating test agent card with merged data: {merged_data}")

    if _MODELS_AVAILABLE:
        # --- MODIFIED: Removed broad try/except, let ValidationError propagate ---
        # Validate and return the Pydantic model
        # This will now raise ValidationError if merged_data is invalid
        return AgentCard.model_validate(merged_data)
        # --- END MODIFIED ---
    else:
        # Return the raw dictionary if models aren't available
        return merged_data

# Add other factory functions here as needed (e.g., create_test_message)
