from typing import Dict, Any, List, Optional import uuid from datetime import datetime # In-memory store for fruits _fruits_store: List[Dict[str, Any]] = [] def validate_fruit_data(fruit_data: Dict[str, Any]) -> bool: """ Validates fruit data before creation. Args: fruit_data (Dict[str, Any]): The fruit data to validate. Returns: bool: True if data is valid, False otherwise. """ required_fields = ['name', 'color', 'shape'] if not all(field in fruit_data for field in required_fields): return False if not isinstance(fruit_data['name'], str) or len(fruit_data['name'].strip()) == 0: return False if not isinstance(fruit_data['color'], str) or len(fruit_data['color'].strip()) == 0: return False if not isinstance(fruit_data['shape'], str) or len(fruit_data['shape'].strip()) == 0: return False return True def create_fruit(fruit_data: Dict[str, Any]) -> Dict[str, Any]: """ Creates a new fruit entry in the in-memory store. Args: fruit_data (Dict[str, Any]): The fruit data containing name, color, and shape. Returns: Dict[str, Any]: The created fruit data with generated ID and timestamp. Raises: ValueError: If the fruit data is invalid. """ if not validate_fruit_data(fruit_data): raise ValueError("Invalid fruit data. Name, color, and shape are required.") new_fruit = { "id": str(uuid.uuid4()), "name": fruit_data["name"].strip(), "color": fruit_data["color"].strip(), "shape": fruit_data["shape"].strip(), "created_at": datetime.utcnow().isoformat() } _fruits_store.append(new_fruit) return new_fruit def get_all_fruits() -> List[Dict[str, Any]]: """ Retrieves all fruits from the in-memory store. Returns: List[Dict[str, Any]]: List of all stored fruits. """ return _fruits_store def get_fruit_by_name(name: str) -> Optional[Dict[str, Any]]: """ Retrieves a fruit by its name. Args: name (str): The name of the fruit to find. Returns: Optional[Dict[str, Any]]: The fruit if found, None otherwise. """ name = name.strip().lower() for fruit in _fruits_store: if fruit["name"].lower() == name: return fruit return None def get_fruits_by_color(color: str) -> List[Dict[str, Any]]: """ Retrieves all fruits of a specific color. Args: color (str): The color to filter by. Returns: List[Dict[str, Any]]: List of fruits matching the color. """ color = color.strip().lower() return [fruit for fruit in _fruits_store if fruit["color"].lower() == color] def get_fruits_by_shape(shape: str) -> List[Dict[str, Any]]: """ Retrieves all fruits of a specific shape. Args: shape (str): The shape to filter by. Returns: List[Dict[str, Any]]: List of fruits matching the shape. """ shape = shape.strip().lower() return [fruit for fruit in _fruits_store if fruit["shape"].lower() == shape]