# services/external/app/registry/geolocation_mapper.py
"""
Geolocation Mapper - Maps tenant locations to cities
"""

from typing import Optional, Tuple
import structlog
from .city_registry import CityRegistry, CityDefinition

logger = structlog.get_logger()


class GeolocationMapper:
    """Maps tenant coordinates to nearest supported city"""

    def __init__(self):
        self.registry = CityRegistry()

    def map_tenant_to_city(
        self,
        latitude: float,
        longitude: float
    ) -> Optional[Tuple[CityDefinition, float]]:
        """
        Map tenant coordinates to nearest city

        Returns:
            Tuple of (CityDefinition, distance_km) or None if no match
        """
        nearest_city = self.registry.find_nearest_city(latitude, longitude)

        if not nearest_city:
            logger.warning(
                "No supported city found for coordinates",
                lat=latitude,
                lon=longitude
            )
            return None

        distance = self.registry._haversine_distance(
            latitude, longitude,
            nearest_city.latitude, nearest_city.longitude
        )

        logger.info(
            "Mapped tenant to city",
            lat=latitude,
            lon=longitude,
            city=nearest_city.name,
            distance_km=round(distance, 2)
        )

        return (nearest_city, distance)

    def validate_location_support(self, latitude: float, longitude: float) -> bool:
        """Check if coordinates are supported"""
        result = self.map_tenant_to_city(latitude, longitude)
        return result is not None
