"""
Settings Validation Utilities
"""
from django.core.exceptions import ValidationError
try:
    import jsonschema
    JSONSCHEMA_AVAILABLE = True
except ImportError:
    JSONSCHEMA_AVAILABLE = False

from .schemas import SETTINGS_SCHEMAS, SETTINGS_KEY_SCHEMA_MAP


def validate_settings_schema(key, value, schema_name=None):
    """
    Validate settings value against JSON schema.
    
    Args:
        key: Settings key
        value: Settings value to validate
        schema_name: Optional schema name (if not provided, will look up from key)
    
    Raises:
        ValidationError: If validation fails
    """
    if not JSONSCHEMA_AVAILABLE:
        # If jsonschema is not available, skip validation
        return
    
    # Get schema name from key if not provided
    if schema_name is None:
        schema_name = SETTINGS_KEY_SCHEMA_MAP.get(key)
    
    if not schema_name:
        # No schema defined for this key - skip validation
        return
    
    schema = SETTINGS_SCHEMAS.get(schema_name)
    if not schema:
        # Schema not found - skip validation
        return
    
    try:
        jsonschema.validate(instance=value, schema=schema)
    except jsonschema.ValidationError as e:
        raise ValidationError(f"Settings validation failed for key '{key}': {e.message}")
    except jsonschema.SchemaError as e:
        # Schema error - log but don't fail validation
        pass

