"""Contracts and the pure three-way merge for generic foreign source sync (SYNC-2B).

No I/O, no SQLite, no source-specific code: a source adapter produces
SyncDevelopment / SyncOffer, the service reads the current row and calls
merge_offer(), then applies the returned plan.

Three values are compared per managed field:

    current   the working value in foreign_offers (used by the CRM and exports;
              a user may have edited it)
    observed  the last non-NULL value the source reported (foreign_offers.
              source_values_json, written by the sync layer only)
    incoming  the value in the SyncOffer being synced

    observed exists:  current == observed -> the field still follows the source,
                                             so incoming may be applied
                      current != observed -> treated as a manual CRM change:
                                             current is preserved
    observed missing: current is NULL     -> incoming fills it
                      current != incoming -> current preserved (unknown provenance)
    incoming is NULL: no information. Never clears current and never changes
                      the observed value.

Source synchronization must preserve explicit CRM/manual overrides. Accepted
edge case: if the source later reports exactly the manually entered value, the
field follows the source again. floor_override, is_active, needs_update,
is_export_ready, timestamps and source identity are never managed here.
"""
from __future__ import annotations

import hashlib
import json
import math
from dataclasses import dataclass, field
from typing import Any, Iterable, Mapping

OBSERVED_VERSION = 1

# Managed columns of foreign_offers and how their values are normalized.
# floor is a SOURCE field; floor_override (CRM) is deliberately absent.
SYNC_MANAGED_FIELDS: dict[str, str] = {
    "offer_title": "text",
    "offer_description": "text",
    "price_value": "amount",
    "price_currency": "currency",
    "area_total_m2": "amount",
    "area_net_m2": "amount",
    "area_gross_m2": "amount",
    "rooms_count": "int",
    "bedrooms_count": "int",
    "bathrooms_count": "int",
    "floor": "int",
    "latitude": "lat",
    "longitude": "lng",
    "source_country_code": "text",
    "source_country_name": "text",
    "source_region_name": "text",
    "source_city_name": "text",
    "source_location_text": "text",
    "market_type_normalized": "text",
    "offer_type_normalized": "text",
    "property_type_source": "text",
    "category_id_domiporta": "text",
}

# Development assignment decisions.
DEV_STATUS_EXISTING = "existing"
DEV_STATUS_CREATED = "created"
DEV_STATUS_WOULD_CREATE = "would_create"
DEV_STATUS_NAME_CONFLICT = "name_conflict"
DEV_STATUS_UNRESOLVED = "unresolved"
_ASSIGNABLE_DEV_STATUSES = (DEV_STATUS_EXISTING, DEV_STATUS_CREATED, DEV_STATUS_WOULD_CREATE)


class SyncContractError(ValueError):
    """A SyncDevelopment / SyncOffer value is not valid."""


# ---------------------------------------------------------------------------
# Value normalization
# ---------------------------------------------------------------------------


def _clean_text(value: Any, label: str) -> str | None:
    if value is None:
        return None
    if not isinstance(value, str):
        raise SyncContractError(f"{label} must be a string.")
    text = value.strip()
    return text or None


def _require_text(value: Any, label: str) -> str:
    text = _clean_text(value, label)
    if not text:
        raise SyncContractError(f"{label} is required.")
    return text


def canonical_value(field_name: str, value: Any) -> Any:
    """The one normalization used for incoming, stored-observed and current values."""
    kind = SYNC_MANAGED_FIELDS.get(field_name)
    if kind is None:
        raise SyncContractError(f"{field_name} is not a sync-managed field.")
    if value is None:
        return None

    if kind in ("text", "currency"):
        text = _clean_text(value, field_name)
        if text is None:
            return None
        return text.upper() if kind == "currency" else text

    if isinstance(value, bool):
        raise SyncContractError(f"{field_name} must be a number.")
    try:
        number = float(value.strip()) if isinstance(value, str) else float(value)
    except (TypeError, ValueError, AttributeError) as exc:
        raise SyncContractError(f"{field_name} must be a number.") from exc
    if not math.isfinite(number):
        raise SyncContractError(f"{field_name} must be finite.")

    if kind == "int":
        if not number.is_integer():
            raise SyncContractError(f"{field_name} must be a whole number.")
        return int(number)
    if kind == "amount":
        if number < 0:
            raise SyncContractError(f"{field_name} must not be negative.")
        return int(number) if number.is_integer() else number
    limit = 90 if kind == "lat" else 180
    if abs(number) > limit:
        raise SyncContractError(f"{field_name} is out of range.")
    return number


def canonical_text_list(value: Any, label: str) -> tuple[str, ...] | None:
    """Ordered, stripped, de-duplicated strings; None when there is nothing (= no information)."""
    if value is None:
        return None
    if isinstance(value, (str, bytes)) or not isinstance(value, Iterable):
        raise SyncContractError(f"{label} must be a list of strings.")
    items: list[str] = []
    for item in value:
        text = _clean_text(item, label)
        if text and text not in items:
            items.append(text)
    return tuple(items) or None


@dataclass(frozen=True)
class _Unparseable:
    """A stored value that does not normalize; equal only to itself, so it never looks 'unchanged'."""

    value: Any


def canonical_current_value(field_name: str, value: Any) -> Any:
    """canonical_value for a value read back from the DB; never raises.

    A stored value that does not normalize comes back as an object equal only to
    itself, so it is never mistaken for an equal source/incoming value.
    """
    try:
        return canonical_value(field_name, value)
    except SyncContractError:
        return _Unparseable(value)


def _canonical_current_list(values: Iterable[Any], label: str) -> tuple[str, ...] | Any:
    try:
        return canonical_text_list(list(values), label) or ()
    except SyncContractError:
        return _Unparseable(tuple(values))


# ---------------------------------------------------------------------------
# Contracts
# ---------------------------------------------------------------------------


@dataclass(frozen=True)
class SourceIdentity:
    source_platform: str
    source_key: str

    def __post_init__(self):
        object.__setattr__(self, "source_platform", _require_text(self.source_platform, "source_platform"))
        object.__setattr__(self, "source_key", _require_text(self.source_key, "source_key"))


@dataclass(frozen=True)
class SyncDevelopment:
    source_platform: str
    source_key: str
    name: str

    def __post_init__(self):
        object.__setattr__(self, "source_platform", _require_text(self.source_platform, "source_platform"))
        object.__setattr__(self, "source_key", _require_text(self.source_key, "source_key"))
        name = " ".join(_require_text(self.name, "name").split())
        object.__setattr__(self, "name", name)

    @property
    def identity(self) -> SourceIdentity:
        return SourceIdentity(self.source_platform, self.source_key)


AVAILABILITY_STATES = ("available", "sold_out", "unclear")


@dataclass(frozen=True)
class SourceAvailability:
    """What the source says about availability, as an adapter judged it.

    available  the source positively reports availability
    sold_out   the source consistently reports none available (confirmed)
    unclear    the source data contradicts itself or is incomplete: kept for review
    Absent (None on SyncOffer) means the source says nothing about availability.
    It never changes is_active or any managed field; it only drives warnings.
    """

    state: str
    detail: str = ""

    def __post_init__(self):
        if self.state not in AVAILABILITY_STATES:
            raise SyncContractError(f"availability state must be one of {AVAILABILITY_STATES}.")
        object.__setattr__(self, "detail", str(self.detail or "").strip())


@dataclass(frozen=True)
class SyncOffer:
    source_platform: str
    source_offer_ref: str
    source_url: str
    development: SourceIdentity | None = None
    fields: Mapping[str, Any] = field(default_factory=dict)
    images: Iterable[str] | None = None
    features: Iterable[str] | None = None
    availability: SourceAvailability | None = None

    def __post_init__(self):
        platform = _require_text(self.source_platform, "source_platform")
        object.__setattr__(self, "source_platform", platform)
        object.__setattr__(self, "source_offer_ref", _require_text(self.source_offer_ref, "source_offer_ref"))
        object.__setattr__(self, "source_url", _require_text(self.source_url, "source_url"))

        if self.development is not None:
            if not isinstance(self.development, SourceIdentity):
                raise SyncContractError("development must be a SourceIdentity.")
            if self.development.source_platform != platform:
                raise SyncContractError("An offer can only reference a development of its own source.")

        normalized: dict[str, Any] = {}
        for name, value in dict(self.fields).items():
            canonical = canonical_value(name, value)  # rejects unknown names
            if canonical is not None:
                normalized[name] = canonical
        object.__setattr__(self, "fields", normalized)
        object.__setattr__(self, "images", canonical_text_list(self.images, "images"))
        object.__setattr__(self, "features", canonical_text_list(self.features, "features"))
        if self.availability is not None and not isinstance(self.availability, SourceAvailability):
            raise SyncContractError("availability must be a SourceAvailability.")


def source_payload_hash(offer: SyncOffer) -> str:
    """Deterministic hash of the normalized SyncOffer (never of raw HTML/REST).

    An informational change signal only: the merge never depends on it, and a
    manual DB edit does not change it.
    """
    payload = {
        "platform": offer.source_platform,
        "ref": offer.source_offer_ref,
        "url": offer.source_url,
        "development": (
            [offer.development.source_platform, offer.development.source_key] if offer.development else None
        ),
        "fields": offer.fields,
        "images": list(offer.images) if offer.images else None,
        "features": list(offer.features) if offer.features else None,
    }
    return hashlib.sha256(_dumps(payload).encode("utf-8")).hexdigest()


def _dumps(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))


# ---------------------------------------------------------------------------
# Observed source values (foreign_offers.source_values_json)
# ---------------------------------------------------------------------------


@dataclass(frozen=True)
class Observed:
    fields: Mapping[str, Any] = field(default_factory=dict)
    images: tuple[str, ...] | None = None
    features: tuple[str, ...] | None = None
    # True once the sync layer assigned a development to this offer.
    development_assigned: bool = False
    # The stored JSON was unreadable. History is then treated as absent (merge
    # only fills NULLs and preserves everything else) and the marker is set
    # conservatively so a development is not re-assigned.
    corrupt: bool = False

    def to_json(self) -> str:
        document: dict[str, Any] = {
            "v": OBSERVED_VERSION,
            "fields": {name: self.fields[name] for name in sorted(self.fields)},
            "development_assigned": bool(self.development_assigned),
        }
        if self.images is not None:
            document["images"] = list(self.images)
        if self.features is not None:
            document["features"] = list(self.features)
        return _dumps(document)


_CORRUPT_OBSERVED = Observed(development_assigned=True, corrupt=True)


def parse_observed(text: str | None) -> Observed:
    """Never raises. NULL/empty/"{}" mean no history; anything unreadable is 'corrupt'."""
    if text is None or not str(text).strip():
        return Observed()
    try:
        document = json.loads(text)
    except (TypeError, ValueError):
        return _CORRUPT_OBSERVED
    if not isinstance(document, dict):
        return _CORRUPT_OBSERVED
    if not document:
        return Observed()
    if document.get("v") != OBSERVED_VERSION:
        return _CORRUPT_OBSERVED

    try:
        raw_fields = document.get("fields", {})
        if not isinstance(raw_fields, dict):
            return _CORRUPT_OBSERVED
        fields: dict[str, Any] = {}
        for name, value in raw_fields.items():
            if name not in SYNC_MANAGED_FIELDS:
                return _CORRUPT_OBSERVED
            canonical = canonical_value(name, value)
            if canonical is not None:
                fields[name] = canonical
        images = canonical_text_list(document["images"], "images") if "images" in document else None
        features = canonical_text_list(document["features"], "features") if "features" in document else None
        assigned = document.get("development_assigned", False)
        if not isinstance(assigned, bool):
            return _CORRUPT_OBSERVED
    except SyncContractError:
        return _CORRUPT_OBSERVED
    return Observed(fields=fields, images=images, features=features, development_assigned=assigned)


# ---------------------------------------------------------------------------
# Merge
# ---------------------------------------------------------------------------


@dataclass(frozen=True)
class ExistingOffer:
    """The current DB state of an offer, as raw column values."""

    fields: Mapping[str, Any]
    images: tuple[str, ...] = ()
    features: tuple[str, ...] = ()
    development_id: int | None = None


@dataclass(frozen=True)
class DevelopmentResolution:
    """What ensure_development decided for the offer's development identity."""

    status: str
    development_id: int | None = None


@dataclass(frozen=True)
class FieldChange:
    field: str
    before: Any
    after: Any


@dataclass(frozen=True)
class PreservedField:
    field: str
    current: Any
    incoming: Any
    reason: str  # "manual" | "unknown_provenance"


@dataclass(frozen=True)
class ListAction:
    action: str  # create | replace | unchanged | preserved | no_information
    value: tuple[str, ...] | None = None


@dataclass(frozen=True)
class DevelopmentAction:
    action: str  # none | assign | would_assign | preserve_current | preserve_detached | name_conflict | unresolved
    development_id: int | None = None


@dataclass(frozen=True)
class MergePlan:
    action: str  # created | updated | unchanged
    create_columns: Mapping[str, Any]
    applied: tuple[FieldChange, ...]
    preserved: tuple[PreservedField, ...]
    observed_after: Observed
    images: ListAction
    features: ListAction
    development: DevelopmentAction
    observed_corrupt: bool
    # Business/exported data actually changed on an existing offer: applied
    # fields, replaced images/features or a newly assigned development. Not
    # set by last-seen, hash or observed-value bookkeeping.
    business_changed: bool

    @property
    def applied_fields(self) -> tuple[str, ...]:
        return tuple(change.field for change in self.applied)


def _merge_list(current: Any, previous: tuple | None, incoming: tuple | None) -> ListAction:
    if incoming is None:
        return ListAction("no_information")
    if previous is None:
        if current == ():
            return ListAction("replace", incoming)
        if current == incoming:
            return ListAction("unchanged")
        return ListAction("preserved")  # unknown provenance
    if current == previous:
        return ListAction("unchanged") if incoming == current else ListAction("replace", incoming)
    return ListAction("unchanged") if incoming == previous else ListAction("preserved")


def _decide_development(
    existing: ExistingOffer | None,
    observed: Observed,
    incoming: SyncOffer,
    resolution: DevelopmentResolution | None,
) -> DevelopmentAction:
    if existing is not None and existing.development_id is not None:
        return DevelopmentAction("preserve_current")
    if incoming.development is None:
        return DevelopmentAction("none")
    if existing is not None and observed.development_assigned:
        return DevelopmentAction("preserve_detached")  # the sync assigned one before: a NULL now is a detach
    status = resolution.status if resolution else DEV_STATUS_UNRESOLVED
    if status == DEV_STATUS_NAME_CONFLICT:
        return DevelopmentAction("name_conflict")
    if status in _ASSIGNABLE_DEV_STATUSES:
        if status == DEV_STATUS_WOULD_CREATE:
            return DevelopmentAction("would_assign")
        return DevelopmentAction("assign", resolution.development_id)
    return DevelopmentAction("unresolved")


def merge_offer(
    existing: ExistingOffer | None,
    observed: Observed,
    incoming: SyncOffer,
    development: DevelopmentResolution | None = None,
) -> MergePlan:
    """Pure three-way merge; see the module docstring for the rules."""
    dev_action = _decide_development(existing, observed, incoming, development)
    assigns = dev_action.action in ("assign", "would_assign")

    observed_fields = dict(observed.fields)
    observed_images = observed.images
    observed_features = observed.features

    if existing is None:
        observed_fields.update(incoming.fields)
        observed_after = Observed(
            fields=observed_fields,
            images=incoming.images,
            features=incoming.features,
            development_assigned=assigns,
            corrupt=False,
        )
        return MergePlan(
            action="created",
            create_columns=dict(incoming.fields),
            applied=(),
            preserved=(),
            observed_after=observed_after,
            images=ListAction("create", incoming.images) if incoming.images else ListAction("no_information"),
            features=ListAction("create", incoming.features) if incoming.features else ListAction("no_information"),
            development=dev_action,
            observed_corrupt=False,
            business_changed=False,
        )

    applied: list[FieldChange] = []
    preserved: list[PreservedField] = []
    for name in SYNC_MANAGED_FIELDS:
        incoming_value = incoming.fields.get(name)
        if incoming_value is None:
            continue  # no information: keep current and the observed value
        current = canonical_current_value(name, existing.fields.get(name))
        previous = observed_fields.get(name)
        if previous is None:
            if current is None:
                applied.append(FieldChange(name, None, incoming_value))
            elif current != incoming_value:
                preserved.append(PreservedField(name, current, incoming_value, "unknown_provenance"))
        elif current == previous:
            if incoming_value != current:
                applied.append(FieldChange(name, current, incoming_value))
        elif incoming_value != previous:
            preserved.append(PreservedField(name, current, incoming_value, "manual"))
        observed_fields[name] = incoming_value

    images = _merge_list(
        _canonical_current_list(existing.images, "images"), observed_images, incoming.images
    )
    features = _merge_list(
        _canonical_current_list(existing.features, "features"), observed_features, incoming.features
    )
    if incoming.images is not None:
        observed_images = incoming.images
    if incoming.features is not None:
        observed_features = incoming.features

    business_changed = bool(
        applied
        or images.action == "replace"
        or features.action == "replace"
        or dev_action.action == "assign"
    )
    observed_after = Observed(
        fields=observed_fields,
        images=observed_images,
        features=observed_features,
        development_assigned=observed.development_assigned or assigns,
        corrupt=False,
    )
    return MergePlan(
        action="updated" if business_changed else "unchanged",
        create_columns={},
        applied=tuple(applied),
        preserved=tuple(preserved),
        observed_after=observed_after,
        images=images,
        features=features,
        development=dev_action,
        observed_corrupt=observed.corrupt,
        business_changed=business_changed,
    )
