"""CYPRUS-SYNC-1: the pure Cyprus adapter, and its output through the generic sync (real throwaway SQLite, no network)."""
import ast
import copy
import pathlib

import pytest

import InvestmentManager.foreign_offers_store as store
from InvestmentManager.foreign_offers_store import update_foreign_offer_fields
from InvestmentManager.foreign_sync import sync_records
from InvestmentManager.foreign_sync_sources import cyprus
from InvestmentManager.foreign_sync_sources.cyprus import (
    adapt_cyprus_catalog, decode_unit_type_ref, encode_unit_type_ref, normalize_project_slug, unit_type_source_url)
from integrations.cyprus_constructions import cyprus_project_details as cpd
from tests.cyprus_constructions.test_unit_type_identity import PHUKET, unit_js
from tests.investmentmanager.test_foreign_developments import foreign_db, fresh_db  # noqa: F401
from tests.investmentmanager.test_foreign_sync_service import offer_row, query

PHUKET_URL = "https://www.cyprusconstructions.com/pl/Phuket_H&W_Resort"
P = "cyprus_constructions"


def unit(external_id="type-a", group="Phase I", title="Aloha Homes – Type A", **overrides):
    base = {
        "external_id": external_id, "title": title, "phase_title": "Type A - Garden", "description": "About it.",
        "status": "Available", "availability_text": "4 units available", "available_units": 4,
        "net_area_m2": 105, "gross_area_m2": 128, "features": ["3 Bedrooms", "Sea view"],
        "price": 191025, "currency": "GBP", "installments": "Key Ready",
        "image_src": "https://cc.test/cover.jpg", "site_plan_image": "https://cc.test/site.webp",
        "floor_plan_image": "https://cc.test/plan.webp", "gallery": ["https://cc.test/g1.jpg", "https://cc.test/g2.jpg"],
        "phase_group_key": group,
    }
    base.update(overrides)
    return base


def project(units=None, url="https://www.cyprusconstructions.com/pl/Aloha_Homes", name="Aloha Homes", locality="Esentepe", region="Kyrenia"):
    json_ld = {k: v for k, v in (("name", name), ("address_locality", locality), ("address_region", region)) if v}
    return {"source": {"project_url": url}, "project": {"name": "Heuristic", "json_ld": json_ld},
            "unit_types": [unit()] if units is None else units}


def phuket_detail(monkeypatch):
    monkeypatch.setattr(cpd, "get_text", lambda s, u: '<script type="application/ld+json">{"@type":"RealEstateListing","name":"Phuket Health and Wellness Resort",'
                        '"address":{"addressLocality":"Bahceli","addressRegion":"Kyrenia"}}</script>')
    monkeypatch.setattr(cpd, "find_initial_script_urls", lambda html, u: [])
    monkeypatch.setattr(cpd, "discover_project_bundle", lambda *a, **k: ("https://cc.test/D.js", PHUKET))
    monkeypatch.setattr(cpd, "extract_page_sections", lambda *a, **k: ({}, {}))
    return cpd.extract_project(object(), PHUKET_URL)


# ---------------------------------------------------------------------------
# Identity encoding
# ---------------------------------------------------------------------------


def test_ref_roundtrips_and_keeps_case_and_none():
    for parts in [("p", "Phase I", "type-a"), ("p", None, "type-A"), ("a&b", 'we"ird|:/', "x y")]:
        assert decode_unit_type_ref(encode_unit_type_ref(*parts)) == parts


def test_ref_parts_cannot_collide():
    refs = {
        encode_unit_type_ref("p", "Phase I", "type-a"), encode_unit_type_ref("p", "Phase II", "type-a"),
        encode_unit_type_ref("p", "Phase I", "type-A"), encode_unit_type_ref("p", None, "type-a"),
        encode_unit_type_ref("p", "null", "type-a"), encode_unit_type_ref("p|Phase I", None, "type-a"),
        encode_unit_type_ref("p", "Phase I|type", "a"), encode_unit_type_ref("q", "Phase I", "type-a"),
    }
    assert len(refs) == 8
    assert encode_unit_type_ref("p", "", "x") == encode_unit_type_ref("p", None, "x")   # an empty group is no group


def test_ref_rejects_missing_parts():
    with pytest.raises(cyprus.CyprusAdaptError):
        encode_unit_type_ref("p", None, "  ")
    with pytest.raises(cyprus.CyprusAdaptError):
        encode_unit_type_ref("", None, "x")
    with pytest.raises(cyprus.CyprusAdaptError):
        decode_unit_type_ref("not json")


def test_slug_is_the_decoded_lowercase_last_segment():
    assert normalize_project_slug("https://www.cyprusconstructions.com/pl/Phuket_H&W_Resort/") == "phuket_h&w_resort"
    assert normalize_project_slug("https://x.test/pl/Aloha%20Homes?x=1") == "aloha homes"
    with pytest.raises(cyprus.CyprusAdaptError):
        normalize_project_slug("https://x.test/")


def test_source_urls_are_distinct_per_offer_and_start_with_the_project_url():
    refs = [encode_unit_type_ref("p", g, e) for g in ("Phase I", "Phase II", None) for e in ("type-a", "type-A", "type-b")]
    urls = [unit_type_source_url("https://x.test/pl/P#old", r) for r in refs]
    assert len(set(urls)) == len(refs) and all(u.startswith("https://x.test/pl/P#unit-type=") for u in urls)


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


def test_one_offer_per_unit_type_never_multiplied_by_available_units():
    catalog = adapt_cyprus_catalog([project([unit(available_units=40)])])

    assert (len(catalog.developments), len(catalog.offers)) == (1, 1)
    dev, offer = catalog.developments[0], catalog.offers[0]
    assert (dev.source_key, dev.name) == ("aloha_homes", "Aloha Homes")
    assert offer.source_offer_ref == encode_unit_type_ref("aloha_homes", "Phase I", "type-a")
    assert offer.development.source_key == "aloha_homes"


def test_exact_field_mapping_and_unmapped_fields():
    offer = adapt_cyprus_catalog([project()]).offers[0]

    assert dict(offer.fields) == {
        "offer_title": "Aloha Homes – Type A", "offer_description": "About it.", "price_value": 191025, "price_currency": "GBP",
        "area_total_m2": 105, "area_net_m2": 105, "area_gross_m2": 128, "bedrooms_count": 3,
        "source_city_name": "Esentepe", "source_region_name": "Kyrenia",
    }
    assert list(offer.features) == ["3 Bedrooms", "Sea view"]
    assert list(offer.images) == ["https://cc.test/cover.jpg", "https://cc.test/g1.jpg", "https://cc.test/g2.jpg", "https://cc.test/plan.webp"]
    assert "Available" not in (offer.fields.get("offer_description") or "") and "Key Ready" not in offer.features


def test_title_is_prefixed_only_when_it_does_not_name_the_project():
    titles = [o.fields["offer_title"] for o in adapt_cyprus_catalog([project([
        unit("a", title="Aloha Homes Phase I – Type A"), unit("b", title="Type B Villa")])]).offers]
    assert titles == ["Aloha Homes Phase I – Type A", "Aloha Homes — Type B Villa"]


def test_a_repeated_title_inside_a_project_gets_its_phase_group():
    offers = adapt_cyprus_catalog([project([unit("a", "Phase I", "Aloha Homes – Type A"), unit("a", "Phase II", "Aloha Homes – Type A")])]).offers
    assert [o.fields["offer_title"] for o in offers] == ["Aloha Homes – Type A — Phase I", "Aloha Homes – Type A — Phase II"]


@pytest.mark.parametrize("price", [None, 0, -5, "SOLD OUT", True])
def test_no_numeric_price_means_no_price_and_no_currency(price):
    fields = adapt_cyprus_catalog([project([unit(price=price)])]).offers[0].fields
    assert fields.get("price_value") is None and fields.get("price_currency") is None


def test_missing_source_currency_is_not_guessed():
    assert adapt_cyprus_catalog([project([unit(currency=None)])]).offers[0].fields.get("price_currency") is None


def test_source_net_area_is_publication_area_and_gross_area_stays_separate():
    offer = adapt_cyprus_catalog([project()]).offers[0]
    assert offer.fields["area_total_m2"] == offer.fields["area_net_m2"] == 105
    assert offer.fields["area_gross_m2"] == 128


def test_missing_net_area_does_not_fall_back_to_gross_area():
    fields = adapt_cyprus_catalog([project([unit(net_area_m2=None, gross_area_m2=128)])]).offers[0].fields

    assert "area_total_m2" not in fields
    assert "area_net_m2" not in fields
    assert fields["area_gross_m2"] == 128


def test_exact_bedroom_and_bathroom_features_are_mapped_conservatively():
    fields = adapt_cyprus_catalog([project([unit(features=[
        " 3 bedrooms ", "2 Bathrooms", "Living room", "3 Bedrooms",
    ])])]).offers[0].fields
    conflict = adapt_cyprus_catalog([project([unit(features=["2 Bedrooms", "3 Bedrooms", "2 Bathrooms"])])]).offers[0].fields
    unrelated = adapt_cyprus_catalog([project([unit(features=["Bedroom views", "Living room", "Bathrooms nearby"])])]).offers[0].fields

    assert fields["bedrooms_count"] == 3 and fields["bathrooms_count"] == 2
    assert "bedrooms_count" not in conflict and conflict["bathrooms_count"] == 2
    assert "bedrooms_count" not in unrelated and "bathrooms_count" not in unrelated


@pytest.mark.parametrize(("source_unit", "expected"), [
    (unit(title="Aloha Apartments - Type A"), "191"),
    (unit(title="Aloha Studio - Type A"), "191"),
    (unit(title="Aloha Penthouse - Type A"), "191"),
    (unit(title="Aloha Loft - Type A"), "191"),
    (unit(title="Aloha Villas - Type A"), "192"),
    (unit(title="Aloha Detached Villa - Type A"), "192"),
    (unit(title="Aloha Eco House - Type A"), "192"),
])
def test_category_is_derived_from_concrete_unit_type_semantics(source_unit, expected):
    fields = adapt_cyprus_catalog([project([source_unit])]).offers[0].fields

    assert fields["category_id_domiporta"] == expected


def test_mixed_project_can_classify_apartments_and_villas_independently():
    offers = adapt_cyprus_catalog([project([
        unit("apt", title="Aloha Studio - Type A"),
        unit("villa", title="Aloha Villa - Type B"),
    ])]).offers

    assert [offer.fields["category_id_domiporta"] for offer in offers] == ["191", "192"]


def test_strong_unit_identity_beats_conflicting_description_for_mykonos_type_c():
    fields = adapt_cyprus_catalog([project([unit(
        external_id="type-c-villas",
        title="Mykonos Villas - Type C",
        description="A limited apartment collection with spacious apartments.",
    )])]).offers[0].fields

    assert fields["category_id_domiporta"] == "192"


def test_idyll_homes_type_a_uses_apartment_semantics_not_homes_branding():
    fields = adapt_cyprus_catalog([project([unit(
        external_id="type-a",
        group=None,
        title="Idyll Homes - Type A",
        phase_title="Type A",
        description=(
            "Idyll Homes is an affordable luxury project in Esentepe. "
            "Idyll is comprised of a communal pool and 7 blocks of two-storey apartments, "
            "which include 1+1 and 2+1 ground floor apartments/penthouses."
        ),
        features=["3 Bedrooms", "2 Bathrooms", "Private Garden", "Pool Access"],
    )], url="https://www.cyprusconstructions.com/pl/Idyll_Homes", name="Idyll Homes")]).offers[0].fields

    assert fields["category_id_domiporta"] == "191"


@pytest.mark.parametrize("source_unit", [
    unit(title="Aloha Homes - Type A", phase_title="Type A", description="About it."),
    unit(title="Bahamas Homes - Type A", phase_title="Type A", description="About it."),
    unit(title="Hawaii Homes - Type A", phase_title="Type A", description="About it."),
    unit(title="Maldives Homes - Type A", phase_title="Type A", description="About it."),
    unit(title="Mykonos Homes - Type A", phase_title="Type A", description="About it."),
    unit(title="Aloha Homes - Type A", phase_title="Type A", description="Detached villa and studio apartment."),
    unit(title="Aloha Studio Villa - Type A", phase_title="Type A", description="About it."),
])
def test_ambiguous_or_conflicting_category_evidence_stays_empty(source_unit):
    fields = adapt_cyprus_catalog([project([source_unit])]).offers[0].fields

    assert "category_id_domiporta" not in fields


def test_location_comes_from_json_ld_and_is_absent_without_it():
    offer = adapt_cyprus_catalog([project(locality=None, region=None)]).offers[0]
    assert offer.fields.get("source_city_name") is None and offer.fields.get("source_region_name") is None
    for forbidden in ("source_country_name", "source_country_code", "market_type_normalized", "offer_type_normalized",
                      "category_id_domiporta", "rooms_count", "bathrooms_count", "floor", "is_active"):
        assert forbidden not in offer.fields or offer.fields[forbidden] is None


def test_images_keep_order_dedupe_exactly_and_empty_is_none_information():
    dup = unit(image_src="https://cc.test/a.jpg", gallery=["https://cc.test/b.jpg", "https://cc.test/a.jpg", "https://cc.test/B.jpg"], floor_plan_image=None)
    assert list(adapt_cyprus_catalog([project([dup])]).offers[0].images) == ["https://cc.test/a.jpg", "https://cc.test/b.jpg", "https://cc.test/B.jpg"]
    none = unit(image_src=None, gallery=[], floor_plan_image=None)
    assert not adapt_cyprus_catalog([project([none])]).offers[0].images


def test_no_features_is_no_information_and_status_texts_never_leak_in():
    offer = adapt_cyprus_catalog([project([unit(features=[])])]).offers[0]
    assert not offer.features


# ---------------------------------------------------------------------------
# Phuket, errors, report
# ---------------------------------------------------------------------------


def test_phuket_yields_eight_distinct_offers(monkeypatch):
    catalog = adapt_cyprus_catalog([phuket_detail(monkeypatch)])

    assert (catalog.report.projects_discovered, catalog.report.units_discovered, catalog.report.offers_adapted) == (1, 8, 8)
    assert catalog.developments[0].name == "Phuket Health and Wellness Resort" and catalog.developments[0].source_key == "phuket_h&w_resort"
    refs = [o.source_offer_ref for o in catalog.offers]
    assert len(set(refs)) == 8 and len({o.source_url for o in catalog.offers}) == 8
    assert {decode_unit_type_ref(r)[1:] for r in refs} >= {("Phase II", "type-a"), ("Phase II", "type-A"), ("Phase I", "type-a")}
    assert len({o.fields["offer_title"] for o in catalog.offers}) == 8


def test_no_reliable_name_is_an_error_and_nothing_is_invented():
    catalog = adapt_cyprus_catalog([project(name=None), project(url="https://x.test/pl/Ok", name="Ok Homes")])

    assert [d.source_key for d in catalog.developments] == ["ok"]
    (error,) = catalog.report.errors
    assert error.project_slug == "aloha_homes" and "name" in error.reason
    assert (catalog.report.projects_discovered, catalog.report.units_discovered, catalog.report.developments_adapted) == (2, 2, 1)


def test_duplicate_identity_is_an_error_and_the_first_wins():
    catalog = adapt_cyprus_catalog([project([unit("a", "Phase I", "Aloha Homes A"), unit("a", "Phase I", "Aloha Homes A copy"), unit("a", "Phase II", "Aloha Homes A2")])])

    assert catalog.report.offers_adapted == 2 and catalog.report.error_count == 1
    error = catalog.report.errors[0]
    assert (error.project_slug, error.phase_group_key, error.external_id, error.title) == ("aloha_homes", "Phase I", "a", "Aloha Homes A copy")
    assert "Duplicate" in error.reason


def test_a_duplicate_project_slug_across_the_catalog_is_an_error():
    catalog = adapt_cyprus_catalog([project(), project()])
    assert catalog.report.developments_adapted == 1 and catalog.report.error_count == 1


def test_a_bad_unit_does_not_stop_its_siblings_or_other_projects():
    bad = [unit("ok", title="Aloha Homes ok"), unit("", title="Aloha Homes no id"), unit("t", title=""), "junk"]
    catalog = adapt_cyprus_catalog([project(bad), project([unit()], url="https://x.test/pl/Other", name="Other")])

    assert catalog.report.offers_adapted == 2 and catalog.report.error_count == 3
    assert (catalog.report.units_discovered, catalog.report.developments_adapted) == (5, 2)


def test_a_project_whose_units_all_fail_produces_no_development():
    catalog = adapt_cyprus_catalog([project([unit("", title="x")])])
    assert catalog.developments == [] and catalog.report.error_count == 1


def test_the_adapter_does_not_mutate_its_input():
    details = [project()]
    snapshot = copy.deepcopy(details)
    adapt_cyprus_catalog(details)
    assert details == snapshot


def test_adapter_module_is_pure():
    tree = ast.parse(pathlib.Path(cyprus.__file__).read_text(encoding="utf-8"))
    imported = {(n.module or "").split(".")[0] if isinstance(n, ast.ImportFrom) else a.name.split(".")[0]
                for n in ast.walk(tree) for a in (n.names if isinstance(n, ast.Import) else [None]) if isinstance(n, ast.Import) or isinstance(n, ast.ImportFrom)}
    assert imported <= {"__future__", "json", "re", "dataclasses", "typing", "urllib", "InvestmentManager"}
    assert not any(isinstance(n, ast.ImportFrom) and n.module and ("store" in n.module or n.module == "InvestmentManager.foreign_sync") for n in ast.walk(tree))


# ---------------------------------------------------------------------------
# Adapter -> generic sync
# ---------------------------------------------------------------------------


def sync(details):
    adapted = adapt_cyprus_catalog(details)
    run = store.create_foreign_sync_run(P)
    return sync_records(P, adapted.developments, adapted.offers, run_id=run["id"])


def blocking(db_path):
    return {r["warning_code"] for r in query(db_path, "SELECT warning_code FROM foreign_offer_export_warnings WHERE is_blocking = 1")}


def test_first_sync_creates_development_and_offer_with_only_source_facts(fresh_db):
    report = sync([project()])

    assert (report.new_count, report.error_count) == (1, 0)
    development = store.find_foreign_development_by_source(P, "aloha_homes")
    row = offer_row(fresh_db, encode_unit_type_ref("aloha_homes", "Phase I", "type-a"), P)
    assert development["name"] == "Aloha Homes" and row["development_id"] == development["id"]
    assert (row["price_value"], row["price_currency"], row["source_city_name"]) == (191025, "GBP", "Esentepe")
    assert (row["area_total_m2"], row["area_net_m2"], row["area_gross_m2"], row["bedrooms_count"]) == (105, 105, 128, 3)
    for empty in ("floor", "rooms_count", "bathrooms_count", "source_country_name",
                  "market_type_normalized", "offer_type_normalized", "category_id_domiporta"):
        assert row[empty] is None, empty
    assert row["is_active"] == 1
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offer_images WHERE foreign_offer_id = ?", row["id"])[0]["n"] == 4


def test_cyprus_net_area_satisfies_the_missing_area_validator(fresh_db):
    sync([project()])
    row = offer_row(fresh_db, encode_unit_type_ref("aloha_homes", "Phase I", "type-a"), P)

    assert row["is_export_ready"] == 0
    assert blocking(fresh_db) == {"missing_country_name", "missing_market_type", "missing_category_id_domiporta"}

    result = update_foreign_offer_fields(row["id"], {"source_country_name": "Cyprus", "market_type_normalized": "primary",
                                                     "category_id_domiporta": "191"})
    assert result["is_export_ready"] is True


def test_classified_cyprus_offer_has_no_missing_category_warning(fresh_db):
    sync([project([unit(title="Aloha Villas - Type A")])])

    assert blocking(fresh_db) == {"missing_country_name", "missing_market_type"}


def test_a_sold_out_offer_without_price_is_flagged_missing_price(fresh_db):
    sync([project([unit(price=None, currency=None)])])
    assert "missing_price" in blocking(fresh_db)


def test_second_identical_sync_is_unchanged_and_creates_nothing(fresh_db):
    sync([project()])
    report = sync([project()])

    assert (report.new_count, report.updated_count, report.unchanged_count) == (0, 0, 1)
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offers")[0]["n"] == 1


def test_source_change_propagates_but_a_manual_edit_and_development_name_survive(fresh_db):
    sync([project()])
    ref = encode_unit_type_ref("aloha_homes", "Phase I", "type-a")
    update_foreign_offer_fields(offer_row(fresh_db, ref, P)["id"], {"offer_title": "Ręczny tytuł"})
    development = store.find_foreign_development_by_source(P, "aloha_homes")

    report = sync([project([unit(price=200000, title="Aloha Homes – Type A renamed")], name="Aloha Homes Renamed")])

    row = offer_row(fresh_db, ref, P)
    assert (row["price_value"], row["offer_title"]) == (200000, "Ręczny tytuł")
    assert store.find_foreign_development_by_source(P, "aloha_homes")["name"] == development["name"] == "Aloha Homes"
    assert report.updated_count == 1


def test_net_and_gross_area_update_when_source_owned_but_total_area_survives_manual_value(fresh_db):
    sync([project()])
    ref = encode_unit_type_ref("aloha_homes", "Phase I", "type-a")

    report = sync([project([unit(net_area_m2=106, gross_area_m2=130)])])
    row = offer_row(fresh_db, ref, P)
    assert (row["area_total_m2"], row["area_net_m2"], row["area_gross_m2"]) == (106, 106, 130)
    assert report.updated_count == 1

    row = offer_row(fresh_db, ref, P)
    update_foreign_offer_fields(row["id"], {"area_total_m2": 111})

    report = sync([project([unit(net_area_m2=107, gross_area_m2=131)])])

    row = offer_row(fresh_db, ref, P)
    assert (row["area_total_m2"], row["area_net_m2"], row["area_gross_m2"]) == (111, 107, 131)
    assert [(p.field, p.reason) for p in report.offers[0].plan.preserved] == [("area_total_m2", "manual")]
    assert report.updated_count == 1


def test_category_updates_from_source_but_manual_category_survives(fresh_db):
    sync([project([unit(title="Aloha Studio - Type A")])])
    ref = encode_unit_type_ref("aloha_homes", "Phase I", "type-a")
    row = offer_row(fresh_db, ref, P)
    assert row["category_id_domiporta"] == "191"

    report = sync([project([unit(title="Aloha Villa - Type A")])])
    row = offer_row(fresh_db, ref, P)
    assert row["category_id_domiporta"] == "192"
    assert report.updated_count == 1

    update_foreign_offer_fields(row["id"], {"category_id_domiporta": "191"})
    report = sync([project([unit(title="Aloha Villas - Type A")])])

    row = offer_row(fresh_db, ref, P)
    assert row["category_id_domiporta"] == "191"
    assert report.updated_count == 1

    report = sync([project([unit(title="Aloha Homes - Type A", phase_title="Type A", description="About it.")])])
    row = offer_row(fresh_db, ref, P)
    assert row["category_id_domiporta"] == "191"
    assert report.updated_count == 1


def test_source_owned_category_recovers_from_house_to_apartment(fresh_db):
    sync([project([unit(title="Aloha Villa - Type A")])])
    ref = encode_unit_type_ref("aloha_homes", "Phase I", "type-a")
    row = offer_row(fresh_db, ref, P)
    assert row["category_id_domiporta"] == "192"

    report = sync([project([unit(
        title="Idyll Homes - Type A",
        phase_title="Type A",
        description="Two-storey apartments with ground floor apartments/penthouses.",
    )])])

    row = offer_row(fresh_db, ref, P)
    assert row["category_id_domiporta"] == "191"
    assert report.updated_count == 1


def test_missing_source_net_area_does_not_erase_manual_total_area(fresh_db):
    sync([project()])
    ref = encode_unit_type_ref("aloha_homes", "Phase I", "type-a")
    row = offer_row(fresh_db, ref, P)
    update_foreign_offer_fields(row["id"], {"area_total_m2": 111})

    report = sync([project([unit(net_area_m2=None, gross_area_m2=130)])])

    row = offer_row(fresh_db, ref, P)
    assert (row["area_total_m2"], row["area_net_m2"], row["area_gross_m2"]) == (111, 105, 130)
    assert report.updated_count == 1


def test_availability_or_status_change_changes_nothing(fresh_db):
    sync([project()])
    before = offer_row(fresh_db, encode_unit_type_ref("aloha_homes", "Phase I", "type-a"), P)

    report = sync([project([unit(status="Sold Out", availability_text="0 units available", available_units=0, installments="x")])])

    assert report.unchanged_count == 1
    assert offer_row(fresh_db, encode_unit_type_ref("aloha_homes", "Phase I", "type-a"), P)["is_active"] == before["is_active"] == 1


def test_a_changed_project_url_with_the_same_identity_creates_no_duplicate(fresh_db):
    sync([project()])
    first = offer_row(fresh_db, encode_unit_type_ref("aloha_homes", "Phase I", "type-a"), P)["source_url"]

    report = sync([project(url="https://www.cyprusconstructions.com/en/Aloha_Homes")])

    assert report.new_count == 0 and report.error_count == 0
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offers")[0]["n"] == 1
    assert offer_row(fresh_db, encode_unit_type_ref("aloha_homes", "Phase I", "type-a"), P)["source_url"] == first


def test_phuket_becomes_eight_distinct_offers_in_one_development(fresh_db, monkeypatch):
    report = sync([phuket_detail(monkeypatch)])

    assert (report.new_count, report.error_count) == (8, 0)
    assert query(fresh_db, "SELECT COUNT(DISTINCT source_offer_ref) AS n, COUNT(DISTINCT source_url) AS u FROM foreign_offers")[0] == {"n": 8, "u": 8} \
        or tuple(query(fresh_db, "SELECT COUNT(DISTINCT source_offer_ref) AS n, COUNT(DISTINCT source_url) AS u FROM foreign_offers")[0].values()) == (8, 8)
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_developments WHERE source_platform = ?", P)[0]["n"] == 1
