from typing import Dict, Any, List, Optional from dataclasses import dataclass from uuid import uuid4 # In-memory storage for countries _countries_store: List[Dict[str, Any]] = [] @dataclass class CountryData: name: str landmass_size: float def validate_country_data(name: str, landmass_size: float) -> bool: """ Validates the country data before creation. Args: name (str): The name of the country. landmass_size (float): The landmass size in square kilometers. Returns: bool: True if data is valid, False otherwise. """ if not name or not isinstance(name, str) or len(name.strip()) == 0: return False if not isinstance(landmass_size, (int, float)) or landmass_size <= 0: return False # Check if country name already exists for country in _countries_store: if country["name"].lower() == name.lower(): return False return True def create_country(name: str, landmass_size: float) -> Optional[Dict[str, Any]]: """ Creates a new country entry in the in-memory store. Args: name (str): The name of the country. landmass_size (float): The landmass size in square kilometers. Returns: Optional[Dict[str, Any]]: The created country data if successful, None if validation fails. """ if not validate_country_data(name, landmass_size): return None country_data = { "id": str(uuid4()), "name": name.strip(), "landmass_size": float(landmass_size) } _countries_store.append(country_data) return country_data def get_all_countries() -> List[Dict[str, Any]]: """ Retrieves all countries from the in-memory store. Returns: List[Dict[str, Any]]: A list of all stored countries. """ return _countries_store def get_country_by_name(name: str) -> Optional[Dict[str, Any]]: """ Retrieves a country by its name. Args: name (str): The name of the country to find. Returns: Optional[Dict[str, Any]]: The country data if found, None otherwise. """ name = name.lower() for country in _countries_store: if country["name"].lower() == name: return country return None def format_country_response(country: Dict[str, Any]) -> Dict[str, Any]: """ Formats the country data for API response. Args: country (Dict[str, Any]): The raw country data. Returns: Dict[str, Any]: Formatted country data. """ return { "id": country["id"], "name": country["name"], "landmass_size": country["landmass_size"], "landmass_size_formatted": f"{country['landmass_size']:,.2f} km²" }