"""SYNC-2B: the generic sync service against a real (throwaway) SQLite database.

Records are hand-built SyncDevelopment / SyncOffer objects: no adapter, no
scraper, no network. Every test runs on a foreign_offers.db under tmp_path.
"""
import json
import sqlite3

import pytest

import InvestmentManager.foreign_offers_importer as importer
import InvestmentManager.foreign_offers_store as store
from InvestmentManager.foreign_sync import sync_records
from InvestmentManager.foreign_sync_merge import SourceIdentity, SyncContractError, SyncDevelopment, SyncOffer
from tests.investmentmanager.test_foreign_developments import (  # noqa: F401  (fixtures)
    _raw_connect,
    _snapshot_all,
    foreign_db,
    fresh_db,
    legacy_db,
)
from tests.investmentmanager.test_foreign_offer_floor import URL as TRIPINVEST_URL
from tests.investmentmanager.test_foreign_offer_floor import _FakeTripinvestConnector

P = "testsrc"  # any provider other than tripinvest


def dev(key="p1", name="Laya Courtyard", platform=P):
    return SyncDevelopment(platform, key, name)


def offer(ref="1", *, platform=P, development="p1", url=None, images=None, features=None, **fields):
    return SyncOffer(
        platform, ref, url or f"https://src.example/{ref}",
        development=SourceIdentity(platform, development) if development else None,
        fields=fields, images=images, features=features,
    )


def run_sync(devs, offers, platform=P, **kwargs):
    run = store.create_foreign_sync_run(platform)
    return sync_records(platform, devs, offers, run_id=run["id"], **kwargs), run["id"]


def query(db_path, sql, *params):
    conn = _raw_connect(db_path)
    try:
        return [dict(row) for row in conn.execute(sql, params)]
    finally:
        conn.close()


def offer_row(db_path, ref="1", platform=P):
    rows = query(db_path, "SELECT * FROM foreign_offers WHERE source_platform = ? AND source_offer_ref = ?", platform, ref)
    return rows[0] if rows else None


def execute(db_path, sql, *params):
    conn = _raw_connect(db_path)
    conn.execute(sql, params)
    conn.commit()
    conn.close()


def images_of(db_path, offer_id):
    return [r["image_url"] for r in query(db_path, "SELECT image_url FROM foreign_offer_images WHERE foreign_offer_id = ? ORDER BY sort_order, id", offer_id)]


def features_of(db_path, offer_id):
    return [r["feature_text"] for r in query(db_path, "SELECT feature_text FROM foreign_offer_features_raw WHERE foreign_offer_id = ? ORDER BY id", offer_id)]


def full_dump(db_path):
    conn = _raw_connect(db_path)
    try:
        tables = [r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")]
        return {t: [tuple(r) for r in conn.execute(f"SELECT * FROM {t} ORDER BY 1")] for t in tables}
    finally:
        conn.close()


BASE_FIELDS = dict(
    offer_title="Laya Courtyard at Dubai Studio City", price_value=699000, price_currency="AED",
    latitude=25.036, longitude=55.232, source_country_code="AE", market_type_normalized="primary",
)


# ---------------------------------------------------------------------------
# Migration
# ---------------------------------------------------------------------------


def test_fresh_database_has_the_sync_merge_columns(fresh_db):
    columns = {r["name"] for r in query(fresh_db, "PRAGMA table_info(foreign_offers)")}
    log_columns = {r["name"]: r for r in query(fresh_db, "PRAGMA table_info(foreign_offer_sync_log)")}
    assert "source_values_json" in columns
    assert "sync_run_id" in log_columns and log_columns["sync_run_id"]["notnull"] == 0


def test_legacy_database_migrates_and_keeps_its_rows(legacy_db):
    before = _snapshot_all(legacy_db)

    store.initialize_foreign_offers_db()
    store.initialize_foreign_offers_db()

    from tests.investmentmanager.foreign_revision_assertions import assert_guard_install_only
    assert_guard_install_only(before,_snapshot_all(legacy_db))
    assert "source_values_json" in {r["name"] for r in query(legacy_db, "PRAGMA table_info(foreign_offers)")}
    assert query(legacy_db, "SELECT COUNT(*) AS n FROM foreign_offers WHERE source_values_json IS NOT NULL")[0]["n"] == 0


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


def test_first_sync_creates_development_and_offer_with_identity_and_observed_values(fresh_db):
    report, run_id = run_sync(
        [dev()], [offer("26161", images=["u1", "u2"], features=["Pool"], **BASE_FIELDS)]
    )

    assert (report.discovered_count, report.new_count, report.updated_count, report.unchanged_count,
            report.missing_count, report.error_count) == (1, 1, 0, 0, 0, 0)
    development = store.find_foreign_development_by_source(P, "p1")
    assert development["name"] == "Laya Courtyard"
    row = offer_row(fresh_db, "26161")
    assert row["development_id"] == development["id"]
    assert (row["offer_title"], row["price_value"], row["latitude"]) == (BASE_FIELDS["offer_title"], 699000, 25.036)
    assert (row["is_active"], row["is_export_ready"], row["needs_update"]) == (1, 0, 0)
    assert row["last_sync_run_id"] == run_id and row["last_source_sync_at"] and row["source_payload_hash"]
    assert images_of(fresh_db, row["id"]) == ["u1", "u2"]
    assert query(fresh_db, "SELECT is_primary FROM foreign_offer_images WHERE foreign_offer_id = ? ORDER BY sort_order", row["id"]) == [
        {"is_primary": 1}, {"is_primary": 0}]
    assert features_of(fresh_db, row["id"]) == ["Pool"]
    assert {r["portal_key"] for r in query(fresh_db, "SELECT portal_key FROM foreign_offer_portal_sync WHERE foreign_offer_id = ?", row["id"])} == {"domiporta", "tabelaofert"}

    observed = json.loads(row["source_values_json"])
    assert set(observed) == {"v", "fields", "images", "features", "development_assigned"}
    assert observed["development_assigned"] is True and observed["images"] == ["u1", "u2"]
    assert observed["fields"]["price_value"] == 699000  # values only, no raw payload

    finished = store.get_foreign_sync_run(run_id)
    assert finished["status"] == "completed" and finished["finished_at"]
    assert (finished["discovered_count"], finished["new_count"], finished["missing_count"], finished["error_count"]) == (1, 1, 0, 0)


def test_created_incomplete_offer_is_judged_by_the_validator_and_is_not_ready(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])  # no images, category, area, city or country name

    row = offer_row(fresh_db)
    warnings = {w["warning_code"]: w["is_blocking"] for w in query(fresh_db, "SELECT warning_code, is_blocking FROM foreign_offer_export_warnings")}
    assert row["is_export_ready"] == 0
    assert {code for code, blocking in warnings.items() if blocking} == {
        "missing_images", "missing_category_id_domiporta", "missing_city_name", "missing_area",
        "missing_country_name",
    }


# ---------------------------------------------------------------------------
# Second sync: unchanged / updated
# ---------------------------------------------------------------------------


def test_identical_second_sync_is_unchanged_and_writes_no_business_data(fresh_db):
    records = ([dev()], [offer("1", images=["u1"], features=["Pool"], **BASE_FIELDS)])
    run_sync(*records)
    execute(fresh_db, "UPDATE foreign_offers SET last_source_change_at = 'SENTINEL'")
    before = offer_row(fresh_db)

    report, run_id = run_sync(*records)

    after = offer_row(fresh_db)
    assert (report.new_count, report.updated_count, report.unchanged_count) == (0, 0, 1)
    assert after["last_source_change_at"] == "SENTINEL"  # the source did not change
    assert after["last_sync_run_id"] == run_id and after["last_sync_run_id"] != before["last_sync_run_id"]
    for column in ("offer_title", "price_value", "source_values_json", "source_payload_hash", "needs_update", "is_active"):
        assert after[column] == before[column]
    logs = query(fresh_db, "SELECT change_detected, sync_run_id FROM foreign_offer_sync_log ORDER BY id")
    assert [entry["change_detected"] for entry in logs] == [1, 0]


def test_changed_source_field_updates_the_offer(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    execute(fresh_db, "UPDATE foreign_offers SET last_source_change_at = 'SENTINEL'")
    first_hash = offer_row(fresh_db)["source_payload_hash"]

    report, _ = run_sync([dev()], [offer("1", **{**BASE_FIELDS, "price_value": 750000})])

    row = offer_row(fresh_db)
    assert (report.updated_count, report.unchanged_count) == (1, 0)
    assert row["price_value"] == 750000
    assert row["source_payload_hash"] != first_hash and row["last_source_change_at"] != "SENTINEL"
    assert json.loads(row["source_values_json"])["fields"]["price_value"] == 750000
    summary = json.loads(query(fresh_db, "SELECT summary FROM foreign_offer_sync_log ORDER BY id DESC LIMIT 1")[0]["summary"])
    assert summary["applied"] == ["price_value"] and summary["action"] == "updated"


# ---------------------------------------------------------------------------
# Manual ownership
# ---------------------------------------------------------------------------


def test_manual_db_edit_is_preserved_by_the_next_sync(fresh_db):
    run_sync([dev()], [offer("1", area_total_m2=80, **BASE_FIELDS)])
    execute(fresh_db, "UPDATE foreign_offers SET area_total_m2 = 82, offer_title = 'Better title'")

    unchanged_source, _ = run_sync([dev()], [offer("1", area_total_m2=80, **BASE_FIELDS)])
    moved_source, _ = run_sync([dev()], [offer("1", area_total_m2=85, **{**BASE_FIELDS, "offer_title": "Source title 2"})])

    row = offer_row(fresh_db)
    assert (row["area_total_m2"], row["offer_title"]) == (82, "Better title")
    assert unchanged_source.unchanged_count == 1 and moved_source.unchanged_count == 1
    preserved = {p.field: p.reason for p in moved_source.offers[0].plan.preserved}
    assert preserved == {"area_total_m2": "manual", "offer_title": "manual"}
    summary = json.loads(query(fresh_db, "SELECT summary FROM foreign_offer_sync_log ORDER BY id DESC LIMIT 1")[0]["summary"])
    assert {p["field"] for p in summary["preserved"]} == {"area_total_m2", "offer_title"}
    assert json.loads(row["source_values_json"])["fields"]["area_total_m2"] == 85  # observed follows the source


def test_source_null_never_erases_a_crm_value_or_the_observed_value(fresh_db):
    run_sync([dev()], [offer("1", area_total_m2=None, **BASE_FIELDS)])
    execute(fresh_db, "UPDATE foreign_offers SET area_total_m2 = 82")  # user fills what the source lacks

    run_sync([dev()], [offer("1", area_total_m2=None, **{k: v for k, v in BASE_FIELDS.items() if k != "price_value"})])

    row = offer_row(fresh_db)
    assert row["area_total_m2"] == 82 and row["price_value"] == 699000
    observed = json.loads(row["source_values_json"])["fields"]
    assert "area_total_m2" not in observed and observed["price_value"] == 699000


def test_floor_follows_the_source_and_floor_override_is_never_written(fresh_db):
    run_sync([dev()], [offer("1", floor=2, **BASE_FIELDS)])
    execute(fresh_db, "UPDATE foreign_offers SET floor_override = 7")

    run_sync([dev()], [offer("1", floor=3, **BASE_FIELDS)])
    assert (offer_row(fresh_db)["floor"], offer_row(fresh_db)["floor_override"]) == (3, 7)

    run_sync([dev()], [offer("1", floor=None, **BASE_FIELDS)])  # NULL never clears
    assert (offer_row(fresh_db)["floor"], offer_row(fresh_db)["floor_override"]) == (3, 7)


def test_is_active_is_never_touched_but_last_seen_is_recorded(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    execute(fresh_db, "UPDATE foreign_offers SET is_active = 0, last_source_sync_at = 'OLD'")

    _, run_id = run_sync([dev()], [offer("1", **BASE_FIELDS)])

    row = offer_row(fresh_db)
    assert row["is_active"] == 0
    assert row["last_source_sync_at"] != "OLD" and row["last_sync_run_id"] == run_id


def test_unreadable_source_values_json_is_non_destructive_and_gets_rewritten(fresh_db):
    run_sync([dev()], [offer("1", area_total_m2=None, **BASE_FIELDS)])
    execute(fresh_db, "UPDATE foreign_offers SET source_values_json = '{broken', offer_title = 'Manual', development_id = NULL")

    report, _ = run_sync([dev()], [offer("1", area_total_m2=82, **{**BASE_FIELDS, "offer_title": "Source"})])

    row = offer_row(fresh_db)
    assert row["offer_title"] == "Manual" and row["area_total_m2"] == 82  # only the NULL was filled
    assert row["development_id"] is None  # not re-assigned from unreadable history
    assert report.offers[0].plan.observed_corrupt is True
    assert json.loads(row["source_values_json"])["v"] == 1  # healed
    assert json.loads(query(fresh_db, "SELECT summary FROM foreign_offer_sync_log ORDER BY id DESC LIMIT 1")[0]["summary"])["observed_corrupt"] is True


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


def test_crm_rename_of_a_source_development_survives_the_next_sync(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    development = store.find_foreign_development_by_source(P, "p1")
    store.rename_foreign_development(development["id"], "Laya - Studio City")

    report, _ = run_sync([dev(name="Laya Courtyard (source renamed)")], [offer("1", **BASE_FIELDS)])

    after = store.find_foreign_development_by_source(P, "p1")
    assert after["id"] == development["id"] and after["name"] == "Laya - Studio City"
    assert report.developments[0].status == "existing"
    assert offer_row(fresh_db)["development_id"] == development["id"]


def test_name_collision_is_reported_and_never_adopted(fresh_db):
    manual = store.create_foreign_development("Laya Courtyard")

    report, _ = run_sync([dev(name="laya courtyard")], [offer("1", **BASE_FIELDS)])

    conflict = report.developments[0]
    assert conflict.status == "name_conflict"
    assert conflict.conflict_with["id"] == manual["id"] and conflict.conflict_with["source_platform"] is None
    assert report.development_conflicts == [conflict]
    assert [d["name"] for d in store.list_foreign_developments()] == ["Laya Courtyard"]  # nothing created, renamed or suffixed
    assert store.find_foreign_development_by_source(P, "p1") is None
    assert query(fresh_db, "SELECT source_platform, source_key FROM foreign_developments") == [{"source_platform": None, "source_key": None}]
    assert offer_row(fresh_db)["development_id"] is None  # the offer exists without a development
    assert report.new_count == 1
    summary = json.loads(query(fresh_db, "SELECT summary FROM foreign_offer_sync_log")[0]["summary"])
    assert summary["development"] == "name_conflict"


def test_offer_gets_its_development_once_the_name_conflict_is_resolved_in_the_crm(fresh_db):
    manual = store.create_foreign_development("Laya Courtyard")
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    store.rename_foreign_development(manual["id"], "Laya Courtyard (old)")

    report, _ = run_sync([dev()], [offer("1", **BASE_FIELDS)])

    created = store.find_foreign_development_by_source(P, "p1")
    assert created["name"] == "Laya Courtyard" and created["id"] != manual["id"]
    assert offer_row(fresh_db)["development_id"] == created["id"]
    assert report.updated_count == 1


def test_manual_development_assignment_and_detach_are_preserved(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS), offer("2", **BASE_FIELDS)])
    other = store.create_foreign_development("Chosen by the user")
    store.set_foreign_offer_development(offer_row(fresh_db, "1")["id"], other["id"])   # reassigned
    store.set_foreign_offer_development(offer_row(fresh_db, "2")["id"], None)          # detached

    run_sync([dev()], [offer("1", **BASE_FIELDS), offer("2", **BASE_FIELDS)])

    assert offer_row(fresh_db, "1")["development_id"] == other["id"]
    assert offer_row(fresh_db, "2")["development_id"] is None


# ---------------------------------------------------------------------------
# Images and features
# ---------------------------------------------------------------------------


def test_gallery_is_replaced_when_untouched_preserved_when_edited_and_never_cleared(fresh_db):
    run_sync([dev()], [offer("1", images=["a", "b"], **BASE_FIELDS)])
    offer_id = offer_row(fresh_db)["id"]

    run_sync([dev()], [offer("1", images=["a", "b", "c"], **BASE_FIELDS)])
    assert images_of(fresh_db, offer_id) == ["a", "b", "c"]

    run_sync([dev()], [offer("1", images=None, **BASE_FIELDS)])
    run_sync([dev()], [offer("1", images=[], **BASE_FIELDS)])
    assert images_of(fresh_db, offer_id) == ["a", "b", "c"]  # no information never clears
    assert json.loads(offer_row(fresh_db)["source_values_json"])["images"] == ["a", "b", "c"]

    execute(fresh_db, "DELETE FROM foreign_offer_images WHERE foreign_offer_id = ? AND image_url = 'b'", offer_id)  # manual change
    report, _ = run_sync([dev()], [offer("1", images=["a", "b", "c", "d"], **BASE_FIELDS)])
    assert images_of(fresh_db, offer_id) == ["a", "c"]
    assert report.offers[0].plan.images.action == "preserved" and report.unchanged_count == 1


def test_features_follow_the_same_policy(fresh_db):
    run_sync([dev()], [offer("1", features=["Pool", "Gym"], **BASE_FIELDS)])
    offer_id = offer_row(fresh_db)["id"]

    run_sync([dev()], [offer("1", features=["Pool", "Gym", "Sauna"], **BASE_FIELDS)])
    assert features_of(fresh_db, offer_id) == ["Pool", "Gym", "Sauna"]

    run_sync([dev()], [offer("1", features=[], **BASE_FIELDS)])
    assert features_of(fresh_db, offer_id) == ["Pool", "Gym", "Sauna"]

    execute(fresh_db, "INSERT INTO foreign_offer_features_raw (foreign_offer_id, feature_text) VALUES (?, 'Manual note')", offer_id)
    run_sync([dev()], [offer("1", features=["Pool"], **BASE_FIELDS)])
    assert features_of(fresh_db, offer_id) == ["Pool", "Gym", "Sauna", "Manual note"]


# ---------------------------------------------------------------------------
# needs_update (existing semantics only)
# ---------------------------------------------------------------------------


def _publish(db_path, offer_id):
    execute(db_path, "UPDATE foreign_offer_portal_sync SET is_published = 1 WHERE foreign_offer_id = ? AND portal_key = 'domiporta'", offer_id)


def test_needs_update_is_set_only_when_business_data_of_a_published_offer_changes(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    offer_id = offer_row(fresh_db)["id"]
    _publish(fresh_db, offer_id)

    run_sync([dev()], [offer("1", **BASE_FIELDS)])                                   # seen only
    assert offer_row(fresh_db)["needs_update"] == 0

    execute(fresh_db, "UPDATE foreign_offers SET price_value = 1")                    # manual edit...
    run_sync([dev()], [offer("1", **{**BASE_FIELDS, "price_value": 800000})])         # ...source moved: preserved
    assert offer_row(fresh_db)["needs_update"] == 0                                   # hash/observed changed, nothing exported changed

    run_sync([dev()], [offer("1", **{**BASE_FIELDS, "price_value": 800000, "offer_title": "New title"})])
    assert offer_row(fresh_db)["needs_update"] == 1
    portal = query(fresh_db, "SELECT needs_update FROM foreign_offer_portal_sync WHERE foreign_offer_id = ? AND portal_key = 'domiporta'", offer_id)
    assert portal == [{"needs_update": 1}]


def test_unpublished_offer_change_does_not_set_needs_update(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    run_sync([dev()], [offer("1", **{**BASE_FIELDS, "offer_title": "Changed"})])

    assert offer_row(fresh_db)["needs_update"] == 0
    assert query(fresh_db, "SELECT event_type FROM foreign_offer_portal_sync_events WHERE event_type NOT LIKE 'foreign_input_%'") == [{"event_type": "update_ignored_no_publication"}]


# ---------------------------------------------------------------------------
# Identity isolation
# ---------------------------------------------------------------------------


def test_same_key_and_ref_in_two_sources_are_independent(fresh_db):
    run_sync([dev("1", "Alpha", platform="src_a")], [offer("1", platform="src_a", development="1", offer_title="A")], platform="src_a")
    run_sync([dev("1", "Beta", platform="src_b")], [offer("1", platform="src_b", development="1", offer_title="B")], platform="src_b")
    before_a = offer_row(fresh_db, "1", "src_a")

    run_sync([dev("1", "Beta", platform="src_b")], [offer("1", platform="src_b", development="1", offer_title="B2")], platform="src_b")

    assert offer_row(fresh_db, "1", "src_a") == before_a  # another source's sync never touches it
    assert offer_row(fresh_db, "1", "src_b")["offer_title"] == "B2"
    assert store.find_foreign_development_by_source("src_a", "1")["name"] == "Alpha"
    assert store.find_foreign_development_by_source("src_b", "1")["name"] == "Beta"


def test_records_of_another_source_are_rejected_before_anything_is_written(fresh_db):
    run = store.create_foreign_sync_run(P)
    before = full_dump(fresh_db)

    with pytest.raises(SyncContractError):
        sync_records(P, [dev()], [offer("1", platform="other", development=None)], run_id=run["id"])
    with pytest.raises(SyncContractError):
        sync_records(P, [dev(platform="other")], [], run_id=run["id"])

    assert full_dump(fresh_db) == before


def test_ambiguous_identity_is_an_error_for_that_record_not_a_crash(fresh_db):
    conn = _raw_connect(fresh_db)
    for url in ("https://tripinvest.pl/oferta/a-1", "https://tripinvest.pl/oferta/b-1"):
        conn.execute("INSERT INTO foreign_offers (source_platform, source_url, source_offer_ref) VALUES ('tripinvest', ?, '1')", (url,))
    conn.commit()
    conn.close()

    report, _ = run_sync([], [offer("1", platform="tripinvest", development=None, offer_title="X")], platform="tripinvest")

    assert report.error_count == 1 and "More than one" in report.offers[0].error


# ---------------------------------------------------------------------------
# Runs
# ---------------------------------------------------------------------------


def test_run_counters_cover_new_updated_unchanged_and_error(fresh_db):
    run_sync([dev()], [offer("keep", **BASE_FIELDS), offer("change", **BASE_FIELDS)])

    report, run_id = run_sync(
        [dev()],
        [
            offer("keep", **BASE_FIELDS),
            offer("change", **{**BASE_FIELDS, "offer_title": "Changed"}),
            offer("brand-new", **BASE_FIELDS),
            offer("dup-url", url="https://src.example/keep", **BASE_FIELDS),  # UNIQUE(source_platform, source_url)
        ],
    )

    assert (report.discovered_count, report.new_count, report.updated_count, report.unchanged_count,
            report.missing_count, report.error_count) == (4, 1, 1, 1, 0, 1)
    run = store.get_foreign_sync_run(run_id)
    assert run["status"] == "completed"
    assert (run["discovered_count"], run["new_count"], run["updated_count"], run["unchanged_count"],
            run["missing_count"], run["error_count"]) == (4, 1, 1, 1, 0, 1)
    assert "dup-url" in run["error_message"]


def test_run_must_exist_belong_to_the_source_and_still_be_running(fresh_db):
    other_source = store.create_foreign_sync_run("another")
    finished = store.create_foreign_sync_run(P)
    store.finish_foreign_sync_run(finished["id"], "completed")

    with pytest.raises(ValueError, match="belongs to"):
        sync_records(P, [dev()], [offer("1")], run_id=other_source["id"])
    with pytest.raises(ValueError, match="not running"):
        sync_records(P, [dev()], [offer("1")], run_id=finished["id"])
    with pytest.raises(ValueError, match="does not exist"):
        sync_records(P, [dev()], [offer("1")], run_id=9999)
    with pytest.raises(ValueError, match="run_id is required"):
        sync_records(P, [dev()], [offer("1")])
    assert offer_row(fresh_db) is None and store.list_foreign_developments() == []


def test_the_caller_can_keep_the_run_open(fresh_db):
    run = store.create_foreign_sync_run(P)
    report = sync_records(P, [dev()], [offer("1", **BASE_FIELDS)], run_id=run["id"], finish_run=False)

    assert store.get_foreign_sync_run(run["id"])["status"] == "running"
    assert report.run_counts()["new_count"] == 1


def test_one_failing_record_does_not_roll_back_the_others(fresh_db):
    report, _ = run_sync(
        [dev()],
        [
            offer("ok-1", **BASE_FIELDS),
            offer("bad", url="https://src.example/ok-1", **BASE_FIELDS),   # violates UNIQUE(source_platform, source_url)
            offer("ok-2", **BASE_FIELDS),
        ],
    )

    assert [o.action for o in report.offers] == ["created", "error", "created"]
    assert offer_row(fresh_db, "ok-1") and offer_row(fresh_db, "ok-2") and offer_row(fresh_db, "bad") is None
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offer_sync_log")[0]["n"] == 2  # nothing half-written for "bad"
    assert (report.new_count, report.error_count) == (2, 1)


def test_duplicate_ref_in_one_batch_is_an_error_for_the_repeat(fresh_db):
    report, _ = run_sync([dev()], [offer("1", offer_title="first"), offer("1", offer_title="second")])

    assert [o.action for o in report.offers] == ["created", "error"]
    assert offer_row(fresh_db)["offer_title"] == "first"


# ---------------------------------------------------------------------------
# Dry run
# ---------------------------------------------------------------------------


def test_dry_run_reports_the_plan_and_writes_nothing(fresh_db):
    run_sync([dev("p1")], [offer("existing", images=["a"], **BASE_FIELDS)])
    execute(fresh_db, "UPDATE foreign_offers SET offer_title = 'Manual'")
    records = (
        [dev("p1"), dev("p2", "Second development")],
        [
            offer("existing", images=["a", "b"], **{**BASE_FIELDS, "offer_title": "Source 2", "price_value": 800000}),
            offer("fresh", development="p2", **BASE_FIELDS),
        ],
    )
    before = full_dump(fresh_db)

    dry = sync_records(P, *records, dry_run=True)  # no run row is needed (or created)

    assert full_dump(fresh_db) == before  # foreign_offers, developments, images, features, logs, runs: all identical
    assert [d.status for d in dry.developments] == ["existing", "would_create"]
    assert dry.developments[1].development_id is None
    assert [(o.action, o.foreign_offer_id is None) for o in dry.offers] == [("updated", False), ("created", True)]
    assert dry.offers[1].plan.development.action == "would_assign"
    assert (dry.new_count, dry.updated_count) == (1, 1)

    real, _ = run_sync(*records)
    assert [o.action for o in real.offers] == [o.action for o in dry.offers]
    assert [d.status for d in real.developments] == ["existing", "created"]
    assert offer_row(fresh_db, "existing")["offer_title"] == "Manual"  # and the real run keeps the manual value too


def test_dry_run_needs_no_run_and_never_touches_one(fresh_db):
    run = store.create_foreign_sync_run(P)

    sync_records(P, [dev()], [offer("1", **BASE_FIELDS)], run_id=run["id"], dry_run=True)
    sync_records(P, [dev()], [offer("1", **BASE_FIELDS)], dry_run=True)

    assert store.get_foreign_sync_run(run["id"])["status"] == "running"
    assert offer_row(fresh_db) is None


# ---------------------------------------------------------------------------
# Regression: TripInvest and the existing CRM store
# ---------------------------------------------------------------------------


def test_tripinvest_import_is_unaffected_by_the_generic_sync(fresh_db, monkeypatch):
    monkeypatch.setattr(importer, "TripinvestConnector", _FakeTripinvestConnector)
    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)
    trip_before = offer_row(fresh_db, "75156", "tripinvest")
    assert trip_before["source_values_json"]  # INV-FIX-003: TripInvest records its observed source values

    run_sync([dev()], [offer("75156", **BASE_FIELDS)])  # same ref, another source

    trip_after = offer_row(fresh_db, "75156", "tripinvest")
    assert trip_after == trip_before
    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)  # refresh still works
    refreshed = offer_row(fresh_db, "75156", "tripinvest")
    assert refreshed["source_values_json"] == trip_before["source_values_json"]  # identical source
    assert refreshed["development_id"] == trip_before["development_id"]


def _blocking_codes(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_later_syncs_that_fill_the_missing_values_clear_the_warnings_until_the_offer_is_ready(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])   # AED, no area / city / country / category / images
    assert offer_row(fresh_db)["is_export_ready"] == 0 and len(_blocking_codes(fresh_db)) == 5

    filled = {**BASE_FIELDS, "area_total_m2": 82, "source_city_name": "Dubai", "source_country_name": "UAE", "category_id_domiporta": "192"}
    run_sync([dev()], [offer("1", images=["https://img/1.jpg"], **filled)])
    assert _blocking_codes(fresh_db) == set()
    assert offer_row(fresh_db)["is_export_ready"] == 1


def test_arriving_images_remove_missing_images(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    assert "missing_images" in _blocking_codes(fresh_db)

    run_sync([dev()], [offer("1", images=["https://img/1.jpg"], **BASE_FIELDS)])

    assert "missing_images" not in _blocking_codes(fresh_db)


def test_a_bookkeeping_only_sync_does_not_recompute_readiness(fresh_db):
    records = ([dev()], [offer("1", images=["https://img/1.jpg"], **BASE_FIELDS)])
    run_sync(*records)
    execute(fresh_db, "DELETE FROM foreign_offer_export_warnings")     # a deliberately stale state
    execute(fresh_db, "UPDATE foreign_offers SET is_export_ready = 1")

    report, _ = run_sync(*records)                                        # nothing changed at the source

    assert report.unchanged_count == 1
    assert offer_row(fresh_db)["is_export_ready"] == 1
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offer_export_warnings")[0]["n"] == 0


def test_a_preserved_manual_value_is_what_the_validator_judges(fresh_db):
    run_sync([dev()], [offer("1", images=["https://img/1.jpg"], **{**BASE_FIELDS, "area_total_m2": 80})])
    execute(fresh_db, "UPDATE foreign_offers SET area_total_m2 = 0")   # a manual value that fails the area rule

    run_sync([dev()], [offer("1", images=["https://img/1.jpg"], **{**BASE_FIELDS, "area_total_m2": 90, "offer_title": "Changed"})])

    assert offer_row(fresh_db)["area_total_m2"] == 0   # the manual value survives...
    assert "missing_area" in _blocking_codes(fresh_db)  # ...and is judged as it is, not the source's 90


def _portal_events(db_path, offer_id):
    return query(db_path, "SELECT portal_key, event_type, payload_json FROM foreign_offer_portal_sync_events WHERE foreign_offer_id = ? AND event_type NOT LIKE 'foreign_input_%'", offer_id)


def test_tripinvest_refresh_of_a_published_offer_flags_needs_update_only_on_a_real_change(fresh_db, monkeypatch):
    monkeypatch.setattr(importer, "TripinvestConnector", _FakeTripinvestConnector)
    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)
    offer_id = offer_row(fresh_db, "75156", "tripinvest")["id"]
    _publish(fresh_db, offer_id)

    # INV-FIX-003: an identical refresh is not a source change (it used to flag the offer).
    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)
    assert offer_row(fresh_db, "75156", "tripinvest")["needs_update"] == 0
    assert _portal_events(fresh_db, offer_id) == []

    monkeypatch.setattr(_FakeTripinvestConnector, "title", "Nowy tytuł")
    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)

    assert offer_row(fresh_db, "75156", "tripinvest")["needs_update"] == 1
    assert query(fresh_db, "SELECT portal_key, needs_update FROM foreign_offer_portal_sync WHERE foreign_offer_id = ? ORDER BY portal_key", offer_id) == [
        {"portal_key": "domiporta", "needs_update": 1}, {"portal_key": "tabelaofert", "needs_update": 0}]
    event = _portal_events(fresh_db, offer_id)
    assert [(e["portal_key"], e["event_type"]) for e in event] == [("domiporta", "update_required")]
    assert json.loads(event[0]["payload_json"]) == {"reason": "foreign_offer_source_changed", "changed_fields": ["offer_title"]}


def test_tripinvest_refresh_of_an_unpublished_offer_only_logs_an_ignored_update(fresh_db, monkeypatch):
    monkeypatch.setattr(importer, "TripinvestConnector", _FakeTripinvestConnector)
    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)
    offer_id = offer_row(fresh_db, "75156", "tripinvest")["id"]

    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)  # identical: nothing to log (INV-FIX-003)
    assert _portal_events(fresh_db, offer_id) == []

    monkeypatch.setattr(_FakeTripinvestConnector, "title", "Nowy tytuł")
    importer.upsert_foreign_offer_from_tripinvest(TRIPINVEST_URL)

    assert offer_row(fresh_db, "75156", "tripinvest")["needs_update"] == 0
    event = _portal_events(fresh_db, offer_id)
    assert [(e["portal_key"], e["event_type"]) for e in event] == [(None, "update_ignored_no_publication")]
    assert json.loads(event[0]["payload_json"])["changed_fields"] == ["offer_title"]


def test_shared_needs_update_helper_returns_the_number_of_published_portals(fresh_db):
    run_sync([dev()], [offer("1", **BASE_FIELDS)])
    offer_id = offer_row(fresh_db)["id"]
    conn = store.open_foreign_offers_connection()
    try:
        assert store.mark_foreign_offer_requires_update(conn, offer_id, "why", ["x"]) == 0
        conn.execute("UPDATE foreign_offer_portal_sync SET is_published = 1 WHERE foreign_offer_id = ?", (offer_id,))
        assert store.mark_foreign_offer_requires_update(conn, offer_id, "why", ["x"]) == 2
        conn.commit()
    finally:
        conn.close()
    assert offer_row(fresh_db)["needs_update"] == 1


def test_crm_store_contract_is_unchanged_by_synced_offers(fresh_db):
    run_sync([dev()], [offer("1", images=["u"], features=["Pool"], **BASE_FIELDS)])

    items = store.list_foreign_offers()

    assert len(items) == 1 and items[0]["development_name"] == "Laya Courtyard"
    assert "source_values_json" not in items[0]
    assert items[0]["effective_floor"] is None and items[0]["images"][0]["image_url"] == "u"
