from decimal import ROUND_DOWN, Decimal, InvalidOperation


def normalize_coordinate(value, max_digits, decimal_places):
    """Normalize coordinate to have exactly 6 decimal places"""
    try:
        if value is None:
            return None

        # Convert to Decimal for precise handling
        value = Decimal(str(value))
        # Round to exactly 6 decimal places
        value = value.quantize(Decimal("0.000001"), rounding=ROUND_DOWN)

        return float(value)
    except (TypeError, ValueError, InvalidOperation):
        return None


def get_english_name(tags):
    """Extract English name from OSM tags, falling back to default name"""
    # Try name:en first
    if "name:en" in tags:
        return tags["name:en"]
    # Then try int_name (international name)
    if "int_name" in tags:
        return tags["int_name"]
    # Fall back to default name
    return tags.get("name")


def normalize_osm_result(result):
    """Normalize OpenStreetMap result to use English names and normalized coordinates"""
    # Normalize coordinates
    result["lat"] = normalize_coordinate(float(result["lat"]), 9, 6)
    result["lon"] = normalize_coordinate(float(result["lon"]), 10, 6)

    # Get address details
    address = result.get("address", {})

    # Normalize place names to English where possible
    if "namedetails" in result:
        # For main display name
        result["display_name"] = get_english_name(result["namedetails"])

        # For address components
        if "city" in address and "city_tags" in result:
            address["city"] = get_english_name(result["city_tags"])
        if "state" in address and "state_tags" in result:
            address["state"] = get_english_name(result["state_tags"])
        if "country" in address and "country_tags" in result:
            address["country"] = get_english_name(result["country_tags"])

    result["address"] = address
    return result
