"""PREPROD-1: the TripInvest importer uses the shared foreign offer validator.

The importer keeps only its own advisory warnings (region/rooms/features heuristics);
missing images/city/category/price/... and is_export_ready come from
foreign_offer_validation.refresh_foreign_offer_export_state on the final row, in the
importer's transaction. Fake connector, throwaway SQLite, no network.
"""
import pytest

import InvestmentManager.foreign_offers_importer as importer
from InvestmentManager.foreign_offer_validation import VALIDATOR_WARNING_CODES, refresh_foreign_offer_export_state
from InvestmentManager.foreign_offers_store import update_foreign_offer_fields
from tests.investmentmanager.test_foreign_developments import _raw_connect, foreign_db, fresh_db  # noqa: F401
from tests.investmentmanager.test_foreign_sync_service import execute, query

URL = "https://tripinvest.pl/oferta/apartament-w-torrevieja-75156"
LEGACY = {"location_region_from_marketing_area", "rooms_count_inferred_from_bedrooms", "unmapped_features_present"}


class Fake:
    data: dict = {}

    def fetch_offer(self, identifier):
        return {"kind": "offer_details", "offer": {}, "url": identifier["url"]}

    def normalize_offer(self, raw_offer):
        d = {"title": "Apartament w Torrevieja", "property_type": "apartament", "price": 199000, "currency": "EUR",
             "area": 64, "gallery": ["https://static.example/1.jpg"], "location": "Costa Blanca, Torrevieja",
             "features": ["Basen"], **type(self).data}
        return {
            "source": {"external_id": "75156"},
            "listing": {"title": d["title"], "description_text": "Opis", "property_type": d["property_type"], "offer_type": "sale",
                        "market_type": "pierwotny", "location": {"address_label": d["location"]}},
            "pricing": {"amount": d["price"], "currency": d["currency"]},
            "metrics": {"area_m2": d["area"], "bedrooms": 2, "bathrooms": 1, "floor": None},
            "media": {"gallery": d["gallery"]},
            "raw": {"payload": {"title": d["title"], "map": {}, "features": d["features"]}},
        }


@pytest.fixture()
def imp(fresh_db, monkeypatch):
    monkeypatch.setattr(importer, "TripinvestConnector", Fake)

    def run(**data):
        monkeypatch.setattr(Fake, "data", data)
        return importer.upsert_foreign_offer_from_tripinvest(URL)

    return run


def rows(db, offer_id):
    return query(db, "SELECT warning_code, is_blocking FROM foreign_offer_export_warnings WHERE foreign_offer_id = ? AND resolved_at IS NULL ORDER BY warning_code", offer_id)


def codes(db, offer_id):
    return [r["warning_code"] for r in rows(db, offer_id)]


def blocking(db, offer_id):
    return {r["warning_code"] for r in rows(db, offer_id) if r["is_blocking"]}


def ready(db, offer_id):
    return query(db, "SELECT is_export_ready FROM foreign_offers WHERE id = ?", offer_id)[0]["is_export_ready"]


NO_CATEGORY = dict(title="Nieruchomość", property_type=None, features=[])


# A. create --------------------------------------------------------------


def test_a_complete_offer_is_ready_with_only_advisory_warnings(imp, fresh_db):
    result = imp()

    oid = result["foreign_offer_id"]
    assert result["is_export_ready"] is True and ready(fresh_db, oid) == 1
    assert not blocking(fresh_db, oid)
    assert LEGACY <= set(codes(fresh_db, oid))
    assert result["warning_count"] == len(rows(fresh_db, oid))


def test_a_missing_category_is_blocking_for_tripinvest_too(imp, fresh_db):
    result = imp(**NO_CATEGORY)

    oid = result["foreign_offer_id"]
    assert "missing_category_id_domiporta" in blocking(fresh_db, oid)
    assert result["is_export_ready"] is False and ready(fresh_db, oid) == 0


@pytest.mark.parametrize("data,code", [
    ({"price": None}, "missing_price"), ({"area": None}, "missing_area"), ({"gallery": []}, "missing_images"),
    ({"location": ""}, "missing_city_name"), ({"currency": "XYZ"}, "unsupported_currency"),
])
def test_shared_rules_block_tripinvest_offers(imp, fresh_db, data, code):
    result = imp(**data)
    assert code in blocking(fresh_db, result["foreign_offer_id"])
    assert result["is_export_ready"] is False


# B. refresh -------------------------------------------------------------


def test_refresh_resolves_and_raises_shared_warnings_from_the_final_row(imp, fresh_db):
    oid = imp(**NO_CATEGORY)["foreign_offer_id"]
    assert ready(fresh_db, oid) == 0

    imp()
    assert "missing_category_id_domiporta" not in codes(fresh_db, oid) and ready(fresh_db, oid) == 1

    # INV-FIX-003: a missing price or an empty gallery is "no information" in the
    # shared merge; it no longer wipes the stored values (it used to block the offer).
    imp(price=None, gallery=[])
    assert not {"missing_price", "missing_images"} & blocking(fresh_db, oid) and ready(fresh_db, oid) == 1

    # A missing value in the final row is still raised by the shared validator.
    update_foreign_offer_fields(oid, {"price_value": None})
    imp()
    assert "missing_price" in blocking(fresh_db, oid) and ready(fresh_db, oid) == 0


def test_readiness_counts_every_unresolved_blocking_row_not_only_the_shared_ones(imp, fresh_db):
    oid = imp()["foreign_offer_id"]
    execute(fresh_db, "INSERT INTO foreign_offer_export_warnings (foreign_offer_id, warning_code, warning_message, field_name, is_blocking) VALUES (?, 'other_blocker', 'x', 'f', 1)", oid)

    conn = _raw_connect(fresh_db)
    state = refresh_foreign_offer_export_state(conn, oid)
    conn.commit()
    conn.close()

    assert state["is_export_ready"] is False and ready(fresh_db, oid) == 0 and "other_blocker" in codes(fresh_db, oid)


# C. legacy warnings -----------------------------------------------------


def test_importer_warnings_survive_and_nothing_is_duplicated(imp, fresh_db):
    oid = imp()["foreign_offer_id"]
    for _ in range(3):
        imp()

    all_codes = [r["warning_code"] for r in query(fresh_db, "SELECT warning_code FROM foreign_offer_export_warnings WHERE foreign_offer_id = ?", oid)]
    assert len(all_codes) == len(set(all_codes)) and LEGACY <= set(all_codes)


def test_a_shared_row_is_not_duplicated_across_refreshes(imp, fresh_db):
    oid = imp(**NO_CATEGORY)["foreign_offer_id"]
    imp(**NO_CATEGORY)
    n = query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offer_export_warnings WHERE foreign_offer_id = ? AND warning_code = 'missing_category_id_domiporta'", oid)[0]["n"]
    assert n == 1


def test_importer_warnings_follow_the_source_and_do_not_emit_shared_codes(imp, fresh_db):
    oid = imp()["foreign_offer_id"]
    imp(features=[])
    assert "unmapped_features_present" not in codes(fresh_db, oid)

    own = {w[0] for w in importer._extract_warning_rows({"metrics": {}, "raw": {"payload": {"features": ["x"]}}}, "Costa")}
    assert own == {"location_region_from_marketing_area", "unmapped_features_present"}
    assert not own & set(VALIDATOR_WARNING_CODES)


# D. needs_update --------------------------------------------------------


def events(db, oid):
    return [r["event_type"] for r in query(db, "SELECT event_type FROM foreign_offer_portal_sync_events WHERE foreign_offer_id = ? ORDER BY id", oid)]


def needs_update(db, oid):
    return query(db, "SELECT needs_update FROM foreign_offers WHERE id = ?", oid)[0]["needs_update"]


def publish(db, oid):
    execute(db, "UPDATE foreign_offer_portal_sync SET is_published = 1 WHERE foreign_offer_id = ? AND portal_key = 'domiporta'", oid)


def test_a_published_business_change_still_flags_update_required(imp, fresh_db):
    oid = imp()["foreign_offer_id"]
    publish(fresh_db, oid)

    imp(price=210000)

    assert needs_update(fresh_db, oid) == 1 and "update_required" in events(fresh_db, oid)


def test_an_unpublished_change_only_logs_the_ignored_update(imp, fresh_db):
    oid = imp()["foreign_offer_id"]
    imp(price=210000)
    assert needs_update(fresh_db, oid) == 0
    assert "update_required" not in events(fresh_db, oid) and "update_ignored_no_publication" in events(fresh_db, oid)


def test_a_validator_only_refresh_never_flags_or_logs(imp, fresh_db):
    oid = imp()["foreign_offer_id"]
    publish(fresh_db, oid)
    execute(fresh_db, "UPDATE foreign_offers SET price_value = NULL WHERE id = ?", oid)
    before = events(fresh_db, oid)

    conn = _raw_connect(fresh_db)
    refresh_foreign_offer_export_state(conn, oid)
    conn.commit()
    conn.close()

    assert "missing_price" in blocking(fresh_db, oid) and ready(fresh_db, oid) == 0
    after = events(fresh_db, oid)
    assert after[:len(before)] == before
    # Changed qualification/warnings now require durable input revision (009),
    # but validation must still create no publication/update audit events.
    assert after[len(before):] and all(e == 'foreign_input_revision_v2' for e in after[len(before):])
    assert needs_update(fresh_db, oid) == 0


# E. transaction ---------------------------------------------------------


def snapshot(db):
    return {t: query(db, f"SELECT * FROM {t} ORDER BY 1") for t in (
        "foreign_offers", "foreign_offer_export_warnings", "foreign_offer_images", "foreign_offer_sync_log",
        "foreign_offer_raw_snapshots")}


def boom(conn, offer_id):
    raise RuntimeError("validator down")


def test_a_validator_failure_rolls_back_a_new_import(imp, fresh_db, monkeypatch):
    monkeypatch.setattr(importer, "refresh_foreign_offer_export_state", boom)
    with pytest.raises(RuntimeError, match="validator down"):
        imp()

    assert all(not v for v in snapshot(fresh_db).values())


def test_a_validator_failure_rolls_back_an_update_completely(imp, fresh_db, monkeypatch):
    imp()
    before = snapshot(fresh_db)

    monkeypatch.setattr(importer, "refresh_foreign_offer_export_state", boom)
    with pytest.raises(RuntimeError):
        imp(price=1, gallery=[], features=[], title="Nieruchomość x")

    assert snapshot(fresh_db) == before
