import re
import unicodedata


def _slugify(value: str) -> str:
    normalized = unicodedata.normalize("NFKD", str(value or ""))
    ascii_text = normalized.encode("ascii", "ignore").decode("ascii").lower()
    slug = re.sub(r"[^a-z0-9]+", "-", ascii_text).strip("-")
    return slug


def _rooms_token(rooms) -> str:
    try:
        rooms_value = int(float(str(rooms).replace(",", ".").strip()))
    except (TypeError, ValueError):
        return ""

    if rooms_value <= 0:
        return ""
    if rooms_value == 1:
        return "1-pokoj"
    return f"{rooms_value}-pokoje"


def build_offer_slug(offer_id, property_type=None, offer_type=None, rooms=None, city=None) -> str:
    base = str(int(offer_id))
    parts = []

    property_slug = _slugify(property_type)
    if property_slug:
        parts.append(property_slug)

    rooms_slug = _rooms_token(rooms)
    if rooms_slug:
        parts.append(rooms_slug)

    offer_type_slug = _slugify(offer_type)
    if offer_type_slug:
        parts.append(f"na-{offer_type_slug}")

    city_slug = _slugify(city)
    if city_slug:
        parts.append(f"w-{city_slug}")

    if not parts:
        return base

    slug = f"{base}-{'-'.join(parts)}"
    if len(slug) <= 120:
        return slug

    shortened_parts = [part for part in parts if not part.startswith("w-")]
    shortened = f"{base}-{'-'.join(shortened_parts)}" if shortened_parts else base
    return shortened[:120].rstrip("-")


def build_offer_path(offer_id, property_type=None, offer_type=None, rooms=None, city=None) -> str:
    return (
        "/nieruchomosc/"
        + build_offer_slug(
            offer_id=offer_id,
            property_type=property_type,
            offer_type=offer_type,
            rooms=rooms,
            city=city,
        )
    )


def extract_offer_id_from_slug(offer_slug: str):
    match = re.match(r"^(\d+)(?:-|$)", str(offer_slug or ""))
    if not match:
        return None
    return int(match.group(1))
