"""Avarten -> generic foreign sync adapter (AVARTEN-SYNC-1).

Maps the canonical offers the existing WordPress-REST Avarten connector produces
(integrations/avarten/connector.py) to SyncDevelopment / SyncOffer
(foreign_sync_merge). Pure: no HTTP, no SQLite, no Flask, no imports of the
connector or of the sync service. Dependency direction:

    Avarten connector -> this adapter -> SyncDevelopment / SyncOffer -> sync_records

One WordPress record is one source development AND one project-level offer (not a
unit). The WordPress post id is the identity of both, in separate namespaces:

    development  (source_platform="avarten", source_key=<post id>)
    offer        (source_platform="avarten", source_offer_ref=<post id>)

Only data the source actually provides is mapped; everything else stays NULL for the
CRM completion workflow. Deliberately NOT mapped (no reliable source value):
area_total_m2, floor, rooms_count, bathrooms_count (Avarten only has an editor-typed
headline that may be the top of a range), category_id_domiporta, offer_type_normalized
and both country fields (the connector's country_code "AE" is a constant it assumes,
not a value read from the source). Bedrooms are mapped only when the connector reports
a single unambiguous value (it reports None for ranges). Developer, handover, payment
plan, bedroom ranges and status labels stay in the canonical/raw layer: there is no
column for them and this stage adds none.
"""
from __future__ import annotations

import html
from dataclasses import dataclass, field
from typing import Any, Iterable

from InvestmentManager.foreign_sync_merge import (
    SourceIdentity,
    SyncContractError,
    SyncDevelopment,
    SyncOffer,
)

SOURCE_PLATFORM = "avarten"
_REST_DATA_SOURCE = "wp_rest"
_MARKETS = ("primary", "secondary")


class AvartenAdaptError(ValueError):
    """A canonical record cannot be adapted (the message says why)."""


@dataclass(frozen=True)
class AdapterError:
    index: int
    wp_post_id: str | None
    title: str | None
    reason: str

    def __str__(self) -> str:
        who = self.wp_post_id or f"#{self.index}"
        return f"{who}{f' ({self.title})' if self.title else ''}: {self.reason}"


@dataclass
class AdapterReport:
    discovered: int = 0
    adapted: int = 0
    errors: list[AdapterError] = field(default_factory=list)

    @property
    def error_count(self) -> int:
        return len(self.errors)


@dataclass
class AdaptedCatalog:
    developments: list[SyncDevelopment]
    offers: list[SyncOffer]
    report: AdapterReport


def _dig(value: Any, *path: str) -> Any:
    for key in path:
        if not isinstance(value, dict):
            return None
        value = value.get(key)
    return value


def _text(value: Any) -> str | None:
    if not isinstance(value, str):
        return None
    text = value.strip()
    return text or None


def _post_id(canonical: dict) -> str:
    """The WordPress post id as text; every place the canonical offer carries it must agree."""
    found: list[str] = []
    for label, value in (
        ("source.external_id", _dig(canonical, "source", "external_id")),
        ("raw.payload.wp_post_id", _dig(canonical, "raw", "payload", "wp_post_id")),
    ):
        if value is None:
            continue
        if isinstance(value, bool):
            raise AvartenAdaptError(f"{label} is not a valid WordPress post id.")
        if isinstance(value, int):
            number = value
        elif isinstance(value, str) and value.strip().isdigit():
            number = int(value.strip())
        else:
            raise AvartenAdaptError(f"{label} is not a valid WordPress post id.")
        if number <= 0:
            raise AvartenAdaptError(f"{label} is not a valid WordPress post id.")
        found.append(str(number))
    if not found:
        raise AvartenAdaptError("Missing WordPress post id.")
    if len(set(found)) > 1:
        raise AvartenAdaptError("Inconsistent WordPress post ids in the canonical offer.")
    return found[0]


def _title(canonical: dict) -> str:
    # The connector substitutes a placeholder title when the REST title is empty; the
    # raw REST title tells whether there really is one.
    raw_title = _dig(canonical, "raw", "payload", "title_rendered")
    if not isinstance(raw_title, str) or not " ".join(html.unescape(raw_title).split()):
        raise AvartenAdaptError("Missing title: a development cannot be created without a name.")
    title = _text(_dig(canonical, "listing", "title"))
    if title is None:
        raise AvartenAdaptError("Missing title: a development cannot be created without a name.")
    return title


def _currency(canonical: dict) -> str | None:
    if _dig(canonical, "pricing", "amount") is None:
        return None
    currency = _text(_dig(canonical, "pricing", "currency"))
    if currency is None or currency.lower() == "unknown":
        return None
    # "source_default" means the connector assumed the currency (the price label
    # named none); an assumption is not source data.
    if _dig(canonical, "raw", "payload", "price_currency_source") == "source_default":
        return None
    return currency


def _property_type(canonical: dict) -> str | None:
    slugs = _dig(canonical, "raw", "payload", "property_type_slugs")
    if not isinstance(slugs, list):
        return None
    parts = [slug.strip() for slug in slugs if isinstance(slug, str) and slug.strip()]
    return ", ".join(parts) or None


def _images(canonical: dict) -> list[str]:
    gallery = _dig(canonical, "media", "gallery")
    images = [url for url in gallery if isinstance(url, str) and url.strip()] if isinstance(gallery, list) else []
    if not images:
        cover = _text(_dig(canonical, "media", "cover_image"))
        images = [cover] if cover else []
    return images


def adapt_avarten_offer(canonical: dict) -> tuple[SyncDevelopment, SyncOffer]:
    """One canonical Avarten offer -> (its development, its project-level offer).

    Raises AvartenAdaptError for anything that must not reach the sync: not a
    WordPress-REST canonical offer, no/invalid post id, no title, no source URL.
    """
    if not isinstance(canonical, dict):
        raise AvartenAdaptError("Canonical offer is not an object.")
    if _dig(canonical, "source", "platform") != SOURCE_PLATFORM:
        raise AvartenAdaptError("Canonical offer is not an Avarten offer.")
    if _dig(canonical, "raw", "payload", "data_source") != _REST_DATA_SOURCE:
        raise AvartenAdaptError("Canonical offer does not come from the WordPress REST API.")

    wp_id = _post_id(canonical)
    title = _title(canonical)
    source_url = _text(_dig(canonical, "source", "external_url"))
    if source_url is None:
        # SyncOffer needs a URL and none is invented here.
        raise AvartenAdaptError("Missing source URL.")

    location = _dig(canonical, "listing", "location") or {}
    market = _dig(canonical, "listing", "market_type")
    bedrooms = _dig(canonical, "metrics", "bedrooms")
    fields = {
        "offer_title": title,
        "offer_description": _dig(canonical, "listing", "description_text"),
        "price_value": _dig(canonical, "pricing", "amount"),
        "price_currency": _currency(canonical),
        "latitude": location.get("lat") if isinstance(location, dict) else None,
        "longitude": location.get("lng") if isinstance(location, dict) else None,
        "source_city_name": location.get("city") if isinstance(location, dict) else None,
        "source_location_text": (
            (location.get("district") or location.get("address_label")) if isinstance(location, dict) else None
        ),
        "market_type_normalized": market if market in _MARKETS else None,
        "property_type_source": _property_type(canonical),
        "bedrooms_count": bedrooms if isinstance(bedrooms, int) and not isinstance(bedrooms, bool) else None,
    }

    try:
        development = SyncDevelopment(SOURCE_PLATFORM, wp_id, title)
        offer = SyncOffer(
            SOURCE_PLATFORM,
            wp_id,
            source_url,
            development=SourceIdentity(SOURCE_PLATFORM, wp_id),
            fields=fields,
            images=_images(canonical),
            features=None,  # the canonical offer has no feature list (payment plan is not a feature)
        )
    except SyncContractError as exc:
        raise AvartenAdaptError(str(exc)) from exc
    return development, offer


def adapt_avarten_catalog(canonical_offers: Iterable[dict]) -> AdaptedCatalog:
    """Adapts a batch; a bad record is reported and skipped, never fatal.

    A WordPress post id that appears twice is not guessed at: the first record
    is kept and every repeat is an error.
    """
    report = AdapterReport()
    developments: list[SyncDevelopment] = []
    offers: list[SyncOffer] = []
    seen: set[str] = set()

    for index, canonical in enumerate(canonical_offers):
        report.discovered += 1
        try:
            development, offer = adapt_avarten_offer(canonical)
            if development.source_key in seen:
                raise AvartenAdaptError(f"Duplicate WordPress post id {development.source_key} in the catalog.")
        except AvartenAdaptError as exc:
            title = _text(_dig(canonical, "listing", "title")) if isinstance(canonical, dict) else None
            try:
                wp_id = _post_id(canonical) if isinstance(canonical, dict) else None
            except AvartenAdaptError:
                wp_id = None
            report.errors.append(AdapterError(index, wp_id, title, str(exc)))
            continue
        seen.add(development.source_key)
        developments.append(development)
        offers.append(offer)
        report.adapted += 1
    return AdaptedCatalog(developments, offers, report)
