"""SYNC-2B: the pure three-way merge, contracts, hash and observed-values parser.

None of these tests opens SQLite (they would not need it): merge_offer() takes
the current row state, the last observed source values and the incoming
SyncOffer, and returns a plan.

    current   working value (CRM/exports; may be manually edited)
    observed  last non-NULL value the source reported
    incoming  value in the SyncOffer being synced
"""
import inspect

import pytest

from InvestmentManager import foreign_sync_merge as merge_module
from InvestmentManager.foreign_sync_merge import (
    SYNC_MANAGED_FIELDS,
    DevelopmentResolution,
    ExistingOffer,
    Observed,
    SourceIdentity,
    SyncContractError,
    SyncDevelopment,
    SyncOffer,
    merge_offer,
    parse_observed,
    source_payload_hash,
)

P = "avarten"


def offer(fields=None, **kwargs):
    kwargs.setdefault("development", None)
    return SyncOffer(P, "26161", "https://avartenproperties.com/property/laya/", fields=fields or {}, **kwargs)


def current(development_id=None, images=(), features=(), **fields):
    return ExistingOffer(fields=fields, images=tuple(images), features=tuple(features), development_id=development_id)


def observed(images=None, features=None, development_assigned=False, **fields):
    return Observed(fields=fields, images=images, features=features, development_assigned=development_assigned)


def applied(plan):
    return {change.field: change.after for change in plan.applied}


def preserved(plan):
    return {item.field: (item.current, item.incoming, item.reason) for item in plan.preserved}


DEV = SourceIdentity(P, "26161")
EXISTING_DEV = DevelopmentResolution("existing", 3)


# ---------------------------------------------------------------------------
# Field rules (the approved decision table)
# ---------------------------------------------------------------------------


def test_A_no_history_and_null_current_takes_incoming():
    plan = merge_offer(current(area_total_m2=None), observed(), offer({"area_total_m2": 82}))

    assert applied(plan) == {"area_total_m2": 82}
    assert plan.preserved == ()
    assert plan.observed_after.fields["area_total_m2"] == 82
    assert plan.action == "updated" and plan.business_changed


def test_B_no_history_and_different_current_is_preserved_as_unknown_provenance():
    plan = merge_offer(current(area_total_m2=90), observed(), offer({"area_total_m2": 82}))

    assert plan.applied == ()
    assert preserved(plan) == {"area_total_m2": (90, 82, "unknown_provenance")}
    assert plan.observed_after.fields["area_total_m2"] == 82  # what the source said is still recorded
    assert plan.action == "unchanged" and not plan.business_changed


def test_no_history_and_equal_current_only_records_the_observed_value():
    plan = merge_offer(current(area_total_m2=82), observed(), offer({"area_total_m2": 82}))

    assert plan.applied == () and plan.preserved == ()
    assert plan.observed_after.fields["area_total_m2"] == 82
    assert plan.action == "unchanged"


def test_C_untouched_field_follows_the_source():
    plan = merge_offer(current(area_total_m2=80), observed(area_total_m2=80), offer({"area_total_m2": 85}))

    assert applied(plan) == {"area_total_m2": 85}
    assert plan.observed_after.fields["area_total_m2"] == 85
    assert plan.business_changed


def test_D_manual_change_is_preserved_when_the_source_moves():
    plan = merge_offer(current(area_total_m2=82), observed(area_total_m2=80), offer({"area_total_m2": 85}))

    assert plan.applied == ()
    assert preserved(plan) == {"area_total_m2": (82, 85, "manual")}
    assert plan.observed_after.fields["area_total_m2"] == 85  # the next sync still sees 82 != 85: still manual
    assert not plan.business_changed


def test_steady_manual_value_is_kept_silently_while_the_source_is_unchanged():
    plan = merge_offer(current(area_total_m2=82), observed(area_total_m2=85), offer({"area_total_m2": 85}))

    assert plan.applied == () and plan.preserved == ()
    assert plan.action == "unchanged"


def test_E_null_incoming_preserves_current_and_the_previous_observed_value():
    plan = merge_offer(
        current(area_total_m2=82, price_value=700),
        observed(area_total_m2=80, price_value=700),
        offer({"area_total_m2": None}),  # also: a field the adapter does not provide at all (price_value)
    )

    assert plan.applied == () and plan.preserved == ()
    assert plan.observed_after.fields == {"area_total_m2": 80, "price_value": 700}
    assert plan.action == "unchanged"


def test_null_incoming_never_clears_even_an_untouched_source_value():
    plan = merge_offer(current(price_value=700), observed(price_value=700), offer({}))
    assert plan.applied == () and plan.observed_after.fields["price_value"] == 700


def test_F_manual_title_is_preserved_and_unchanged_source_raises_no_conflict():
    manual = current(offer_title="Laya Courtyard (Studio City)")
    conflict = merge_offer(manual, observed(offer_title="Project A"), offer({"offer_title": "Project A2"}))
    quiet = merge_offer(manual, observed(offer_title="Project A"), offer({"offer_title": "Project A"}))

    assert preserved(conflict) == {"offer_title": ("Laya Courtyard (Studio City)", "Project A2", "manual")}
    assert conflict.applied == ()
    assert quiet.preserved == () and quiet.applied == ()


def test_G_source_price_change_propagates_when_untouched():
    plan = merge_offer(
        current(price_value=699000.0, price_currency="AED"),  # REAL from SQLite equals the observed int
        observed(price_value=699000, price_currency="AED"),
        offer({"price_value": 750000, "price_currency": "AED"}),
    )

    assert applied(plan) == {"price_value": 750000}
    assert plan.business_changed and plan.action == "updated"


def test_H_floor_follows_the_source_and_floor_override_is_never_managed():
    existing = ExistingOffer(fields={"floor": 2, "floor_override": 5})
    plan = merge_offer(existing, observed(floor=2), offer({"floor": 3}))
    cleared = merge_offer(existing, observed(floor=2), offer({"floor": None}))

    assert applied(plan) == {"floor": 3}
    assert "floor_override" not in SYNC_MANAGED_FIELDS
    assert all(change.field != "floor_override" for change in plan.applied)
    assert cleared.applied == () and cleared.observed_after.fields["floor"] == 2  # NULL never clears floor
    with pytest.raises(SyncContractError):
        offer({"floor_override": 4})


def test_unparseable_current_value_is_never_mistaken_for_the_source_value():
    plan = merge_offer(current(price_value="abc"), observed(price_value=100), offer({"price_value": 120}))
    assert plan.applied == () and preserved(plan)["price_value"][2] == "manual"


def test_only_allowlisted_fields_are_ever_applied():
    everything = {name: None for name in SYNC_MANAGED_FIELDS}
    plan = merge_offer(current(), observed(), offer(everything))
    assert plan.applied == ()
    assert set(SYNC_MANAGED_FIELDS) == {
        "offer_title", "offer_description", "price_value", "price_currency", "area_total_m2", "rooms_count",
        "area_net_m2", "area_gross_m2", "bedrooms_count", "bathrooms_count", "floor", "latitude", "longitude", "source_country_code",
        "source_country_name", "source_region_name", "source_city_name", "source_location_text",
        "market_type_normalized", "offer_type_normalized", "property_type_source", "category_id_domiporta",
    }
    for forbidden in ("floor_override", "is_active", "needs_update", "is_export_ready", "development_id",
                      "source_platform", "source_offer_ref", "source_url", "last_source_sync_at"):
        assert forbidden not in SYNC_MANAGED_FIELDS


# ---------------------------------------------------------------------------
# Create
# ---------------------------------------------------------------------------


def test_create_uses_only_provided_values_and_records_everything_observed():
    plan = merge_offer(
        None, Observed(),
        offer({"offer_title": "Laya", "price_value": 699000, "area_total_m2": None},
              development=DEV, images=["u1", "u2"], features=["Pool"]),
        EXISTING_DEV,
    )

    assert plan.action == "created"
    assert dict(plan.create_columns) == {"offer_title": "Laya", "price_value": 699000}
    assert plan.images.action == "create" and plan.images.value == ("u1", "u2")
    assert plan.features.action == "create" and plan.features.value == ("Pool",)
    assert plan.development.action == "assign" and plan.development.development_id == 3
    assert plan.observed_after.development_assigned is True
    assert plan.observed_after.fields == {"offer_title": "Laya", "price_value": 699000}
    assert plan.observed_after.images == ("u1", "u2")


def test_create_without_development_or_images_says_so():
    plan = merge_offer(None, Observed(), offer({"offer_title": "Laya"}))
    assert plan.development.action == "none" and plan.observed_after.development_assigned is False
    assert plan.images.action == "no_information" and plan.features.action == "no_information"


# ---------------------------------------------------------------------------
# Development
# ---------------------------------------------------------------------------


def test_I_manual_development_assignment_is_never_changed():
    plan = merge_offer(current(development_id=7), observed(), offer(development=DEV), EXISTING_DEV)

    assert plan.development.action == "preserve_current"
    assert not plan.business_changed


def test_J_manual_detach_of_a_development_the_sync_assigned_is_not_reassigned():
    plan = merge_offer(current(development_id=None), observed(development_assigned=True), offer(development=DEV), EXISTING_DEV)

    assert plan.development.action == "preserve_detached"
    assert plan.development.development_id is None
    assert not plan.business_changed and plan.observed_after.development_assigned is True


def test_development_is_assigned_to_an_existing_offer_the_sync_never_assigned():
    plan = merge_offer(current(development_id=None), observed(), offer(development=DEV), EXISTING_DEV)

    assert plan.development.action == "assign" and plan.development.development_id == 3
    assert plan.business_changed and plan.action == "updated"
    assert plan.observed_after.development_assigned is True


@pytest.mark.parametrize(
    "resolution,expected",
    [
        (DevelopmentResolution("would_create"), "would_assign"),
        (DevelopmentResolution("name_conflict"), "name_conflict"),
        (DevelopmentResolution("unresolved"), "unresolved"),
        (None, "unresolved"),
    ],
)
def test_development_that_cannot_be_assigned_is_reported_and_leaves_the_offer_alone(resolution, expected):
    plan = merge_offer(current(development_id=None), observed(), offer(development=DEV), resolution)

    assert plan.development.action == expected
    assert plan.observed_after.development_assigned is (expected == "would_assign")
    assert plan.business_changed is False


def test_offer_without_development_identity_never_touches_the_development():
    plan = merge_offer(current(development_id=None), observed(), offer(), EXISTING_DEV)
    assert plan.development.action == "none"


# ---------------------------------------------------------------------------
# Images and features (one ordered list each)
# ---------------------------------------------------------------------------


def test_K_untouched_gallery_is_replaced_by_the_new_source_list():
    plan = merge_offer(current(images=["a", "b"]), observed(images=("a", "b")), offer(images=["a", "b", "c"]))

    assert plan.images.action == "replace" and plan.images.value == ("a", "b", "c")
    assert plan.observed_after.images == ("a", "b", "c")
    assert plan.business_changed


def test_unchanged_gallery_is_left_alone():
    plan = merge_offer(current(images=["a", "b"]), observed(images=("a", "b")), offer(images=["a", "b"]))
    assert plan.images.action == "unchanged" and not plan.business_changed


def test_L_manually_changed_gallery_is_preserved():
    changed = merge_offer(current(images=["a"]), observed(images=("a", "b")), offer(images=["a", "b", "c"]))
    quiet = merge_offer(current(images=["a"]), observed(images=("a", "b")), offer(images=["a", "b"]))
    reordered = merge_offer(current(images=["b", "a"]), observed(images=("a", "b")), offer(images=["x"]))

    assert changed.images.action == "preserved" and changed.images.value is None
    assert quiet.images.action == "unchanged"
    assert reordered.images.action == "preserved"  # order is part of the value
    assert not changed.business_changed


@pytest.mark.parametrize("empty", [None, [], ()])
def test_M_empty_incoming_gallery_is_no_information(empty):
    plan = merge_offer(current(images=["a", "b"]), observed(images=("a", "b")), offer(images=empty))

    assert plan.images.action == "no_information"
    assert plan.observed_after.images == ("a", "b")  # never replaced with an empty value


def test_gallery_without_history_fills_only_an_empty_gallery():
    fill = merge_offer(current(images=[]), observed(), offer(images=["a"]))
    keep = merge_offer(current(images=["z"]), observed(), offer(images=["a"]))
    same = merge_offer(current(images=["a"]), observed(), offer(images=["a"]))

    assert fill.images.action == "replace"
    assert keep.images.action == "preserved" and same.images.action == "unchanged"


def test_features_follow_the_same_rules_as_the_gallery():
    follow = merge_offer(current(features=["Pool"]), observed(features=("Pool",)), offer(features=["Pool", "Gym"]))
    manual = merge_offer(current(features=["Sauna"]), observed(features=("Pool",)), offer(features=["Pool", "Gym"]))
    empty = merge_offer(current(features=["Pool"]), observed(features=("Pool",)), offer(features=[]))

    assert follow.features.action == "replace" and follow.features.value == ("Pool", "Gym")
    assert manual.features.action == "preserved"
    assert empty.features.action == "no_information" and empty.observed_after.features == ("Pool",)


def test_image_and_feature_lists_are_stripped_and_deduplicated():
    incoming = offer(images=[" a ", "a", "", "b"], features=["x", " x", ""])
    assert incoming.images == ("a", "b") and incoming.features == ("x",)


# ---------------------------------------------------------------------------
# Observed values JSON
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("text", [None, "", "   ", "{}"])
def test_missing_or_empty_observed_json_means_no_history(text):
    parsed = parse_observed(text)
    assert parsed == Observed() and not parsed.corrupt


@pytest.mark.parametrize(
    "text",
    [
        "{not json", "[]", "42", '"x"', '{"v": 2, "fields": {}}', '{"fields": {"offer_title": "x"}}',
        '{"v": 1, "fields": []}', '{"v": 1, "fields": {"floor_override": 3}}',
        '{"v": 1, "fields": {"price_value": "abc"}}', '{"v": 1, "images": "a"}',
        '{"v": 1, "development_assigned": "yes"}',
    ],
)
def test_N_malformed_observed_json_is_corrupt_and_conservative(text):
    parsed = parse_observed(text)

    assert parsed.corrupt is True
    assert parsed.fields == {} and parsed.images is None and parsed.features is None
    assert parsed.development_assigned is True  # never re-assign a development from unreadable history


def test_N_merge_with_corrupt_history_only_fills_nulls_and_preserves_everything_else():
    plan = merge_offer(
        current(development_id=None, images=["manual"], area_total_m2=None, offer_title="Manual title"),
        parse_observed("{broken"),
        offer({"area_total_m2": 82, "offer_title": "Source title"}, development=DEV, images=["src"]),
        EXISTING_DEV,
    )

    assert applied(plan) == {"area_total_m2": 82}
    assert preserved(plan) == {"offer_title": ("Manual title", "Source title", "unknown_provenance")}
    assert plan.images.action == "preserved"
    assert plan.development.action == "preserve_detached"
    assert plan.observed_corrupt is True
    assert plan.observed_after.corrupt is False  # rewritten as valid JSON


def test_observed_json_round_trips_deterministically_without_raw_payload():
    original = Observed(
        fields={"price_value": 699000, "offer_title": "Laya", "latitude": 25.036},
        images=("u1", "u2"), features=("Pool",), development_assigned=True,
    )
    text = original.to_json()

    assert text == Observed(
        fields={"latitude": 25.036, "offer_title": "Laya", "price_value": 699000},
        images=("u1", "u2"), features=("Pool",), development_assigned=True,
    ).to_json()  # key order does not matter
    assert text == (
        '{"development_assigned":true,"features":["Pool"],"fields":{"latitude":25.036,'
        '"offer_title":"Laya","price_value":699000},"images":["u1","u2"],"v":1}'
    )
    assert parse_observed(text) == original


# ---------------------------------------------------------------------------
# Contracts and hash
# ---------------------------------------------------------------------------


def test_sync_development_normalizes_and_requires_identity():
    dev = SyncDevelopment(" avarten ", " 26161 ", "  Laya   Courtyard ")
    assert (dev.source_platform, dev.source_key, dev.name) == ("avarten", "26161", "Laya Courtyard")
    assert dev.identity == SourceIdentity("avarten", "26161")
    for args in (("", "1", "n"), ("p", " ", "n"), ("p", "1", ""), ("p", None, "n")):
        with pytest.raises(SyncContractError):
            SyncDevelopment(*args)


@pytest.mark.parametrize(
    "kwargs",
    [
        {"source_platform": ""}, {"source_offer_ref": "  "}, {"source_url": ""},
        {"fields": {"nope": 1}}, {"fields": {"price_value": True}}, {"fields": {"price_value": -1}},
        {"fields": {"latitude": 91}}, {"fields": {"longitude": -181}}, {"fields": {"rooms_count": 2.5}},
        {"fields": {"offer_title": 5}}, {"images": "not-a-list"}, {"images": [1]},
        {"development": SourceIdentity("cyprus_constructions", "x")},  # another source's development
        {"development": ("avarten", "1")},
    ],
)
def test_sync_offer_rejects_invalid_input(kwargs):
    base = {"source_platform": P, "source_offer_ref": "1", "source_url": "https://x/1"}
    with pytest.raises(SyncContractError):
        SyncOffer(**{**base, **kwargs})


def test_sync_offer_normalizes_values():
    normalized = SyncOffer(
        P, " 26161 ", " https://x/1 ",
        fields={"offer_title": "  Laya ", "offer_description": "   ", "price_currency": "aed", "price_value": "699000",
                "area_total_m2": 82.0, "rooms_count": 3.0, "latitude": "25.5", "source_city_name": None},
    )

    assert normalized.source_offer_ref == "26161" and normalized.source_url == "https://x/1"
    assert normalized.fields == {
        "offer_title": "Laya", "price_currency": "AED", "price_value": 699000,
        "area_total_m2": 82, "rooms_count": 3, "latitude": 25.5,
    }


def test_source_net_and_gross_area_follow_source_ownership_rules():
    fill = merge_offer(
        current(area_net_m2=None, area_gross_m2=None),
        observed(),
        offer({"area_net_m2": 105, "area_gross_m2": 128}),
    )
    manual = merge_offer(current(area_net_m2=110), observed(area_net_m2=105), offer({"area_net_m2": 106}))
    empty = merge_offer(current(area_gross_m2=128), observed(area_gross_m2=128), offer({"area_gross_m2": None}))

    assert applied(fill) == {"area_net_m2": 105, "area_gross_m2": 128}
    assert preserved(manual) == {"area_net_m2": (110, 106, "manual")}
    assert empty.applied == () and empty.observed_after.fields["area_gross_m2"] == 128


def test_source_payload_hash_is_deterministic_and_reflects_normalized_content():
    a = offer({"price_value": 1, "offer_title": "T"}, images=["u"])
    b = offer({"offer_title": " T ", "price_value": 1.0, "area_total_m2": None}, images=["u"])  # same after normalizing
    c = offer({"price_value": 2, "offer_title": "T"}, images=["u"])
    d = offer({"price_value": 1, "offer_title": "T"}, images=["u", "v"])
    e = offer({"price_value": 1, "offer_title": "T"}, images=["u"], development=DEV)

    assert source_payload_hash(a) == source_payload_hash(b)
    assert len({source_payload_hash(x) for x in (a, c, d, e)}) == 4
    assert len(source_payload_hash(a)) == 64


def test_merge_module_is_pure_and_source_agnostic():
    source = inspect.getsource(merge_module)
    assert "sqlite3" not in source
    for word in ("import requests", "avarten", "cyprus"):
        assert word not in source.lower()
