import re
import json
from bs4 import BeautifulSoup

def parse_property_details(
    html: str,
    url: str,
    offer_id: str | None = None,
    listing_id: int | None = None,
    images_from_listing: list | None = None
) -> dict:
    soup = BeautifulSoup(html, "html.parser")

    # =====================
    # TITLE
    # =====================
    title = None
    h1 = soup.select_one("h1, .property-title, .elementor-heading-title")
    if h1:
        title = h1.get_text(strip=True)

    # =====================
    # PRICE
    # =====================
    price_raw = None
    price_from = None
    currency = None

    price_tag = soup.select_one(".hz-ele-price .item-price")
    if price_tag:
        price_raw = price_tag.get_text(" ", strip=True)
        match = re.search(r"([\d,]+)\s*(AED)", price_raw)
        if match:
            price_from = int(match.group(1).replace(",", ""))
            currency = match.group(2)

    # =====================
    # OVERVIEW (DETAILS LIST)
    # =====================
    overview = {}
    for li in soup.select("#property-detail-wrap li"):
        key = li.select_one("strong")
        val = li.select_one("span")
        if key and val:
            overview[key.get_text(strip=True)] = val.get_text(strip=True)

    beds_raw = overview.get("Sypialnia")
    baths_raw = overview.get("Łazienka")
    property_type_raw = overview.get("Typ nieruchomości:")
    handover = overview.get("Termin oddania")
    status = overview.get("Status")

    property_type = []
    if property_type_raw:
        property_type = [t.strip() for t in property_type_raw.split(",")]

    # =====================
    # ADDRESS
    # =====================
    location = {}
    for li in soup.select("#property-address-wrap li"):
        key = li.select_one("strong")
        val = li.select_one("span")
        if key and val:
            location[key.get_text(strip=True)] = val.get_text(strip=True)

    # =====================
    # DEVELOPER + PAYMENT PLAN
    # =====================
    developer = None
    payment_plan = {}

    for li in soup.select(".additional-details-ul li, #property-detail-wrap li"):
        key = li.select_one("strong")
        val = li.select_one("span")
        if not key or not val:
            continue

        k = key.get_text(strip=True)
        v = val.get_text(strip=True)

        if "Deweloper" in k:
            developer = v
        if "Zaliczka" in k:
            payment_plan["downpayment"] = v
        if "Płatność za przekazanie" in k:
            payment_plan["handover"] = v

    # =====================
    # DESCRIPTION
    # =====================
    description = ""
    desc_container = soup.select_one("#property-description-wrap .block-content-wrap")
    if desc_container:
        description = desc_container.get_text(separator="\n\n", strip=True)

    # =====================
    # MAP JSON (LAT/LNG)
    # =====================
    lat = lng = property_id = None
    for script in soup.find_all("script"):
        if "houzezSingleOsMapElementor" in script.text:
            match = re.search(r'\{.*?\}', script.text, re.S)
            if match:
                try:
                    data = json.loads(match.group())
                    lat = float(data.get("lat"))
                    lng = float(data.get("lng"))
                    property_id = data.get("property_id")
                except Exception:
                    pass

    # =====================
    # GALLERY
    # =====================
    gallery = []
    for img in soup.select(".listing-slider img"):
        src = img.get("data-lzl-src") or img.get("src")
        if src and "base64" not in src:
            gallery.append(src)

    # fallback z listingu
    if not gallery and images_from_listing:
        gallery = images_from_listing

    gallery = list(dict.fromkeys(gallery))  # dedup

    # =====================
    # FINAL OBJECT
    # =====================
    return {
        "url": url,
        "offer_id": offer_id,
        "listing_id": listing_id,
        "property_id": property_id,

        "title": title,
        "status": status,

        "price_raw": price_raw,
        "price_from": price_from,
        "currency": currency,

        "handover": handover,
        "property_type_raw": property_type_raw,
        "property_type": property_type,

        "beds_raw": beds_raw,
        "baths_raw": baths_raw,

        "developer": developer,
        "payment_plan": payment_plan,

        "location": {
            **location,
            "lat": lat,
            "lng": lng
        },

        "description": description,
        "gallery": gallery
    }
