from __future__ import annotations

import html
import logging
import math
import re
import time
from urllib.parse import urlparse

import requests
from bs4 import BeautifulSoup

from integrations.avarten.details_crawler import parse_property_details
from integrations.avarten.listing_crawler import (
    MAX_PRICE,
    MIN_PRICE,
    fetch_html,
    get_max_pages,
    parse_listings,
)
from integrations.avarten.php_serialized import PhpSerializedError, php_unserialize
from integrations.avarten.rest_client import AvartenRestClient, AvartenRestError

logger = logging.getLogger(__name__)

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
SLEEP_BETWEEN_DETAILS = 1.2


def _parse_number(value):
    if value is None:
        return None
    if isinstance(value, (int, float)):
        return value
    text = str(value).strip()
    if not text:
        return None
    cleaned = re.sub(r"[^\d,.\-]", "", text).replace(" ", "")
    if cleaned.count(",") > 0 and cleaned.count(".") > 0:
        cleaned = cleaned.replace(",", "")
    else:
        cleaned = cleaned.replace(",", ".")
    try:
        parsed = float(cleaned)
        return int(parsed) if parsed.is_integer() else parsed
    except ValueError:
        return None


def _normalize_currency(value):
    text = str(value or "").strip().upper()
    if text in {"AED"}:
        return "AED"
    if text in {"EUR", "€"}:
        return "EUR"
    if text in {"PLN", "ZL", "ZŁ"}:
        return "PLN"
    return "unknown"


def _image_urls_from_listing_images(images):
    urls = []
    for image in images or []:
        if isinstance(image, dict):
            url = image.get("image")
            if url:
                urls.append(url)
    return urls


# ---------------------------------------------------------------------------
# WordPress REST (primary structured source)
# ---------------------------------------------------------------------------

# Houzez post meta the integration reads. Requested explicitly so the REST
# payload does not carry the SEO/plugin meta WordPress attaches to every post.
REST_META_KEYS = (
    "fave_property_price",
    "fave_prop-price",
    "fave_property_bedrooms",
    "fave_bedroom",
    "fave_property_bathrooms",
    "fave_property_year",
    "fave_property_address",
    "fave_property_map_address",
    "fave_property_location",
    "houzez_geolocation_lat",
    "houzez_geolocation_long",
    "fave_developers",
    "additional_features",
    "fave_property_images",
    "fave_featured",
)
_REST_BASE_FIELDS = (
    "id", "slug", "link", "status", "title", "date_gmt", "modified", "modified_gmt",
    "featured_media", "class_list",
)
_REST_META_FIELDS = tuple(f"property_meta.{key}" for key in REST_META_KEYS)
REST_LIST_FIELDS = ",".join(_REST_BASE_FIELDS + _REST_META_FIELDS)
REST_DETAIL_FIELDS = ",".join(_REST_BASE_FIELDS + ("content",) + _REST_META_FIELDS)

# Image sizes that reproduce the URLs the HTML pages used to expose
# (listing card: 592x444, offer gallery: 1170x785).
COVER_IMAGE_SIZES = ("houzez-item-image-1", "medium_large", "large")
GALLERY_IMAGE_SIZES = ("houzez-gallery", "large")

FEATURED_LABEL = "Wyróżniony"
MARKET_LABELS_PL = {"primary": "Pierwotny", "secondary": "Wtórny"}
PROPERTY_TYPE_LABELS_PL = {
    "apartments": "Apartamenty",
    "penthouses": "Penthousy",
    "villas": "Wille",
    "townhouses": "Domy szeregowe",
    "residential": "Nieruchomości mieszkalne",
}
DEFAULT_CURRENCY = "AED"


def _clean_text(value):
    if value is None:
        return None
    text = " ".join(html.unescape(str(value)).split())
    return text or None


def _meta_first(meta, key):
    """First value of a WordPress meta entry (the API wraps them in lists)."""
    if not isinstance(meta, dict):
        return None
    value = meta.get(key)
    if isinstance(value, list):
        value = value[0] if value else None
    if isinstance(value, (dict, list)):
        return None
    text = None if value is None else str(value).strip()
    return text or None


def _meta_list(meta, key):
    if not isinstance(meta, dict):
        return []
    value = meta.get(key)
    if value is None:
        return []
    if not isinstance(value, list):
        value = [value]
    return [str(item).strip() for item in value if item is not None and str(item).strip()]


def _parse_rest_price(value):
    """Structured Houzez price such as "699000" or "660,000".

    Unlike _parse_number, a comma followed by exactly three digits is a
    thousands separator here (the site stores prices both ways).
    """
    if value is None or isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        number = float(value)
    else:
        if str(value).strip().startswith("-"):
            return None
        text = re.sub(r"[^\d,.\s]", "", str(value))
        text = re.sub(r"\s+", "", text)
        if not text:
            return None
        if re.fullmatch(r"\d{1,3}(,\d{3})+(\.\d+)?", text):
            text = text.replace(",", "")
        elif re.fullmatch(r"\d{1,3}(\.\d{3})+(,\d+)?", text):
            text = text.replace(".", "").replace(",", ".")
        elif "," in text and "." not in text:
            text = text.replace(",", ".")
        try:
            number = float(text)
        except ValueError:
            return None
    if not math.isfinite(number) or number <= 0:
        return None
    return int(number) if number.is_integer() else number


def _parse_count(value):
    """A plain non-negative integer count ("2"); anything else ("Multiple") is None."""
    if value is None:
        return None
    match = re.fullmatch(r"\s*(\d+)\s*", str(value))
    return int(match.group(1)) if match else None


def _parse_coordinate(value, limit):
    if value is None:
        return None
    try:
        number = float(str(value).strip())
    except ValueError:
        return None
    if not math.isfinite(number) or abs(number) > limit:
        return None
    return number


def _rest_coordinates(meta):
    lat = _parse_coordinate(_meta_first(meta, "houzez_geolocation_lat"), 90)
    lng = _parse_coordinate(_meta_first(meta, "houzez_geolocation_long"), 180)
    if lat is None or lng is None:
        # "lat,lng,zoom" fallback that Houzez keeps next to the split fields.
        parts = (_meta_first(meta, "fave_property_location") or "").split(",")
        if len(parts) >= 2:
            lat = _parse_coordinate(parts[0], 90)
            lng = _parse_coordinate(parts[1], 180)
    if lat is None or lng is None:
        return None, None
    return lat, lng


def _class_slugs(record, prefix):
    slugs = []
    class_list = record.get("class_list")
    for item in class_list if isinstance(class_list, list) else []:
        if isinstance(item, str) and item.startswith(prefix):
            slug = item[len(prefix):].strip()
            if slug and slug not in slugs:
                slugs.append(slug)
    return slugs


def _humanize_slug(slug):
    return " ".join(part.capitalize() for part in re.split(r"[-_]+", slug) if part)


def _rest_currency(amount, price_label):
    """(currency, source). The price label is the only place the site prints one."""
    if amount is None:
        return "unknown", "no_price"
    match = re.search(r"\b([A-Z]{3})\b", price_label or "")
    if match:
        return _normalize_currency(match.group(1)), "label"
    return DEFAULT_CURRENCY, "source_default"


def _rest_payment_plan(meta):
    raw_value = _meta_first(meta, "additional_features")
    if not raw_value:
        return []
    try:
        parsed = php_unserialize(raw_value)
    except PhpSerializedError:
        logger.warning("Avarten additional_features could not be decoded; payment plan skipped.")
        return []
    if not isinstance(parsed, dict):
        return []
    plan = []
    for entry in parsed.values():
        if not isinstance(entry, dict):
            continue
        stage = _clean_text(entry.get("fave_additional_feature_title"))
        value = _clean_text(entry.get("fave_additional_feature_value"))
        if stage and value:
            plan.append({"stage": stage, "value": value})
    return plan


def _rest_bedrooms(meta):
    """(bedrooms, beds_raw, options).

    fave_property_bedrooms is an editor-typed headline ("2", "Multiple") while
    fave_bedroom lists every offered configuration. A number is only reported
    when it is unambiguous; ranges stay in beds_raw.
    """
    options = sorted(
        {count for count in map(_parse_count, _meta_list(meta, "fave_bedroom")) if count is not None}
    )
    headline = _meta_first(meta, "fave_property_bedrooms")
    if len(options) > 1:
        return None, ", ".join(str(count) for count in options), options
    if len(options) == 1:
        return options[0], str(options[0]), options
    return _parse_count(headline), headline, options


def _iso(gmt_value, local_value):
    value = gmt_value or local_value
    if not isinstance(value, str) or not value.strip():
        return None
    value = value.strip()
    if gmt_value and not re.search(r"(Z|[+-]\d{2}:?\d{2})$", value):
        value += "Z"
    return value


def _html_to_text(content_html):
    if not content_html:
        return None
    text = BeautifulSoup(str(content_html), "html.parser").get_text("\n\n", strip=True)
    return text or None


def _pick_image_url(media_record, preferred_sizes):
    if not isinstance(media_record, dict):
        return None
    if media_record.get("media_type") not in (None, "image"):
        return None
    sizes = (media_record.get("media_details") or {}).get("sizes") or {}
    for size_name in preferred_sizes:
        candidate = (sizes.get(size_name) or {}).get("source_url")
        if candidate:
            return candidate
    return media_record.get("source_url") or None


def _rest_price_of(record):
    return _parse_rest_price(_meta_first(record.get("property_meta"), "fave_property_price"))


def _is_featured(record):
    return _meta_first(record.get("property_meta"), "fave_featured") == "1"


def _slug_from_url(url):
    if not url:
        return None
    parts = [part for part in urlparse(str(url)).path.split("/") if part]
    if "property" in parts:
        index = parts.index("property")
        if index + 1 < len(parts):
            return parts[index + 1]
    return None


def _post_id_from_identifier(identifier):
    for key in ("listing_id", "offer_id"):
        value = identifier.get(key)
        if value is None or isinstance(value, bool):
            continue
        match = re.search(r"(\d+)$", str(value).strip())
        if match and int(match.group(1)) > 0:
            return int(match.group(1))
    return None


def _gallery_media_ids(record):
    """Gallery media ids in meta order; the featured image when the gallery is empty."""
    meta = record.get("property_meta")
    gallery_ids = [count for count in map(_parse_count, _meta_list(meta, "fave_property_images")) if count]
    featured = record.get("featured_media")
    return gallery_ids or ([featured] if isinstance(featured, int) and featured > 0 else [])


class AvartenConnector:
    source_name = "avarten"

    def __init__(self, rest_client: AvartenRestClient | None = None):
        self._rest_client = rest_client

    @property
    def rest_client(self) -> AvartenRestClient:
        if self._rest_client is None:
            self._rest_client = AvartenRestClient()
        return self._rest_client

    # -- catalog -----------------------------------------------------------

    def fetch_catalog(self, filters: dict, page: int, per_page: int) -> tuple[list[dict], dict]:
        try:
            return self._fetch_catalog_rest(page, per_page)
        except AvartenRestError as exc:
            logger.warning("Avarten REST catalog failed (%s); falling back to HTML listing.", exc)
            return self._fetch_catalog_html(page, per_page)

    def _fetch_catalog_rest(self, page: int, per_page: int) -> tuple[list[dict], dict]:
        records = self.rest_client.list_properties(fields=REST_LIST_FIELDS)
        if not records:
            # A 200 with no properties at all is indistinguishable from a
            # disabled/blocked API, so it is treated as a failure, not as
            # an empty catalog.
            raise AvartenRestError("Avarten REST returned no properties.")

        # Same business range the HTML listing query applied (min/max price).
        listed = []
        for record in records:
            price = _rest_price_of(record)
            if price is not None and MIN_PRICE <= price <= MAX_PRICE:
                listed.append(record)
        # The HTML listing shows featured offers first, then newest first.
        listed.sort(key=lambda record: str(record.get("date_gmt") or ""), reverse=True)
        listed.sort(key=lambda record: not _is_featured(record))

        per_page = max(1, int(per_page))
        page = max(1, int(page))
        total_pages = max(1, math.ceil(len(listed) / per_page))
        page_records = listed[(page - 1) * per_page: page * per_page]

        covers = self._cover_urls(page_records)
        raw_items = [
            {
                "kind": "rest_offer",
                "offer": record,
                "images": [covers[record.get("id")]] if record.get("id") in covers else [],
            }
            for record in page_records
        ]
        meta = {
            "total_records": len(page_records),
            "current_page": page,
            "per_page": per_page,
            "total_pages": total_pages,
            "max_pages": total_pages,
        }
        return raw_items, meta

    def _cover_urls(self, records: list[dict]) -> dict[int, str]:
        """post id -> cover URL, resolved with one batched media request."""
        media_by_post: dict[int, int] = {}
        for record in records:
            featured = record.get("featured_media")
            post_id = record.get("id")
            if isinstance(featured, int) and featured > 0 and isinstance(post_id, int):
                media_by_post[post_id] = featured
        if not media_by_post:
            return {}
        try:
            media = self.rest_client.get_media(media_by_post.values())
        except AvartenRestError as exc:
            logger.warning("Avarten REST media lookup failed (%s); catalog covers omitted.", exc)
            return {}
        covers = {}
        for post_id, media_id in media_by_post.items():
            url = _pick_image_url(media.get(media_id), COVER_IMAGE_SIZES)
            if url:
                covers[post_id] = url
        return covers

    def fetch_full_catalog(self) -> list[dict]:
        """Every published property as a canonical offer, with description and gallery.

        For source synchronization: one REST list request (with content) plus batched
        media lookups, no per-offer requests. There is no price filter (the public
        catalog's business range does not apply) and no HTML fallback: the legacy
        pages lack the structured fields, so any REST failure raises AvartenRestError.
        """
        records = self.rest_client.list_properties(fields=REST_DETAIL_FIELDS)
        if not records:
            raise AvartenRestError("Avarten REST returned no properties.")

        wanted: list[int] = []
        for record in records:
            wanted.extend(_gallery_media_ids(record))
        media = self.rest_client.get_media(wanted) if wanted else {}

        canonical = []
        for record in records:
            urls = []
            for media_id in _gallery_media_ids(record):
                url = _pick_image_url(media.get(media_id), GALLERY_IMAGE_SIZES)
                if url and url not in urls:
                    urls.append(url)
            canonical.append(
                self.normalize_offer(
                    {
                        "kind": "rest_offer",
                        "offer": record,
                        "images": urls,
                        "images_source": "rest_media" if urls else "none",
                    }
                )
            )
        return canonical

    def _fetch_catalog_html(self, page: int, per_page: int) -> tuple[list[dict], dict]:
        page_html = fetch_html(page)
        offers = parse_listings(page_html)
        max_pages = get_max_pages(page_html)

        raw_items = [
            {"kind": "catalog_offer", "offer": {**offer, "data_source": "html"}}
            for offer in offers
        ]
        meta = {
            "total_records": len(offers),
            "current_page": page,
            "per_page": per_page,
            "total_pages": max_pages,
            "max_pages": max_pages,
        }
        return raw_items, meta

    # -- single offer ------------------------------------------------------

    def fetch_offer(self, identifier: dict) -> dict | None:
        post_id = _post_id_from_identifier(identifier)
        slug = _slug_from_url(identifier.get("url"))
        if post_id is None and not slug:
            # Nothing REST can resolve (e.g. a non-property URL): legacy behaviour.
            return self._fetch_offer_html(identifier)

        try:
            return self._fetch_offer_rest(identifier, post_id, slug)
        except AvartenRestError as exc:
            logger.warning("Avarten REST offer lookup failed (%s); falling back to HTML page.", exc)
            return self._fetch_offer_html(identifier)

    def _fetch_offer_rest(self, identifier: dict, post_id: int | None, slug: str | None) -> dict | None:
        record = None
        if post_id is not None:
            record = self.rest_client.get_property(post_id=post_id, fields=REST_DETAIL_FIELDS)
        if record is None and slug:
            record = self.rest_client.get_property(slug=slug, fields=REST_DETAIL_FIELDS)
        if record is None:
            return None

        images, images_source = self._gallery_urls(record, identifier.get("url"))
        return {
            "kind": "rest_offer",
            "offer": record,
            "images": images,
            "images_source": images_source,
            "url": identifier.get("url"),
        }

    def _gallery_urls(self, record: dict, requested_url: str | None) -> tuple[list[str], str]:
        media_ids = _gallery_media_ids(record)

        if media_ids:
            try:
                media = self.rest_client.get_media(media_ids)
            except AvartenRestError as exc:
                logger.warning("Avarten REST media lookup failed (%s); trying the HTML gallery.", exc)
            else:
                urls = []
                for media_id in media_ids:
                    url = _pick_image_url(media.get(media_id), GALLERY_IMAGE_SIZES)
                    if url and url not in urls:
                        urls.append(url)
                if urls:
                    return urls, "rest_media"

        page_url = requested_url or record.get("link")
        if page_url:
            try:
                response = requests.get(page_url, headers=HEADERS, timeout=20)
                response.raise_for_status()
                details = parse_property_details(html=response.text, url=page_url)
                if details.get("gallery"):
                    return list(details["gallery"]), "html_fallback"
            except Exception as exc:
                logger.warning("Avarten HTML gallery fallback failed for %s: %s", page_url, exc)
        return [], "none"

    def _fetch_offer_html(self, identifier: dict) -> dict | None:
        url = identifier.get("url")
        if not url:
            return None

        response = requests.get(url, headers=HEADERS, timeout=20)
        response.raise_for_status()

        details = parse_property_details(
            html=response.text,
            url=url,
            offer_id=identifier.get("offer_id"),
            listing_id=identifier.get("listing_id"),
        )
        time.sleep(SLEEP_BETWEEN_DETAILS)
        return {"kind": "offer_details", "offer": {**details, "data_source": "html"}, "url": url}

    # -- normalization -----------------------------------------------------

    def normalize_offer(self, raw_offer: dict) -> dict:
        kind = raw_offer.get("kind")
        if kind == "rest_offer":
            return self._normalize_rest_offer(raw_offer)
        if kind == "catalog_offer":
            return self._normalize_catalog_offer(raw_offer["offer"])
        if kind == "offer_details":
            return self._normalize_offer_details(raw_offer["offer"], raw_offer.get("url"))
        raise ValueError(f"Unsupported avarten raw offer kind: {kind}")

    def _normalize_rest_offer(self, raw_offer: dict) -> dict:
        record = raw_offer.get("offer") or {}
        meta = record.get("property_meta") if isinstance(record.get("property_meta"), dict) else {}
        images = [url for url in raw_offer.get("images") or [] if isinstance(url, str) and url]

        post_id = record.get("id") if isinstance(record.get("id"), int) and not isinstance(record.get("id"), bool) else None
        post_id_text = str(post_id) if post_id is not None else None
        slug = _clean_text(record.get("slug"))
        link = _clean_text(record.get("link"))
        title_raw = (record.get("title") or {}).get("rendered") if isinstance(record.get("title"), dict) else record.get("title")
        title = _clean_text(title_raw)
        content_html = (record.get("content") or {}).get("rendered") if isinstance(record.get("content"), dict) else None
        description = _html_to_text(content_html)

        amount = _parse_rest_price(_meta_first(meta, "fave_property_price"))
        price_label = _meta_first(meta, "fave_prop-price")
        currency, currency_source = _rest_currency(amount, price_label)
        if not price_label and amount is not None:
            price_label = f"{amount:,} {currency}".replace(",", " ") if currency != "unknown" else None

        bedrooms, beds_raw, bedroom_options = _rest_bedrooms(meta)
        bathrooms_text = _meta_first(meta, "fave_property_bathrooms")
        bathrooms = _parse_count(bathrooms_text)

        market_slugs = _class_slugs(record, "property_status-")
        market_type = next((slug for slug in market_slugs if slug in MARKET_LABELS_PL), "unknown")
        type_slugs = _class_slugs(record, "property_type-")
        type_labels = [PROPERTY_TYPE_LABELS_PL.get(slug) or _humanize_slug(slug) for slug in type_slugs]
        city_slugs = _class_slugs(record, "property_city-")
        city = _humanize_slug(city_slugs[0]) if city_slugs else None
        area = _clean_text(_meta_first(meta, "fave_property_map_address") or _meta_first(meta, "fave_property_address"))
        address_parts = []
        for part in (area, city):
            if part and part.lower() not in {existing.lower() for existing in address_parts}:
                address_parts.append(part)
        lat, lng = _rest_coordinates(meta)

        developer = _clean_text(_meta_first(meta, "fave_developers"))
        handover = _clean_text(_meta_first(meta, "fave_property_year"))
        payment_plan = _rest_payment_plan(meta)
        labels = [FEATURED_LABEL] if _is_featured(record) else []
        cover = images[0] if images else None

        payload = {
            "data_source": "wp_rest",
            "wp_post_id": post_id,
            "slug": slug,
            "link": link,
            "title_rendered": title_raw,
            "date_gmt": record.get("date_gmt"),
            "modified": record.get("modified"),
            "modified_gmt": record.get("modified_gmt"),
            "status": MARKET_LABELS_PL.get(market_type),
            "market_status": market_type,
            "property_type": type_labels,
            "property_type_slugs": type_slugs,
            "developer": developer,
            "handover": handover,
            "beds_raw": beds_raw,
            "baths_raw": bathrooms_text,
            "bedrooms_options": bedroom_options,
            "price_raw": _meta_first(meta, "fave_property_price"),
            "price_currency_source": currency_source,
            "payment_plan": {item["stage"]: item["value"] for item in payment_plan},
            "images_source": raw_offer.get("images_source"),
            "rest_record": record,
        }

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "avarten",
                "external_id": post_id_text,
                "external_url": link,
            },
            "identity": {
                "offer_id": post_id_text or link or slug or "avarten-unknown",
                "reference": post_id_text,
                "slug": slug,
            },
            "status": {
                "lifecycle": "active",
                "labels": labels,
                "published_at": _iso(record.get("date_gmt"), None),
                "updated_at": _iso(record.get("modified_gmt"), record.get("modified")),
            },
            "listing": {
                "title": title or "Nieruchomość",
                "subtitle": None,
                "description_text": description,
                "description_html": description,
                "property_type": "unknown",
                "offer_type": "sale",
                "market_type": market_type,
                "country_code": "AE",
                "location": {
                    "city": city,
                    "region": None,
                    "district": area,
                    "address_label": ", ".join(address_parts) or None,
                    "lat": lat,
                    "lng": lng,
                },
            },
            "pricing": {
                "amount": amount,
                "currency": currency,
                "period": "total",
                "price_label": price_label,
            },
            "metrics": {
                "area_m2": None,
                "usable_area_m2": None,
                "plot_area_m2": None,
                "rooms": None,
                "bedrooms": bedrooms,
                "bathrooms": bathrooms,
                "floor": None,
                "floors_total": None,
            },
            "technical": {
                "building_condition": None,
                "property_condition": None,
                "construction_year": None,
                "heating": None,
                "parking": None,
                "windows_type": None,
                "kitchen_type": None,
                "furnishing": None,
                "utilities": {
                    "electricity": None,
                    "gas": None,
                    "sewage": None,
                },
            },
            "financials": {
                "admin_fee": None,
                "payment_plan": payment_plan,
            },
            "media": {
                "cover_image": cover,
                "gallery": images,
                "video": None,
            },
            "agent": {
                "agent_id": None,
                "name": None,
                "email": None,
                "phone": None,
                "license": None,
                "branch": None,
            },
            "seo": {
                "canonical_url": link,
                "robots": "noindex,follow",
                "og_image": cover,
            },
            "raw": {"payload": payload},
        }

    def _normalize_catalog_offer(self, offer: dict) -> dict:
        listing_images = _image_urls_from_listing_images(offer.get("images"))
        price_from = _parse_number(offer.get("price_from"))
        offer_url = offer.get("url")
        offer_id = offer.get("offer_id")
        listing_id = offer.get("listing_id")

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "avarten",
                "external_id": offer_id,
                "external_url": offer_url,
            },
            "identity": {
                "offer_id": offer_url or str(offer_id or listing_id or "avarten-unknown"),
                "reference": str(offer_id) if offer_id else None,
                "slug": None,
            },
            "status": {
                "lifecycle": "active",
                "labels": offer.get("labels") or [],
                "published_at": None,
                "updated_at": None,
            },
            "listing": {
                "title": offer.get("title") or "Nieruchomość",
                "subtitle": None,
                "description_text": None,
                "description_html": None,
                "property_type": "unknown",
                "offer_type": "sale",
                "market_type": "unknown",
                "country_code": "AE",
                "location": {
                    "city": offer.get("location"),
                    "region": None,
                    "district": None,
                    "address_label": offer.get("location"),
                    "lat": None,
                    "lng": None,
                },
            },
            "pricing": {
                "amount": price_from,
                "currency": _normalize_currency(offer.get("currency")),
                "period": "total",
                "price_label": offer.get("price_from"),
            },
            "metrics": {
                "area_m2": None,
                "usable_area_m2": None,
                "plot_area_m2": None,
                "rooms": None,
                "bedrooms": _parse_number(offer.get("beds_raw")),
                "bathrooms": _parse_number(offer.get("baths_raw")),
                "floor": None,
                "floors_total": None,
            },
            "technical": {
                "building_condition": None,
                "property_condition": None,
                "construction_year": None,
                "heating": None,
                "parking": None,
                "windows_type": None,
                "kitchen_type": None,
                "furnishing": None,
                "utilities": {
                    "electricity": None,
                    "gas": None,
                    "sewage": None,
                },
            },
            "financials": {
                "admin_fee": None,
                "payment_plan": [],
            },
            "media": {
                "cover_image": listing_images[0] if listing_images else None,
                "gallery": listing_images,
                "video": None,
            },
            "agent": {
                "agent_id": None,
                "name": None,
                "email": None,
                "phone": None,
                "license": None,
                "branch": None,
            },
            "seo": {
                "canonical_url": offer_url,
                "robots": "noindex,follow",
                "og_image": listing_images[0] if listing_images else None,
            },
            "raw": {"payload": offer},
        }

    def _normalize_offer_details(self, offer: dict, url: str | None) -> dict:
        gallery = offer.get("gallery") or []
        location = offer.get("location") or {}
        payment_plan = offer.get("payment_plan") or {}
        payment_plan_items = [{"stage": k, "value": v} for k, v in payment_plan.items()]
        price_from = _parse_number(offer.get("price_from"))
        offer_id = offer.get("offer_id")
        listing_id = offer.get("listing_id")

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "avarten",
                "external_id": offer_id,
                "external_url": url,
            },
            "identity": {
                "offer_id": url or str(offer_id or listing_id or "avarten-unknown"),
                "reference": str(offer_id) if offer_id else None,
                "slug": None,
            },
            "status": {
                "lifecycle": "active",
                "labels": [],
                "published_at": None,
                "updated_at": None,
            },
            "listing": {
                "title": offer.get("title") or "Nieruchomość",
                "subtitle": None,
                "description_text": offer.get("description"),
                "description_html": offer.get("description"),
                "property_type": "unknown",
                "offer_type": "sale",
                "market_type": "unknown",
                "country_code": "AE",
                "location": {
                    "city": location.get("Miejscowość"),
                    "region": location.get("Województwo"),
                    "district": location.get("Dzielnica"),
                    "address_label": ", ".join(
                        str(v) for v in location.values() if v is not None and str(v).strip()
                    ) or None,
                    "lat": location.get("lat"),
                    "lng": location.get("lng"),
                },
            },
            "pricing": {
                "amount": price_from,
                "currency": _normalize_currency(offer.get("currency")),
                "period": "total",
                "price_label": offer.get("price_raw"),
            },
            "metrics": {
                "area_m2": None,
                "usable_area_m2": None,
                "plot_area_m2": None,
                "rooms": None,
                "bedrooms": _parse_number(offer.get("beds_raw")),
                "bathrooms": _parse_number(offer.get("baths_raw")),
                "floor": None,
                "floors_total": None,
            },
            "technical": {
                "building_condition": None,
                "property_condition": None,
                "construction_year": None,
                "heating": None,
                "parking": None,
                "windows_type": None,
                "kitchen_type": None,
                "furnishing": None,
                "utilities": {
                    "electricity": None,
                    "gas": None,
                    "sewage": None,
                },
            },
            "financials": {
                "admin_fee": None,
                "payment_plan": payment_plan_items,
            },
            "media": {
                "cover_image": gallery[0] if gallery else None,
                "gallery": gallery,
                "video": None,
            },
            "agent": {
                "agent_id": None,
                "name": None,
                "email": None,
                "phone": None,
                "license": None,
                "branch": None,
            },
            "seo": {
                "canonical_url": url,
                "robots": "noindex,follow",
                "og_image": gallery[0] if gallery else None,
            },
            "raw": {"payload": offer},
        }

