"""AVARTEN-SYNC-1: the pure Avarten -> SyncDevelopment/SyncOffer adapter.

Canonical offers are produced by the real AvartenConnector.normalize_offer() from
REST-shaped fixtures, so the adapter is tested against the connector's actual output
(never against a hand-written shape). No HTTP, no database.
"""
import ast
import inspect

import pytest

from InvestmentManager.foreign_sync_merge import SourceIdentity, SyncDevelopment, SyncOffer
from InvestmentManager.foreign_sync_sources import avarten as adapter_module
from InvestmentManager.foreign_sync_sources.avarten import (
    AvartenAdaptError,
    adapt_avarten_catalog,
    adapt_avarten_offer,
)
from integrations.avarten.connector import AvartenConnector
from tests.avarten.avarten_rest_fixtures import BASE, rest_property

CONNECTOR = AvartenConnector()
GALLERY = [f"{BASE}/wp-content/uploads/2025/04/img-{i}-1170x785.jpg" for i in range(3)]


def canonical(images=None, **overrides):
    return CONNECTOR.normalize_offer(
        {"kind": "rest_offer", "offer": rest_property(**overrides), "images": GALLERY if images is None else images, "images_source": "rest_media"}
    )


def adapt(**kwargs):
    return adapt_avarten_offer(canonical(**kwargs))


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


def test_wp_post_id_is_the_development_key_and_the_offer_ref():
    development, offer = adapt()

    assert development == SyncDevelopment("avarten", "26161", "Laya Courtyard at Dubai Studio City")
    assert (offer.source_platform, offer.source_offer_ref) == ("avarten", "26161")
    assert offer.development == SourceIdentity("avarten", "26161")  # same id, separate namespaces


def test_development_name_is_the_english_rest_title_html_unescaped():
    development, offer = adapt(title={"rendered": "Costa Mare at Al Marjan Island &#8211; Ellington"})

    assert development.name == "Costa Mare at Al Marjan Island – Ellington"
    assert offer.fields["offer_title"] == development.name


def test_the_developer_is_not_used_as_the_development_name():
    development, _ = adapt(meta={"fave_developers": ["Deca Development"]})
    assert "Deca" not in development.name


def test_source_url_is_the_canonical_english_link_and_identity_ignores_it():
    _, offer = adapt()
    assert offer.source_url == f"{BASE}/property/laya-courtyard-at-dubai-studio-city/"
    assert "/pl/" not in offer.source_url

    _, renamed = adapt(link=f"{BASE}/property/some-new-slug/")
    assert renamed.source_offer_ref == offer.source_offer_ref  # the URL is not the identity


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


def test_maps_the_data_avarten_really_has():
    _, offer = adapt()

    assert dict(offer.fields) == {
        "offer_title": "Laya Courtyard at Dubai Studio City",
        "offer_description": offer.fields["offer_description"],
        "price_value": 699000,
        "price_currency": "AED",
        "latitude": pytest.approx(25.03605241282),
        "longitude": pytest.approx(55.231962187092),
        "source_city_name": "Dubai",
        "source_location_text": "Dubai Studio City",
        "market_type_normalized": "primary",
        "property_type_source": "apartments",
    }
    assert offer.fields["offer_description"].startswith("Laya Courtyard at Dubai Studio City by DECA properties")


def test_nothing_is_fabricated_for_data_the_source_does_not_have():
    _, offer = adapt()

    for absent in ("area_total_m2", "floor", "rooms_count", "bathrooms_count", "bedrooms_count", "category_id_domiporta",
                   "offer_type_normalized", "source_country_name", "source_country_code", "source_region_name"):
        assert absent not in offer.fields, absent
    assert "floor_override" not in offer.fields


def test_bedroom_range_is_not_collapsed_and_a_single_value_is_kept():
    _, ranged = adapt()  # fave_bedroom = 1, 2
    _, single = adapt(meta={"fave_bedroom": ["6"], "fave_property_bedrooms": ["6"]})
    _, unclear = adapt(meta={"fave_bedroom": [], "fave_property_bedrooms": ["Multiple"]})

    assert "bedrooms_count" not in ranged.fields
    assert single.fields["bedrooms_count"] == 6
    assert "bedrooms_count" not in unclear.fields


def test_ambiguous_bathrooms_are_never_mapped():
    _, offer = adapt(meta={"fave_property_bathrooms": ["7"]})
    assert "bathrooms_count" not in offer.fields


@pytest.mark.parametrize(
    "status_class,expected",
    [("property_status-primary", "primary"), ("property_status-secondary", "secondary"), (None, None)],
)
def test_market_type_only_when_the_source_status_is_unambiguous(status_class, expected):
    classes = ["property", "property_type-apartments"] + ([status_class] if status_class else [])
    _, offer = adapt(class_list=classes)
    assert offer.fields.get("market_type_normalized") == expected


def test_property_type_is_kept_as_the_source_taxonomy_text():
    _, offer = adapt(class_list=["property_type-penthouses", "property_type-villas", "property_status-primary"])
    assert offer.fields["property_type_source"] == "penthouses, villas"

    _, none = adapt(class_list=["property_status-primary"])
    assert "property_type_source" not in none.fields


def test_currency_comes_from_the_source_label_only():
    assert adapt()[1].fields["price_currency"] == "AED"
    # no currency in the label: the connector assumes AED, and an assumption is not source data
    assert "price_currency" not in adapt(meta={"fave_prop-price": [""]})[1].fields
    assert adapt(meta={"fave_prop-price": [""]})[1].fields["price_value"] == 699000
    # a currency the connector cannot name is unknown, not stored as text
    assert "price_currency" not in adapt(meta={"fave_prop-price": ["699,000 USD"]})[1].fields
    # no price -> no currency either
    no_price = adapt(meta={"fave_property_price": [""]})[1]
    assert "price_value" not in no_price.fields and "price_currency" not in no_price.fields


def test_location_prefers_the_district_and_falls_back_to_the_address_label():
    _, offer = adapt(meta={"fave_property_map_address": [""], "fave_property_address": [""]})
    assert offer.fields["source_city_name"] == "Dubai"
    assert offer.fields["source_location_text"] == "Dubai"  # no district: the address label (here just the city)


def test_coordinates_are_optional():
    _, offer = adapt(meta={"houzez_geolocation_lat": [""], "houzez_geolocation_long": [""], "fave_property_location": [""]})
    assert "latitude" not in offer.fields and "longitude" not in offer.fields


# ---------------------------------------------------------------------------
# Images / features
# ---------------------------------------------------------------------------


def test_images_keep_the_connector_order_and_are_not_duplicated():
    _, offer = adapt(images=[GALLERY[2], GALLERY[0], GALLERY[2], GALLERY[1]])
    assert offer.images == (GALLERY[2], GALLERY[0], GALLERY[1])


def test_the_cover_is_the_first_gallery_image_and_is_not_added_again():
    canon = canonical()
    assert canon["media"]["cover_image"] == canon["media"]["gallery"][0]
    _, offer = adapt_avarten_offer(canon)
    assert offer.images == tuple(GALLERY)


def test_without_images_the_offer_carries_no_image_information():
    _, offer = adapt(images=[])
    assert offer.images is None  # SYNC-2B: no information, never clears an existing gallery


def test_only_a_cover_is_used_when_the_gallery_is_empty():
    canon = canonical()
    canon["media"] = {"cover_image": GALLERY[0], "gallery": [], "video": None}
    assert adapt_avarten_offer(canon)[1].images == (GALLERY[0],)


def test_no_features_are_invented_from_the_payment_plan():
    canon = canonical()
    assert canon["financials"]["payment_plan"]  # the source does have one...
    assert adapt_avarten_offer(canon)[1].features is None  # ...but a payment plan is not a feature


# ---------------------------------------------------------------------------
# Missing / invalid records
# ---------------------------------------------------------------------------


def test_a_minimal_record_adapts_with_only_what_it_has():
    minimal = CONNECTOR.normalize_offer({"kind": "rest_offer", "offer": {
        "id": 7, "slug": "bare", "link": f"{BASE}/property/bare/", "title": {"rendered": "Bare"}}, "images": []})

    development, offer = adapt_avarten_offer(minimal)

    assert (development.source_key, development.name) == ("7", "Bare")
    assert dict(offer.fields) == {"offer_title": "Bare"}
    assert offer.images is None and offer.features is None


@pytest.mark.parametrize("title", [{"rendered": ""}, {"rendered": "   "}, {"rendered": "&nbsp;"}, {"rendered": None}, None])
def test_a_missing_title_is_an_error_and_no_name_is_invented(title):
    with pytest.raises(AvartenAdaptError, match="title"):
        adapt(title=title)


@pytest.mark.parametrize("bad_id", [None, "abc", "0", 0, -4, True, 1.5])
def test_missing_or_invalid_wp_id_is_an_error(bad_id):
    with pytest.raises(AvartenAdaptError, match="post id"):
        adapt(id=bad_id)


def test_inconsistent_ids_are_an_error():
    canon = canonical()
    canon["source"]["external_id"] = "111"
    with pytest.raises(AvartenAdaptError, match="Inconsistent"):
        adapt_avarten_offer(canon)


def test_a_missing_source_url_is_an_error_and_none_is_invented():
    with pytest.raises(AvartenAdaptError, match="source URL"):
        adapt(link=None)
    with pytest.raises(AvartenAdaptError, match="source URL"):
        adapt(link="   ")


def test_only_wordpress_rest_canonical_avarten_offers_are_accepted():
    legacy = AvartenConnector().normalize_offer({"kind": "offer_details", "offer": {"title": "Old HTML", "offer_id": "hz-1"}, "url": "https://x/1"})
    with pytest.raises(AvartenAdaptError, match="WordPress REST"):
        adapt_avarten_offer(legacy)

    foreign = canonical()
    foreign["source"]["platform"] = "tripinvest"
    with pytest.raises(AvartenAdaptError, match="not an Avarten"):
        adapt_avarten_offer(foreign)
    for junk in (None, [], "x", 5):
        with pytest.raises(AvartenAdaptError):
            adapt_avarten_offer(junk)


# ---------------------------------------------------------------------------
# Batch
# ---------------------------------------------------------------------------


def test_one_bad_record_does_not_block_the_good_ones_and_is_reported():
    good_a = canonical(id=1, slug="a", link=f"{BASE}/property/a/", title={"rendered": "Alpha"})
    bad = canonical(id=2, slug="b", link=f"{BASE}/property/b/", title={"rendered": ""})
    good_c = canonical(id=3, slug="c", link=f"{BASE}/property/c/", title={"rendered": "Gamma"})

    result = adapt_avarten_catalog([good_a, bad, good_c])

    assert (result.report.discovered, result.report.adapted, result.report.error_count) == (3, 2, 1)
    assert [d.source_key for d in result.developments] == ["1", "3"]
    assert [o.source_offer_ref for o in result.offers] == ["1", "3"]
    error = result.report.errors[0]
    assert (error.index, error.wp_post_id) == (1, "2") and "title" in error.reason
    assert "2" in str(error)


def test_a_duplicate_wp_id_is_an_error_and_the_first_record_wins():
    first = canonical(id=5, slug="a", link=f"{BASE}/property/a/", title={"rendered": "First"})
    second = canonical(id=5, slug="b", link=f"{BASE}/property/b/", title={"rendered": "Second"})

    result = adapt_avarten_catalog([first, second])

    assert (result.report.discovered, result.report.adapted, result.report.error_count) == (2, 1, 1)
    assert result.developments[0].name == "First" and len(result.offers) == 1
    assert "Duplicate" in result.report.errors[0].reason and result.report.errors[0].title == "Second"


def test_errors_carry_identity_and_title_when_available_and_never_raise():
    nonsense = [None, {"source": {"platform": "avarten"}}, "x"]

    result = adapt_avarten_catalog(nonsense)

    assert (result.report.discovered, result.report.adapted, result.report.error_count) == (3, 0, 3)
    assert result.developments == [] and result.offers == []
    assert all(e.reason for e in result.report.errors)


def test_an_empty_batch_is_empty_not_an_error():
    result = adapt_avarten_catalog([])
    assert (result.report.discovered, result.report.adapted, result.report.error_count) == (0, 0, 0)


# ---------------------------------------------------------------------------
# Purity
# ---------------------------------------------------------------------------


def test_the_adapter_imports_no_http_database_flask_connector_or_sync_service():
    tree = ast.parse(inspect.getsource(adapter_module))
    imported = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            imported.update(alias.name for alias in node.names)
        elif isinstance(node, ast.ImportFrom):
            imported.add(node.module)
    assert imported <= {"__future__", "dataclasses", "html", "typing", "InvestmentManager.foreign_sync_merge"}, imported
