"""Cyprus Constructions -> generic foreign sync adapter (CYPRUS-SYNC-1).

Maps the output of the existing Cyprus parser
(modules/cyprus_constructions/cyprus_project_details.extract_project) to
SyncDevelopment / SyncOffer (foreign_sync_merge). Pure: no HTTP, no SQLite, no Flask,
no imports of the parser or of the sync service. Dependency direction:

    Cyprus parser/live client -> this adapter -> SyncDevelopment / SyncOffer -> sync_records

Semantics (fixed product decisions):

- A project is a development. A UnitType is ONE offer of a type, never an individual
  unit: the source has no unit numbers, floors or inventory, and `available_units`
  is data about the type, never a reason to create N offers.
- Development identity: (cyprus_constructions, <normalized project URL slug>). The
  numeric project id is not used: it is not unique (two projects have id 5).
- Offer identity: (project slug, phase_group_key, external_id), encoded by
  encode_unit_type_ref(). external_id repeats between phase groups and its case matters.

Only what the source states is mapped; the rest stays NULL for the CRM completion
workflow. Preserved source facts:

- netArea and grossArea are stored separately as source facts. They are NOT mapped
  to separate fields; netArea is also the explicit business-approved canonical
  publication area (area_total_m2). grossArea is never used as a fallback area.
- exact feature strings like "3 Bedrooms" / "2 Bathrooms" set bedrooms_count and
  bathrooms_count. Living-room-like text is not treated as rooms.
- category_id_domiporta is derived only from concrete UnitType semantics. Strong
  identity/title evidence wins over weaker prose; ambiguous evidence stays NULL.

Deliberately NOT mapped:

- floor, rooms, market type, offer type, property type (the JSON-LD category is
  project-level), coordinates (the parser output has none), country
  (the source states no country; "Cyprus"/"North Cyprus"/"CY" would be an assumption).
- availability, status, installments and the phase title: never turned into is_active,
  fields, features or description. They contradict each other in the source.

Availability (INV-LC-5) is only classified into SyncOffer.availability, which
drives warnings, never fields or is_active (see _availability for the rules).
"""
from __future__ import annotations

import json
import re
from dataclasses import dataclass, field
from typing import Any, Iterable
from urllib.parse import quote, unquote, urlparse

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

SOURCE_PLATFORM = "cyprus_constructions"
_TITLE_SEPARATOR = " — "
_BEDROOM_RE = re.compile(r"^\s*(\d+)\s+bedrooms?\s*$", re.IGNORECASE)
_BATHROOM_RE = re.compile(r"^\s*(\d+)\s+bathrooms?\s*$", re.IGNORECASE)
_APARTMENT_CATEGORY = "191"
_HOUSE_CATEGORY = "192"
_APARTMENT_RE = re.compile(r"\b(apartments?|studios?|penthouses?|lofts?)\b", re.IGNORECASE)
_HOUSE_RE = re.compile(r"\b(villas?|houses?)\b", re.IGNORECASE)


class CyprusAdaptError(ValueError):
    """A project or unit type cannot be adapted (the message says why)."""


# ---------------------------------------------------------------------------
# Identity
# ---------------------------------------------------------------------------


def normalize_project_slug(project_url: Any) -> str:
    """The project's URL slug, decoded and lower-cased ("Phuket_H&W_Resort" -> "phuket_h&w_resort")."""
    if not isinstance(project_url, str) or not project_url.strip():
        raise CyprusAdaptError("Missing project URL.")
    segments = [part for part in urlparse(project_url.strip()).path.split("/") if part]
    if not segments:
        raise CyprusAdaptError("Project URL has no slug.")
    slug = unquote(segments[-1]).replace("&amp;", "&").strip().lower()
    if not slug:
        raise CyprusAdaptError("Project URL has no slug.")
    return slug


def _identity_part(value: Any, label: str, *, optional: bool = False) -> str | None:
    if value is None and optional:
        return None
    if not isinstance(value, str):
        raise CyprusAdaptError(f"{label} must be a string.")
    text = value.strip()
    if not text:
        if optional:
            return None  # an empty group key is no key
        raise CyprusAdaptError(f"{label} is required.")
    return text


def encode_unit_type_ref(project_slug: Any, phase_group_key: Any, external_id: Any) -> str:
    """The deterministic source_offer_ref of a unit type: a compact JSON array.

    ["phuket_h&w_resort","Phase II","type-A"]   or   ["edremit_villas",null,"type-a"]

    JSON string escaping makes it unambiguous whatever the parts contain (no
    separator can collide), a missing group is `null` (distinct from the text "null"
    or ""), and external_id keeps its case. Parts are only stripped.
    """
    return json.dumps(
        [
            _identity_part(project_slug, "project slug"),
            _identity_part(phase_group_key, "phase group key", optional=True),
            _identity_part(external_id, "external_id"),
        ],
        ensure_ascii=False,
        separators=(",", ":"),
    )


def decode_unit_type_ref(ref: str) -> tuple[str, str | None, str]:
    try:
        parts = json.loads(ref)
    except (TypeError, ValueError) as exc:
        raise CyprusAdaptError("Not a unit type reference.") from exc
    if (
        not isinstance(parts, list) or len(parts) != 3
        or not isinstance(parts[0], str) or not isinstance(parts[2], str)
        or not (parts[1] is None or isinstance(parts[1], str))
    ):
        raise CyprusAdaptError("Not a unit type reference.")
    return parts[0], parts[1], parts[2]


def unit_type_source_url(project_url: str, ref: str) -> str:
    """The project URL plus a fragment naming the unit type.

    UnitTypes have no page of their own; foreign_offers still has
    UNIQUE(source_platform, source_url), so the fragment keeps the URLs of a project's
    offers distinct while staying visibly the project URL. The identity is the
    source_offer_ref, never this URL.
    """
    base = project_url.strip().split("#", 1)[0]
    return f"{base}#unit-type={quote(ref, safe='')}"


# ---------------------------------------------------------------------------
# Report
# ---------------------------------------------------------------------------


@dataclass(frozen=True)
class AdapterError:
    project_slug: str | None
    phase_group_key: str | None
    external_id: str | None
    title: str | None
    reason: str

    def __str__(self) -> str:
        where = " / ".join(part for part in (self.project_slug, self.phase_group_key, self.external_id) if part)
        return f"{where or '?'}{f' ({self.title})' if self.title else ''}: {self.reason}"


@dataclass
class AdapterReport:
    projects_discovered: int = 0
    units_discovered: int = 0
    developments_adapted: int = 0
    offers_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


# ---------------------------------------------------------------------------
# Mapping
# ---------------------------------------------------------------------------


def _text(value: Any) -> str | None:
    if not isinstance(value, str):
        return None
    collapsed = " ".join(value.split())
    return collapsed or None


def _project_name(detail: dict) -> str:
    name = _text(((detail.get("project") or {}).get("json_ld") or {}).get("name"))
    if name is None:
        # project.name is a heuristic (unit title / URL slug) and card.title is an
        # upper-case marketing label: neither is a name, so none is invented.
        raise CyprusAdaptError("No reliable project name (the page has no JSON-LD name).")
    return name


def _offer_title(project_name: str, unit_title: str) -> str:
    """The unit type's own title, prefixed with the project only when it does not name it.

    Unit titles already start with the project ("Aloha Homes Phase I – Type A"), so
    prefixing them would only repeat it.
    """
    first_word = project_name.split()[0].casefold()
    if unit_title.casefold().startswith(first_word):
        return unit_title
    return f"{project_name}{_TITLE_SEPARATOR}{unit_title}"


def _price(unit: dict) -> tuple[Any, str | None]:
    """A numeric price and the currency the source printed next to it (its own symbol,
    e.g. "£191,025" -> GBP), or nothing: "SOLD OUT" is not a price."""
    price = unit.get("price")
    if isinstance(price, bool) or not isinstance(price, (int, float)) or price <= 0:
        return None, None
    return price, _text(unit.get("currency"))


def _availability(unit: dict) -> SourceAvailability | None:
    """Classifies what the unit type says about availability (INV-LC-5).

    Signals: available_units (parsed from the availability text), status,
    the price text ("SOLD OUT") and the payment-plan text. The contradictions
    are the parser's own quality checks (cyprus_project_details.quality_warnings).

    sold_out  available_units == 0 and nothing contradicts it
    available available_units > 0 and nothing contradicts it
    unclear   any contradiction, or a sold-out word without an availability count
    None      no availability information at all
    """
    count = unit.get("available_units")
    count = count if isinstance(count, int) and not isinstance(count, bool) else None
    status = (_text(unit.get("status")) or "")
    price_text = (_text(unit.get("price_text")) or "")
    installments = (_text(unit.get("installments")) or "")
    availability_text = _text(unit.get("availability_text"))
    status_low, price_low, installments_low = status.lower(), price_text.lower(), installments.lower()
    says_sold = "sold" in status_low or "sold out" in price_low

    conflicts = []
    if count is not None and count > 0 and says_sold:
        conflicts.append(f"dostępnych {count}, ale status/cena mówi Sold Out")
    if count == 0 and status_low == "available":
        conflicts.append("dostępnych 0, ale status Available")
    if count == 0 and installments and "sold out" not in installments_low:
        conflicts.append("dostępnych 0, ale plan płatności nie mówi Sold Out")

    detail = f"availability={availability_text!r}, status={status or None!r}, price={price_text or None!r}"
    if conflicts:
        return SourceAvailability("unclear", f"{'; '.join(conflicts)} ({detail})")
    if count == 0:
        return SourceAvailability("sold_out", detail)
    if count is not None and count > 0:
        return SourceAvailability("available", detail)
    if says_sold:
        return SourceAvailability("unclear", f"Sold Out bez liczby dostępnych lokali ({detail})")
    return None


def _images(unit: dict) -> list[str]:
    """Type cover, then the gallery, then the type's floor plan; exact duplicates are
    removed by SyncOffer. The site plan is left out: it is a drawing that is not
    shared project-wide (it differs between the types of most projects)."""
    gallery = unit.get("gallery")
    urls = [unit.get("image_src"), *(gallery if isinstance(gallery, list) else []), unit.get("floor_plan_image")]
    return [url.strip() for url in urls if isinstance(url, str) and url.strip()]


def _features(unit: dict) -> list[str] | None:
    features = unit.get("features")
    return [f for f in features if isinstance(f, str)] if isinstance(features, list) else None


def _positive_area(value: Any) -> Any:
    if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
        return None
    return value


def _exact_feature_count(features: list[str] | None, pattern: re.Pattern[str]) -> int | None:
    counts: set[int] = set()
    for feature in features or []:
        match = pattern.fullmatch(feature)
        if match:
            counts.add(int(match.group(1)))
    return counts.pop() if len(counts) == 1 else None


def _category_evidence(values: Iterable[str | None]) -> set[str]:
    categories: set[str] = set()
    for value in values:
        if not value:
            continue
        if _APARTMENT_RE.search(value):
            categories.add(_APARTMENT_CATEGORY)
        if _HOUSE_RE.search(value):
            categories.add(_HOUSE_CATEGORY)
    return categories


def _single_category(categories: set[str]) -> str | None:
    return next(iter(categories)) if len(categories) == 1 else None


def _category_id_domiporta(unit: dict, features: list[str] | None) -> str | None:
    strong = _category_evidence([
        _text(unit.get("external_id")),
        _text(unit.get("title")),
        _text(unit.get("phase_title")),
    ])
    strong_category = _single_category(strong)
    if strong_category is not None:
        return strong_category
    if strong:
        return None

    weak = _category_evidence([_text(unit.get("description")), *(features or [])])
    return _single_category(weak)


def _adapt_project(detail: dict, report: AdapterReport, seen_refs: set[str], seen_slugs: set[str]):
    units = detail.get("unit_types")
    units = units if isinstance(units, list) else []
    report.projects_discovered += 1
    report.units_discovered += len(units)

    slug = None
    try:
        slug = normalize_project_slug((detail.get("source") or {}).get("project_url"))
        if slug in seen_slugs:
            raise CyprusAdaptError(f"Duplicate project slug {slug!r} in the catalog.")
        project_name = _project_name(detail)
        if not units:
            raise CyprusAdaptError("The project has no unit types.")
        development = SyncDevelopment(SOURCE_PLATFORM, slug, project_name)
    except (CyprusAdaptError, SyncContractError) as exc:
        report.errors.append(AdapterError(slug, None, None, None, str(exc)))
        return None
    seen_slugs.add(slug)

    project_url = detail["source"]["project_url"]
    specs: list[dict] = []
    for unit in units:
        external_id = unit.get("external_id") if isinstance(unit, dict) else None
        group = unit.get("phase_group_key") if isinstance(unit, dict) else None
        title = _text(unit.get("title")) if isinstance(unit, dict) else None
        try:
            if not isinstance(unit, dict):
                raise CyprusAdaptError("Unit type is not an object.")
            if title is None:
                raise CyprusAdaptError("Missing unit type title.")
            ref = encode_unit_type_ref(slug, group, unit.get("external_id"))
            if ref in seen_refs:
                raise CyprusAdaptError("Duplicate unit type identity (project, phase group, external_id).")
            seen_refs.add(ref)
        except CyprusAdaptError as exc:
            report.errors.append(AdapterError(slug, group if isinstance(group, str) else None,
                                              external_id if isinstance(external_id, str) else None, title, str(exc)))
            continue
        specs.append({"unit": unit, "ref": ref, "group": _identity_part(group, "phase group key", optional=True),
                      "title": _offer_title(project_name, title)})

    # Titles must not repeat inside a project: only then the phase group is added.
    counts: dict[str, int] = {}
    for spec in specs:
        counts[spec["title"].casefold()] = counts.get(spec["title"].casefold(), 0) + 1
    for spec in specs:
        if counts[spec["title"].casefold()] > 1 and spec["group"]:
            spec["title"] = f"{spec['title']}{_TITLE_SEPARATOR}{spec['group']}"

    offers: list[SyncOffer] = []
    json_ld = (detail.get("project") or {}).get("json_ld") or {}
    for spec in specs:
        unit = spec["unit"]
        price, currency = _price(unit)
        net_area = _positive_area(unit.get("net_area_m2"))
        features = _features(unit)
        try:
            offers.append(
                SyncOffer(
                    SOURCE_PLATFORM,
                    spec["ref"],
                    unit_type_source_url(project_url, spec["ref"]),
                    development=SourceIdentity(SOURCE_PLATFORM, slug),
                    fields={
                        "offer_title": spec["title"],
                        "offer_description": _text(unit.get("description")),
                        "price_value": price,
                        "price_currency": currency,
                        "area_total_m2": net_area,
                        "area_net_m2": net_area,
                        "area_gross_m2": _positive_area(unit.get("gross_area_m2")),
                        "bedrooms_count": _exact_feature_count(features, _BEDROOM_RE),
                        "bathrooms_count": _exact_feature_count(features, _BATHROOM_RE),
                        "category_id_domiporta": _category_id_domiporta(unit, features),
                        "source_city_name": _text(json_ld.get("address_locality")),
                        "source_region_name": _text(json_ld.get("address_region")),
                    },
                    images=_images(unit),
                    features=features,
                    availability=_availability(unit),
                )
            )
        except SyncContractError as exc:
            seen_refs.discard(spec["ref"])
            report.errors.append(AdapterError(slug, spec["group"], unit.get("external_id"), _text(unit.get("title")), str(exc)))
    return development, offers


def adapt_cyprus_catalog(project_details: Iterable[dict]) -> AdaptedCatalog:
    """Adapts every project (`extract_project` results). A bad project or unit type is
    reported and skipped, never fatal. A development is only produced for a project that
    yields at least one offer."""
    report = AdapterReport()
    developments: list[SyncDevelopment] = []
    offers: list[SyncOffer] = []
    seen_refs: set[str] = set()
    seen_slugs: set[str] = set()

    for detail in project_details:
        if not isinstance(detail, dict):
            report.projects_discovered += 1
            report.errors.append(AdapterError(None, None, None, None, "Project detail is not an object."))
            continue
        adapted = _adapt_project(detail, report, seen_refs, seen_slugs)
        if adapted is None:
            continue
        development, project_offers = adapted
        if not project_offers:
            continue  # every unit type of it failed; the errors are already reported
        developments.append(development)
        offers.extend(project_offers)
        report.developments_adapted += 1
        report.offers_adapted += len(project_offers)
    return AdaptedCatalog(developments, offers, report)
