"""AVARTEN-SYNC-1: the adapter feeding the generic sync, and the manual orchestrator.

Real (throwaway) SQLite, no network: canonical offers come from the real connector's
normalize_offer() on REST fixtures; the orchestrator gets a fake connector.
"""
import json

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 avarten_run
from InvestmentManager.foreign_sync_sources.avarten import adapt_avarten_catalog
from InvestmentManager.foreign_sync_sources.avarten_run import AvartenFetchError, run_avarten_foreign_sync
from integrations.avarten.connector import AvartenConnector
from tests.avarten.avarten_rest_fixtures import BASE, rest_property
from tests.investmentmanager.test_foreign_developments import _raw_connect, foreign_db, fresh_db  # noqa: F401
from tests.investmentmanager.test_foreign_sync_service import full_dump, offer_row, query

CONNECTOR = AvartenConnector()
GALLERY = [f"{BASE}/wp-content/uploads/2025/04/laya-{i}-1170x785.jpg" for i in range(3)]


def canonical(images=None, **overrides):
    return CONNECTOR.normalize_offer(
        {"kind": "rest_offer", "offer": rest_property(**overrides),
         "images": GALLERY if images is None else images, "images_source": "rest_media"}
    )


def sync(canonicals):
    adapted = adapt_avarten_catalog(canonicals)
    run = store.create_foreign_sync_run("avarten")
    report = sync_records("avarten", adapted.developments, adapted.offers, run_id=run["id"])
    return report, 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 warnings(db_path):
    return {r["warning_code"] for r in query(db_path, "SELECT warning_code FROM foreign_offer_export_warnings")}


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


def test_first_sync_creates_the_development_and_the_project_level_offer(fresh_db):
    report, run_id = sync([canonical()])

    assert (report.new_count, report.error_count) == (1, 0)
    development = store.find_foreign_development_by_source("avarten", "26161")
    assert development["name"] == "Laya Courtyard at Dubai Studio City"
    row = offer_row(fresh_db, "26161", "avarten")
    assert row["development_id"] == development["id"]                       # development assigned
    assert row["source_url"] == f"{BASE}/property/laya-courtyard-at-dubai-studio-city/"
    assert (row["offer_title"], row["price_value"], row["price_currency"]) == ("Laya Courtyard at Dubai Studio City", 699000, "AED")
    assert (row["source_city_name"], row["source_location_text"], row["market_type_normalized"]) == ("Dubai", "Dubai Studio City", "primary")
    assert row["latitude"] == pytest.approx(25.03605241282) and row["property_type_source"] == "apartments"
    for untouched in ("area_total_m2", "floor", "floor_override", "rooms_count", "bathrooms_count", "bedrooms_count",
                      "category_id_domiporta", "offer_type_normalized", "source_country_name", "source_country_code"):
        assert row[untouched] is None, untouched
    assert row["last_sync_run_id"] == run_id and row["is_active"] == 1
    assert [r["image_url"] for r in query(fresh_db, "SELECT image_url FROM foreign_offer_images WHERE foreign_offer_id = ? ORDER BY sort_order", row["id"])] == GALLERY


def test_a_typical_avarten_offer_is_in_the_crm_but_not_export_ready(fresh_db):
    sync([canonical()])

    row = offer_row(fresh_db, "26161", "avarten")
    assert row["is_export_ready"] == 0
    assert blocking(fresh_db) == {"missing_area", "missing_country_name", "missing_category_id_domiporta"}
    assert "missing_images" not in warnings(fresh_db) and "missing_city_name" not in warnings(fresh_db)


def test_an_offer_without_images_also_gets_missing_images(fresh_db):
    sync([canonical(images=[])])
    assert "missing_images" in blocking(fresh_db)


def test_a_second_identical_sync_is_unchanged(fresh_db):
    sync([canonical()])
    before = offer_row(fresh_db, "26161", "avarten")

    report, run_id = sync([canonical()])

    assert (report.new_count, report.updated_count, report.unchanged_count) == (0, 0, 1)
    after = offer_row(fresh_db, "26161", "avarten")
    for column in ("offer_title", "price_value", "source_values_json", "source_payload_hash", "development_id", "last_source_change_at"):
        assert after[column] == before[column]
    assert after["last_sync_run_id"] == run_id
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offers")[0]["n"] == 1


def test_a_source_change_propagates_when_the_field_was_not_edited(fresh_db):
    sync([canonical()])

    report, _ = sync([canonical(meta={"fave_property_price": ["750000"], "fave_prop-price": ["750,000 AED/-"]},
                                title={"rendered": "Laya Courtyard (Phase 2)"})])

    row = offer_row(fresh_db, "26161", "avarten")
    assert (report.updated_count, row["price_value"], row["offer_title"]) == (1, 750000, "Laya Courtyard (Phase 2)")
    assert store.find_foreign_development_by_source("avarten", "26161")["name"] == "Laya Courtyard at Dubai Studio City"  # the name is CRM-owned


def test_a_manual_crm_edit_survives_a_later_source_update(fresh_db):
    sync([canonical()])
    offer_id = offer_row(fresh_db, "26161", "avarten")["id"]
    update_foreign_offer_fields(offer_id, {"price_value": 720000, "area_total_m2": 90, "offer_title": "Laya - poprawiony"})

    report, _ = sync([canonical(meta={"fave_property_price": ["750000"], "fave_prop-price": ["750,000 AED/-"]},
                                title={"rendered": "Laya Courtyard (renamed at source)"})])

    row = offer_row(fresh_db, "26161", "avarten")
    assert (row["price_value"], row["area_total_m2"], row["offer_title"]) == (720000, 90, "Laya - poprawiony")
    assert {p.field for p in report.offers[0].plan.preserved} == {"price_value", "offer_title"}
    assert row["area_total_m2"] == 90  # a value the source never had


def test_manual_completion_makes_the_offer_ready(fresh_db):
    sync([canonical()])
    offer_id = offer_row(fresh_db, "26161", "avarten")["id"]

    result = update_foreign_offer_fields(offer_id, {"area_total_m2": 82, "category_id_domiporta": "191",
                                                    "source_country_name": "United Arab Emirates", "rooms_count": 2})
    assert result["is_export_ready"] is True
    assert {w["warning_code"] for w in result["warnings"] if w["is_blocking"]} == set()
    assert {w["warning_code"] for w in result["warnings"]} == {"missing_floor"}   # advisory only (primary-market apartment)
    assert offer_row(fresh_db, "26161", "avarten")["is_export_ready"] == 1


def test_the_same_wp_id_with_a_changed_url_does_not_create_a_duplicate(fresh_db):
    sync([canonical()])
    first_url = offer_row(fresh_db, "26161", "avarten")["source_url"]

    report, _ = sync([canonical(slug="laya-courtyard-new-slug", link=f"{BASE}/property/laya-courtyard-new-slug/")])

    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offers WHERE source_platform = 'avarten'")[0]["n"] == 1
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_developments WHERE source_platform = 'avarten'")[0]["n"] == 1
    assert report.new_count == 0 and report.error_count == 0
    assert offer_row(fresh_db, "26161", "avarten")["source_url"] == first_url   # the old URL stays (known SYNC-2B limitation)


def test_several_projects_become_several_developments_and_offers(fresh_db):
    catalog = [canonical(id=i, slug=f"p{i}", link=f"{BASE}/property/p{i}/", title={"rendered": f"Project {i}"}) for i in (1, 2, 3)]

    report, _ = sync(catalog)

    assert report.new_count == 3
    assert [d["name"] for d in store.list_foreign_developments()] == ["Project 1", "Project 2", "Project 3"]
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offers WHERE development_id IS NOT NULL")[0]["n"] == 3


def test_a_development_name_collision_is_reported_and_the_offer_is_still_created(fresh_db):
    store.create_foreign_development("Laya Courtyard at Dubai Studio City")   # a manual development with that name

    report, _ = sync([canonical()])

    assert [d.status for d in report.developments] == ["name_conflict"]
    assert offer_row(fresh_db, "26161", "avarten")["development_id"] is None


# ---------------------------------------------------------------------------
# Orchestrator
# ---------------------------------------------------------------------------


class FakeConnector:
    def __init__(self, catalog=None, error=None):
        self._catalog, self._error, self.calls = catalog, error, 0

    def fetch_full_catalog(self):
        self.calls += 1
        if self._error:
            raise self._error
        return self._catalog


def three(bad_middle=True):
    return [
        canonical(id=1, slug="a", link=f"{BASE}/property/a/", title={"rendered": "Alpha"}),
        canonical(id=2, slug="b", link=f"{BASE}/property/b/", title={"rendered": ""} if bad_middle else {"rendered": "Beta"}),
        canonical(id=3, slug="c", link=f"{BASE}/property/c/", title={"rendered": "Gamma"}),
    ]


def test_a_fetch_failure_writes_nothing_and_creates_no_run(fresh_db):
    before = full_dump(fresh_db)

    with pytest.raises(AvartenFetchError, match="fetch failed"):
        run_avarten_foreign_sync(connector=FakeConnector(error=RuntimeError("REST down")))

    assert full_dump(fresh_db) == before
    assert store.get_latest_foreign_sync_run("avarten") is None


def test_partial_adapter_errors_still_sync_the_good_records_and_are_not_hidden(fresh_db):
    result = run_avarten_foreign_sync(connector=FakeConnector(three()))

    assert (result.adapter_report.discovered, result.adapter_report.adapted, result.adapter_report.error_count) == (3, 2, 1)
    assert (result.sync_report.new_count, result.error_count) == (2, 1)
    assert result.fully_successful is False
    assert offer_row(fresh_db, "1", "avarten") and offer_row(fresh_db, "3", "avarten") and offer_row(fresh_db, "2", "avarten") is None
    run = result.run
    assert run["status"] == "completed"
    assert (run["discovered_count"], run["new_count"], run["updated_count"], run["unchanged_count"],
            run["missing_count"], run["error_count"]) == (3, 2, 0, 0, 0, 1)
    assert "title" in run["error_message"] and "2" in run["error_message"]
    assert result.summary()["adapter_errors"] == 1 and result.summary()["run_id"] == run["id"]


def test_a_fully_good_catalog_is_a_full_success_with_sensible_counters(fresh_db):
    first = run_avarten_foreign_sync(connector=FakeConnector(three(bad_middle=False)))
    second = run_avarten_foreign_sync(connector=FakeConnector(three(bad_middle=False)))

    assert first.fully_successful and first.summary()["new"] == 3 and first.run["error_count"] == 0
    assert second.fully_successful and (second.summary()["new"], second.summary()["unchanged"]) == (0, 3)
    assert second.run["id"] != first.run["id"] and second.run["unchanged_count"] == 3
    assert store.get_latest_foreign_sync_run("avarten")["id"] == second.run["id"]


def test_the_run_is_closed_exactly_once(fresh_db):
    result = run_avarten_foreign_sync(connector=FakeConnector(three(bad_middle=False)))

    run_id = result.run["id"]
    assert store.finish_foreign_sync_run(run_id, "failed", error_message="second close") is None   # already finished
    assert store.get_foreign_sync_run(run_id) == result.run
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_sync_runs")[0]["n"] == 1


def test_a_catalog_with_nothing_usable_fails_the_run_and_writes_no_offers(fresh_db):
    bad = [canonical(id=i, slug=f"x{i}", link=f"{BASE}/property/x{i}/", title={"rendered": ""}) for i in (1, 2)]

    result = run_avarten_foreign_sync(connector=FakeConnector(bad))

    assert result.run["status"] == "failed" and result.run["error_count"] == 2 and result.run["discovered_count"] == 2
    assert query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offers")[0]["n"] == 0


def test_a_crash_inside_the_sync_fails_the_run_and_re_raises(fresh_db, monkeypatch):
    def boom(*args, **kwargs):
        raise RuntimeError("engine exploded")

    monkeypatch.setattr(avarten_run, "sync_records", boom)
    with pytest.raises(RuntimeError, match="engine exploded"):
        run_avarten_foreign_sync(connector=FakeConnector(three(bad_middle=False)))

    run = store.get_latest_foreign_sync_run("avarten")
    assert run["status"] == "failed" and "engine exploded" in run["error_message"]


def test_dry_run_writes_nothing_at_all(fresh_db):
    run_avarten_foreign_sync(connector=FakeConnector(three(bad_middle=False)))
    execute = _raw_connect(fresh_db)
    execute.execute("UPDATE foreign_offers SET offer_title = 'Manual title' WHERE source_offer_ref = '1'")
    execute.commit()
    execute.close()
    before = full_dump(fresh_db)
    catalog = three()
    catalog[0] = canonical(id=1, slug="a", link=f"{BASE}/property/a/", title={"rendered": "Alpha changed"})
    catalog.append(canonical(id=9, slug="n", link=f"{BASE}/property/n/", title={"rendered": "Brand new"}))

    result = run_avarten_foreign_sync(dry_run=True, connector=FakeConnector(catalog))

    assert full_dump(fresh_db) == before          # no run, developments, offers, warnings, logs
    assert result.run is None and result.dry_run is True
    assert (result.sync_report.new_count, result.sync_report.unchanged_count, result.adapter_report.error_count) == (1, 2, 1)
    assert [d.status for d in result.sync_report.developments] == ["existing", "existing", "would_create"]
    assert result.summary()["run_id"] is None


def test_a_dry_run_after_a_fetch_failure_still_raises(fresh_db):
    with pytest.raises(AvartenFetchError):
        run_avarten_foreign_sync(dry_run=True, connector=FakeConnector(error=RuntimeError("down")))


def test_the_command_line_entrypoint_reports_and_uses_exit_codes(fresh_db, monkeypatch, capsys):
    monkeypatch.setattr(avarten_run, "run_avarten_foreign_sync", lambda dry_run=False: run_avarten_foreign_sync(
        dry_run=dry_run, connector=FakeConnector(three(bad_middle=False))))
    assert avarten_run.main(["--dry-run"]) == 0
    assert json.loads(capsys.readouterr().out)["dry_run"] is True

    monkeypatch.setattr(avarten_run, "run_avarten_foreign_sync", lambda dry_run=False: run_avarten_foreign_sync(
        dry_run=dry_run, connector=FakeConnector(three())))
    assert avarten_run.main([]) == 1   # partial adapter errors are not a full success

    def down(dry_run=False):
        raise AvartenFetchError("catalog down")

    monkeypatch.setattr(avarten_run, "run_avarten_foreign_sync", down)
    assert avarten_run.main([]) == 2
