from bs4 import BeautifulSoup
from integrations.tripinvest.helpers import extract_int, extract_offer_url_from_card
from integrations.tripinvest.helpers import extract_price

# =====================================================
# PARSERY LISTINGU
# =====================================================

def extract_offer_containers(soup: BeautifulSoup):
    """Zwraca listę kart ofert"""
    return soup.select("div.m-offer-row.js-offer")


def parse_offer_card(offer, base_url: str) -> dict:
    """Parsuje pojedynczą kartę oferty"""
    data = {}

    data["id"] = offer.get("data-id")
    data["url"] = extract_offer_url_from_card(offer, base_url)

    title_el = offer.select_one("a.m-offer-row-name")
    data["title"] = title_el.get_text(strip=True) if title_el else None

    loc_el = offer.select_one("div.m-offer-row-location")
    data["location"] = loc_el.get_text(strip=True) if loc_el else None

    price_el = offer.select_one("div.m-offer-row-price-value")
    if price_el:
        price_text = price_el.get_text(" ", strip=True)
        data["price_raw"] = price_text
        data["currency"] = "EUR" if "€" in price_text else None
        data["price"] = extract_price(price_text)
    else:
        data["price_raw"] = None
        data["price"] = None
        data["currency"] = None

    data["labels"] = [
        l.get_text(strip=True)
        for l in offer.select("div.m-offer-row-labels div")
    ]

    images = []

    # cover (pierwsze, najważniejsze)
    cover = offer.select_one("div.cover-bg[data-bg]")
    if cover:
        images.append(cover["data-bg"])

    # kolejne zdjęcia ze slidera
    for img in offer.select("a.m-offer-row-slider-item[data-bg]"):
        src = img["data-bg"]
        if src not in images:
            images.append(src)
        if len(images) == 3:
            break

    data["images"] = images

    # --- PARAMETRY ---
    data["area_m2"] = None
    data["plot_area_m2"] = None
    data["bedrooms"] = None
    data["bathrooms"] = None

    for li in offer.select("ul.c-features li"):
        icon = li.select_one("i")
        value = li.select_one("span.font-bold")

        if not icon or not value:
            continue

        txt = value.get_text(strip=True)
        classes = icon.get("class", [])
        tippy = li.get("data-tippy-content", "").lower()

        if "ti-home" in classes and "działki" not in tippy:
            data["area_m2"] = extract_int(txt)

        elif "ti-area" in classes or "powierzchnia działki" in tippy:
            data["plot_area_m2"] = extract_int(txt)

        elif "ti-bed" in classes:
            data["bedrooms"] = extract_int(txt)

        elif "ti-bath" in classes:
            data["bathrooms"] = extract_int(txt)

    return data

