"""Lambda validate_image function module.""" from typing import Any from common.connectors import s3 from common.schemas.s3_event import S3Event from common.schemas.s3_reference import S3Reference from pydantic import ValidationError from src.errors.invalid_image_error import InvalidImageError from src.logic import image_metadata as image_metadata_logic from src.schemas.image_validation_result import ImageValidationResult def handle(s3_reference: S3Reference) -> ImageValidationResult: """ The main handler function, executed by local dev as well as by Lambda function running inside Docker. Args: s3_reference: S3Reference an object containing information about the key and bucket of the s3 asset Returns: ImageValidatinoResult: An ImageValidationResult object containing the validation result of the image file. """ try: result = image_metadata_logic.get_image_metadata(s3_reference) if result: return ImageValidationResult.model_validate( {"is_valid": True, "metadata": result.model_dump()} ) return ImageValidationResult.model_validate({"is_valid": False}) except InvalidImageError as invalidImageError: return ImageValidationResult.model_validate( {"is_valid": False, "errors": invalidImageError.errors} ) except ValidationError: return ImageValidationResult.model_validate( {"is_valid": False, "status": "INVALID_EVENT"} ) def handler(event: dict[str, Any], context: Any) -> dict[str, Any]: """ Lambda entry point. Args: event: Lambda event payload (should look like event.shadow.json) context: Lambda context. Raises: ValidationError: If the event JSON does not conform to the S3Event schema. """ try: s3_reference: S3Reference = S3Event(**event).to_reference() if not s3.object_exists(s3_reference): return ImageValidationResult.model_validate( {"is_valid": False, "status": "NOT_FOUND"} ).model_dump() return handle(s3_reference).model_dump() except ValidationError: return ImageValidationResult.model_validate( {"is_valid": False, "status": "INVALID_EVENT"} ).model_dump()