import re


_WEIGHT_UNITS = re.compile(r"\b(kg|g(?:rams?)?|lb|lbs|ounces?|oz)\b", re.IGNORECASE)
_AREA_UNITS = re.compile(
    r"\b(sq\s*\.?\s*m(?:eters?)?|m²|m\^2|square\s*m(?:eters?)?|sqm|sq\s*m|hectares?|ha|sq\s*ft|square\s*feet)\b",
    re.IGNORECASE,
)
_LENGTH_UNITS = re.compile(
    r"\b(m(?:eters?)?|cm|km|mm|feet|ft|inches?|in|yards?|yd|miles?|mi)\b",
    re.IGNORECASE,
)


PRICE_LIKE_TAGS = frozenset({"cost", "price"})

QUANTITY_LIKE_TAGS = frozenset({
    "quantity",
    "size",
    "weight",
    "height",
    "width",
    "length",
    "depth",
    "area",
    "distance",
})

_KEYWORD_TAGS = {
    "price": "price",
    "cost": "cost",
    "quantity": "quantity",
    "size": "size",
    "weight": "weight",
    "height": "height",
    "width": "width",
    "length": "length",
    "depth": "depth",
    "area": "area",
    "distance": "distance",
}


def detect_quantity_attribute_tag(caption: str):
    if not caption or not caption.strip():
        return None
    caption_text = caption.strip().lower()
    for key, tag in _KEYWORD_TAGS.items():
        if key in caption_text:
            return tag
    if _WEIGHT_UNITS.search(caption):
        return "weight"
    if _AREA_UNITS.search(caption):
        return "area"
    if _LENGTH_UNITS.search(caption):
        return "length"
    return None


def attribute_tag_from_tag(tag: str):
    if not tag or not tag.strip():
        return None
    key = tag.strip().lower()
    return _KEYWORD_TAGS.get(key, key)
