"""SYNC-1: additive persistence foundation for foreign source synchronization.

Covers source identity (developments and offers), sync run tracking and the
per-offer sync metadata, on fresh, pre-FD-1 and current (manual developments)
databases. Nothing here runs a scraper or a synchronizer: SYNC-1 only adds
storage, and it must not change how existing rows or importers behave.

Ownership note: source synchronization must preserve explicit CRM/manual
overrides. SYNC-1 defines no field ownership policy (that is SYNC-2); the
tests only prove that the new persistence writes nothing but its own fields.

Every test runs against a throwaway foreign_offers.db under tmp_path.
"""
import logging
import sqlite3

import pytest

import InvestmentManager.foreign_offers_importer as importer
import InvestmentManager.foreign_offers_store as store
from tests.investmentmanager.foreign_revision_assertions import assert_guard_install_only
from tests.investmentmanager.test_foreign_developments import (  # noqa: F401  (fixtures)
    LEGACY_SCHEMA,
    _raw_connect,
    _snapshot_all,
    foreign_db,
    fresh_db,
    legacy_db,
)
from tests.investmentmanager.test_foreign_offer_floor import URL, _FakeTripinvestConnector
from tests.investmentmanager.test_foreign_offer_floor_override import (
    _build_pre_floor2_database,
    _full_snapshot,
)

NEW_OFFER_COLUMNS = {"last_sync_run_id", "source_payload_hash", "area_net_m2", "area_gross_m2"}
NEW_DEVELOPMENT_COLUMNS = {"source_platform", "source_key"}


def _schema_fingerprint(db_path):
    conn = _raw_connect(db_path)
    try:
        return [
            tuple(row)
            for row in conn.execute("SELECT type, name, sql FROM sqlite_master ORDER BY type, name")
        ]
    finally:
        conn.close()


def _insert_offer(conn, platform, ref, url=None, **extra):
    columns = {"source_platform": platform, "source_offer_ref": ref, "source_url": url or f"https://{platform}.example/{ref}"}
    columns.update(extra)
    names = ", ".join(columns)
    marks = ", ".join("?" for _ in columns)
    cursor = conn.execute(f"INSERT INTO foreign_offers ({names}) VALUES ({marks})", tuple(columns.values()))
    return cursor.lastrowid


# ---------------------------------------------------------------------------
# Schema
# ---------------------------------------------------------------------------


def test_fresh_database_has_the_new_columns_tables_and_indexes(fresh_db):
    conn = _raw_connect(fresh_db)
    try:
        dev = {row[1]: row for row in conn.execute("PRAGMA table_info(foreign_developments)")}
        assert NEW_DEVELOPMENT_COLUMNS <= set(dev)
        assert all(dev[name][3] == 0 and dev[name][4] is None for name in NEW_DEVELOPMENT_COLUMNS)  # nullable, no default

        offer = {row[1]: row for row in conn.execute("PRAGMA table_info(foreign_offers)")}
        assert NEW_OFFER_COLUMNS <= set(offer)
        assert all(offer[name][3] == 0 and offer[name][4] is None for name in NEW_OFFER_COLUMNS)

        runs = {row[1]: row for row in conn.execute("PRAGMA table_info(foreign_sync_runs)")}
        assert set(runs) == {
            "id", "source_platform", "status", "started_at", "finished_at", "discovered_count",
            "new_count", "updated_count", "unchanged_count", "missing_count", "error_count", "error_message",
        }

        dev_indexes = {row[1]: row for row in conn.execute("PRAGMA index_list(foreign_developments)")}
        assert dev_indexes["ux_foreign_developments_source_identity"][2] == 1  # unique
        assert dev_indexes["ux_foreign_developments_source_identity"][4] == 1  # partial

        offer_indexes = {row[1]: row for row in conn.execute("PRAGMA index_list(foreign_offers)")}
        assert offer_indexes["ux_foreign_offers_source_identity"][2] == 1
        assert offer_indexes["ux_foreign_offers_source_identity"][4] == 1
        # what already existed is still there
        assert "idx_foreign_offers_source_offer_ref" in offer_indexes
        assert any(row[1] == "sqlite_autoindex_foreign_offers_1" for row in conn.execute("PRAGMA index_list(foreign_offers)"))

        fks = [tuple(row)[2:5] for row in conn.execute("PRAGMA foreign_key_list(foreign_offers)")]
        assert ("foreign_sync_runs", "last_sync_run_id", "id") in fks
        assert any(row[1] == "idx_foreign_sync_runs_source" for row in conn.execute("PRAGMA index_list(foreign_sync_runs)"))
    finally:
        conn.close()


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

    store.initialize_foreign_offers_db()

    assert_guard_install_only(before, _snapshot_all(legacy_db))
    conn = _raw_connect(legacy_db)
    try:
        offer_columns = {row[1] for row in conn.execute("PRAGMA table_info(foreign_offers)")}
        assert NEW_OFFER_COLUMNS <= offer_columns
        assert conn.execute(
            "SELECT COUNT(*) FROM foreign_offers WHERE last_sync_run_id IS NOT NULL OR source_payload_hash IS NOT NULL"
        ).fetchone()[0] == 0
    finally:
        conn.close()


def test_migration_is_idempotent(legacy_db):
    store.initialize_foreign_offers_db()
    once = _schema_fingerprint(legacy_db)

    store.initialize_foreign_offers_db()
    store.initialize_foreign_offers_db()

    assert _schema_fingerprint(legacy_db) == once


def test_current_database_with_manual_developments_upgrades_without_touching_them(foreign_db):
    foreign_db.parent.mkdir(parents=True, exist_ok=True)
    _build_pre_floor2_database(foreign_db)  # production shape: FD-1 schema, manual 'Azure Bay' assigned to offer 1
    before = _full_snapshot(foreign_db)

    store.initialize_foreign_offers_db()
    store.initialize_foreign_offers_db()

    assert_guard_install_only(before, _full_snapshot(foreign_db))
    assert store.list_foreign_developments() == [
        {"id": 1, "name": "Azure Bay", "created_at": store.list_foreign_developments()[0]["created_at"],
         "updated_at": store.list_foreign_developments()[0]["updated_at"]}
    ]
    conn = _raw_connect(foreign_db)
    try:
        row = conn.execute("SELECT source_platform, source_key FROM foreign_developments WHERE id = 1").fetchone()
        assert (row["source_platform"], row["source_key"]) == (None, None)  # never guessed from the name
        assert conn.execute("SELECT development_id FROM foreign_offers WHERE id = 1").fetchone()[0] == 1
    finally:
        conn.close()
    assert store.find_foreign_development_by_source("avarten", "26161") is None
    assert store.create_foreign_development("Second").get("id") == 2  # AUTOINCREMENT continues


def test_offer_identity_index_is_skipped_not_fatal_when_existing_rows_already_duplicate(fresh_db, caplog, monkeypatch):
    conn = _raw_connect(fresh_db)
    conn.execute("DROP INDEX ux_foreign_offers_source_identity")
    _insert_offer(conn, "avarten", "26161", url="https://a/1")
    _insert_offer(conn, "avarten", "26161", url="https://a/2")
    conn.commit()
    conn.close()
    monkeypatch.setattr(store, "_source_identity_warning_logged", False)

    with caplog.at_level(logging.WARNING, logger=store.logger.name):
        store.initialize_foreign_offers_db()  # must not raise: this runs on every CRM request
        store.initialize_foreign_offers_db()

    conn = _raw_connect(fresh_db)
    try:
        names = {row[1] for row in conn.execute("PRAGMA index_list(foreign_offers)")}
    finally:
        conn.close()
    assert "ux_foreign_offers_source_identity" not in names
    warnings = [record for record in caplog.records if "ux_foreign_offers_source_identity" in record.getMessage()]
    assert len(warnings) == 1  # logged once, not on every request
    with pytest.raises(store.AmbiguousSourceIdentityError):
        store.find_foreign_offer_by_source_identity("avarten", "26161")


# ---------------------------------------------------------------------------
# Development source identity
# ---------------------------------------------------------------------------


def test_manual_development_needs_no_source_identity(fresh_db):
    created = store.create_foreign_development("Azure Bay")

    assert set(created) == {"id", "name", "created_at", "updated_at"}  # existing shape unchanged
    assert store.find_foreign_development_by_source("avarten", "Azure Bay") is None
    store.create_foreign_development("Second Manual")  # several NULL identities are fine
    assert [d["name"] for d in store.list_foreign_developments()] == ["Azure Bay", "Second Manual"]


def test_source_development_is_found_by_platform_and_key(fresh_db):
    created = store.create_foreign_development("Laya Courtyard", "avarten", "26161")

    found = store.find_foreign_development_by_source("avarten", "26161")

    assert found["id"] == created["id"]
    assert (found["name"], found["source_platform"], found["source_key"]) == ("Laya Courtyard", "avarten", "26161")
    assert store.find_foreign_development_by_source("avarten", "26162") is None
    assert store.find_foreign_development_by_source("cyprus_constructions", "26161") is None


def test_two_sources_may_share_a_source_key(fresh_db):
    first = store.create_foreign_development("Avarten One", "avarten", "1")
    second = store.create_foreign_development("Cyprus One", "cyprus_constructions", "1")

    assert first["id"] != second["id"]
    assert store.find_foreign_development_by_source("avarten", "1")["id"] == first["id"]
    assert store.find_foreign_development_by_source("cyprus_constructions", "1")["id"] == second["id"]


def test_same_source_identity_cannot_create_two_developments(fresh_db):
    store.create_foreign_development("Laya Courtyard", "avarten", "26161")

    with pytest.raises(sqlite3.IntegrityError, match="source_key"):
        store.create_foreign_development("Laya Courtyard (renamed)", "avarten", "26161")


def test_source_identity_survives_a_crm_rename(fresh_db):
    created = store.create_foreign_development("Laya Courtyard", "avarten", "26161")

    store.rename_foreign_development(created["id"], "Laya - Dubai Studio City")

    found = store.find_foreign_development_by_source("avarten", "26161")
    assert found["id"] == created["id"] and found["name"] == "Laya - Dubai Studio City"


@pytest.mark.parametrize(
    "platform,key",
    [("avarten", None), (None, "26161"), ("", "26161"), ("avarten", "  "), ("  ", "  ")],
)
def test_partial_or_blank_source_identity_is_rejected(fresh_db, platform, key):
    with pytest.raises(ValueError):
        store.create_foreign_development("X", platform, key)
    assert store.list_foreign_developments() == []


def test_development_name_uniqueness_still_applies_to_source_developments(fresh_db):
    store.create_foreign_development("Azure Bay")  # manual
    with pytest.raises(sqlite3.IntegrityError, match="name"):
        store.create_foreign_development("azure bay", "avarten", "9")  # collision policy is SYNC-2's job


# ---------------------------------------------------------------------------
# Offer source identity (existing source_platform + source_offer_ref)
# ---------------------------------------------------------------------------


def test_existing_offers_are_found_by_their_existing_identity(legacy_db):
    found = store.find_foreign_offer_by_source_identity("tripinvest", "70005")

    assert found["id"] == 5
    assert found["source_url"] == "https://tripinvest.pl/oferta/offer-5"
    assert found["is_active"] == 1
    assert (found["last_sync_run_id"], found["source_payload_hash"]) == (None, None)
    assert store.find_foreign_offer_by_source_identity("tripinvest", "nope") is None


def test_two_sources_may_share_a_source_offer_ref(fresh_db):
    conn = _raw_connect(fresh_db)
    first = _insert_offer(conn, "avarten", "7")
    second = _insert_offer(conn, "cyprus_constructions", "7")
    conn.commit()
    conn.close()

    assert store.find_foreign_offer_by_source_identity("avarten", "7")["id"] == first
    assert store.find_foreign_offer_by_source_identity("cyprus_constructions", "7")["id"] == second


def test_same_platform_and_offer_ref_cannot_be_inserted_twice(fresh_db):
    conn = _raw_connect(fresh_db)
    _insert_offer(conn, "avarten", "26161", url="https://avartenproperties.com/property/laya/")
    with pytest.raises(sqlite3.IntegrityError, match="source_offer_ref"):
        _insert_offer(conn, "avarten", "26161", url="https://avartenproperties.com/property/laya-renamed/")
    conn.close()


def test_missing_or_empty_offer_refs_are_not_treated_as_an_identity(fresh_db):
    conn = _raw_connect(fresh_db)
    _insert_offer(conn, "avarten", None, url="https://a/1")
    _insert_offer(conn, "avarten", None, url="https://a/2")
    _insert_offer(conn, "avarten", "", url="https://a/3")
    _insert_offer(conn, "avarten", "", url="https://a/4")
    conn.commit()
    conn.close()
    with pytest.raises(ValueError):
        store.find_foreign_offer_by_source_identity("avarten", "")


def test_tripinvest_is_exempt_from_the_unique_index_and_lookup_reports_ambiguity(fresh_db):
    # TripInvest's ref is not guaranteed 1:1 with its URL; enforcing it would
    # change today's importer behaviour, so only lookups guard against it.
    conn = _raw_connect(fresh_db)
    _insert_offer(conn, "tripinvest", "75156", url="https://tripinvest.pl/oferta/old-slug-75156")
    _insert_offer(conn, "tripinvest", "75156", url="https://tripinvest.pl/oferta/new-slug-75156")
    conn.commit()
    conn.close()

    with pytest.raises(store.AmbiguousSourceIdentityError):
        store.find_foreign_offer_by_source_identity("tripinvest", "75156")


# ---------------------------------------------------------------------------
# Sync runs
# ---------------------------------------------------------------------------


def test_create_run_starts_in_running_state_with_zero_counts(fresh_db):
    run = store.create_foreign_sync_run("avarten")

    assert run["source_platform"] == "avarten"
    assert run["status"] == "running"
    assert run["started_at"] and run["finished_at"] is None and run["error_message"] is None
    assert [run[k] for k in (
        "discovered_count", "new_count", "updated_count", "unchanged_count", "missing_count", "error_count"
    )] == [0, 0, 0, 0, 0, 0]
    assert store.get_foreign_sync_run(run["id"]) == run


def test_finish_run_completed_stores_counts(fresh_db):
    run = store.create_foreign_sync_run("avarten")

    finished = store.finish_foreign_sync_run(
        run["id"], "completed",
        discovered_count=45, new_count=40, updated_count=3, unchanged_count=2, missing_count=1, error_count=0,
    )

    assert finished["status"] == "completed" and finished["finished_at"]
    assert (finished["discovered_count"], finished["new_count"], finished["updated_count"],
            finished["unchanged_count"], finished["missing_count"], finished["error_count"]) == (45, 40, 3, 2, 1, 0)
    assert finished["error_message"] is None
    assert store.get_foreign_sync_run(run["id"]) == finished


def test_finish_run_failed_keeps_the_error_summary(fresh_db):
    run = store.create_foreign_sync_run("cyprus_constructions")

    finished = store.finish_foreign_sync_run(
        run["id"], "failed", discovered_count=3, error_count=1, error_message="REST returned HTTP 503"
    )

    assert finished["status"] == "failed"
    assert finished["error_message"] == "REST returned HTTP 503"
    assert finished["error_count"] == 1 and finished["discovered_count"] == 3


def test_a_finished_run_is_never_rewritten(fresh_db):
    run = store.create_foreign_sync_run("avarten")
    first = store.finish_foreign_sync_run(run["id"], "completed", new_count=5)

    assert store.finish_foreign_sync_run(run["id"], "failed", error_message="late") is None
    assert store.get_foreign_sync_run(run["id"]) == first


def test_finish_run_rejects_bad_input_and_unknown_runs(fresh_db):
    run = store.create_foreign_sync_run("avarten")

    with pytest.raises(ValueError):
        store.finish_foreign_sync_run(run["id"], "running")
    with pytest.raises(ValueError):
        store.finish_foreign_sync_run(run["id"], "done")
    with pytest.raises(ValueError):
        store.finish_foreign_sync_run(run["id"], "completed", new_count=-1)
    with pytest.raises(ValueError):
        store.finish_foreign_sync_run(run["id"], "completed", new_count=True)
    assert store.get_foreign_sync_run(run["id"])["status"] == "running"  # nothing was half-written
    assert store.finish_foreign_sync_run(9999, "completed") is None
    assert store.get_foreign_sync_run(9999) is None


def test_status_check_constraint_rejects_unknown_values_at_the_database(fresh_db):
    conn = _raw_connect(fresh_db)
    with pytest.raises(sqlite3.IntegrityError):
        conn.execute("INSERT INTO foreign_sync_runs (source_platform, status) VALUES ('avarten', 'weird')")
    conn.close()


def test_latest_run_is_per_source_and_the_newest_by_id(fresh_db):
    a1 = store.create_foreign_sync_run("avarten")
    c1 = store.create_foreign_sync_run("cyprus_constructions")
    a2 = store.create_foreign_sync_run("avarten")
    store.finish_foreign_sync_run(a1["id"], "completed")

    assert store.get_latest_foreign_sync_run("avarten")["id"] == a2["id"]  # a1 finishing later does not matter
    assert store.get_latest_foreign_sync_run("cyprus_constructions")["id"] == c1["id"]
    assert store.get_latest_foreign_sync_run("tripinvest") is None


# ---------------------------------------------------------------------------
# Per-offer sync metadata
# ---------------------------------------------------------------------------


def _offer_row(db_path, offer_id):
    conn = _raw_connect(db_path)
    try:
        return dict(conn.execute("SELECT * FROM foreign_offers WHERE id = ?", (offer_id,)).fetchone())
    finally:
        conn.close()


def test_record_seen_stores_last_seen_run_and_hash(fresh_db):
    conn = _raw_connect(fresh_db)
    offer_id = _insert_offer(conn, "avarten", "26161")
    conn.commit()
    conn.close()
    run = store.create_foreign_sync_run("avarten")

    result = store.record_foreign_offer_seen(offer_id, run["id"], "hash-1")

    assert result["foreign_offer_id"] == offer_id
    assert result["last_sync_run_id"] == run["id"]
    assert result["source_payload_hash"] == "hash-1"
    assert result["last_source_sync_at"]
    found = store.find_foreign_offer_by_source_identity("avarten", "26161")
    assert (found["last_sync_run_id"], found["source_payload_hash"]) == (run["id"], "hash-1")
    assert found["last_source_sync_at"] == result["last_source_sync_at"]


def test_record_seen_does_not_touch_activity_or_any_other_field(fresh_db):
    conn = _raw_connect(fresh_db)
    offer_id = _insert_offer(
        conn, "avarten", "26161",
        offer_title="Laya", price_value=699000, floor=None, floor_override=3,
        is_active=0, is_export_ready=1, needs_update=1, last_exported_at="2026-09-07 16:53:47",
    )
    development = conn.execute("INSERT INTO foreign_developments (name) VALUES ('Laya')").lastrowid
    conn.execute("UPDATE foreign_offers SET development_id = ? WHERE id = ?", (development, offer_id))
    conn.commit()
    conn.close()
    before = _offer_row(fresh_db, offer_id)
    run = store.create_foreign_sync_run("avarten")

    store.record_foreign_offer_seen(offer_id, run["id"], "hash-1")

    after = _offer_row(fresh_db, offer_id)
    changed = {key for key in before if before[key] != after[key]}
    assert changed <= {"last_source_sync_at", "last_sync_run_id", "source_payload_hash", "updated_at"}
    assert after["is_active"] == 0  # "seen" is not "active"
    assert (after["needs_update"], after["is_export_ready"], after["floor_override"]) == (1, 1, 3)
    assert after["development_id"] == development and after["last_source_change_at"] == before["last_source_change_at"]


def test_record_seen_edge_cases(fresh_db):
    conn = _raw_connect(fresh_db)
    offer_id = _insert_offer(conn, "avarten", "1")
    conn.commit()
    conn.close()
    run = store.create_foreign_sync_run("avarten")

    assert store.record_foreign_offer_seen(9999, run["id"], "h") is None
    with pytest.raises(sqlite3.IntegrityError):
        store.record_foreign_offer_seen(offer_id, 9999, "h")  # unknown run
    with pytest.raises(ValueError):
        store.record_foreign_offer_seen(offer_id, run["id"], "")
    assert _offer_row(fresh_db, offer_id)["last_sync_run_id"] is None  # failed calls wrote nothing


# ---------------------------------------------------------------------------
# Backward compatibility
# ---------------------------------------------------------------------------


def test_tripinvest_import_still_works_and_coexists_with_sync_metadata(fresh_db, monkeypatch):
    monkeypatch.setattr(importer, "TripinvestConnector", _FakeTripinvestConnector)

    result = importer.upsert_foreign_offer_from_tripinvest(URL)
    found = store.find_foreign_offer_by_source_identity("tripinvest", "75156")

    assert found["id"] == result["foreign_offer_id"]
    # INV-FIX-003: the importer records the payload hash of the merged offer; a manual import has no run.
    assert found["last_sync_run_id"] is None and len(found["source_payload_hash"]) == 64
    payload_hash = found["source_payload_hash"]

    run = store.create_foreign_sync_run("tripinvest")
    store.record_foreign_offer_seen(found["id"], run["id"], "h")
    importer.upsert_foreign_offer_from_tripinvest(URL)  # refresh must not erase the run that last saw it

    after = store.find_foreign_offer_by_source_identity("tripinvest", "75156")
    assert (after["last_sync_run_id"], after["source_payload_hash"]) == (run["id"], payload_hash)
    assert after["is_active"] == 1


def test_list_foreign_offers_contract_is_unchanged(legacy_db):
    store.initialize_foreign_offers_db()
    items = store.list_foreign_offers()

    assert [item["id"] for item in items] == [8, 6, 5, 1]
    assert not (NEW_OFFER_COLUMNS & set(items[0]))  # no new field leaks into the CRM list API
