"""Characterisation tests for InvestmentConnector.normalize_offer()
(modules/offers/connectors/investment_connector.py).

Scope:
  - Only normalize_offer() is exercised, for both raw-offer "kinds" it
    supports (`catalog_row` and `offer_row`). `fetch_catalog()` /
    `fetch_offer()` perform real SQLite reads and are intentionally NOT
    covered here.
  - `offer_row` normalization calls modules.investment.functions.get_image_path(),
    which needs a Flask *request* context (url_for) and reads the local
    filesystem (IMAGES_DIR). Both are provided here via the `request_context`
    fixture and a `monkeypatch`-redirected IMAGES_DIR pointing at a pytest
    `tmp_path`, so these tests never touch the real static/images/ directory
    or depend on the working directory's contents.
  - `catalog_row` normalization does NOT call get_image_path() itself (the
    image URL is passed in on the raw offer dict by fetch_catalog()), so
    those tests need no filesystem/request-context setup at all.

Record/row fixtures are built dynamically from the real
modules.investment.record_schema.OFFER_IDX / CATALOG_ROW_IDX classes (via
getattr on the field name), not from hardcoded numeric indices, so they stay
in sync with the actual schema.
"""
import os

import pytest

from modules.investment import functions as investment_functions
from modules.investment.record_schema import CATALOG_ROW_IDX as CIDX
from modules.investment.record_schema import OFFER_IDX as IDX
from InvestmentWebsite.offers.connectors.investment_connector import InvestmentConnector


# ---------------------------------------------------------------------------
# Record/row builders, derived from the real schema classes.
# ---------------------------------------------------------------------------

def _index_map(schema_cls):
    return {name: value for name, value in vars(schema_cls).items() if not name.startswith("_")}


_OFFER_FIELDS = _index_map(IDX)
_OFFER_MAX_INDEX = max(_OFFER_FIELDS.values())

_CATALOG_FIELDS = _index_map(CIDX)
_CATALOG_MAX_INDEX = max(_CATALOG_FIELDS.values())

DEFAULT_OFFER_VALUES = {
    "ID": 555,
    "PROPERTY_TYPE": "Mieszkanie",
    "OFFER_TYPE": "sprzedaż",
    "MARKET_TYPE": "wtórny",
    "COUNTRY": "Polska",
    "CITY": "Gdańsk",
    "REGION": "pomorskie",
    "PRICE": 450000,
    "PLOT_AREA_M2": None,
    "PLOT_SHAPE": None,
    "PLOT_TERRAIN": None,
    "BUILDING_TYPE": None,
    "HOUSE_TYPE": None,
    "ROOF_TYPE": None,
    "PARKING": "tak",
    "FLOORS_COUNT": 4,
    "FLOOR": 2,
    "AREA_M2": 62.5,
    "USABLE_AREA_M2": 58.0,
    "ROOMS": 3,
    "FURNISHING": "umeblowane",
    "WINDOWS_TYPE": "PCV",
    "KITCHEN_TYPE": "otwarta",
    "SEWAGE": "miejska",
    "HEATING": "gazowe",
    "ELECTRICITY": "tak",
    "GAS": "tak",
    "ADMIN_FEE": 450,
    "LAND_USE": None,
    "BUILDING_CONDITION": "dobry",
    "PURPOSE": None,
    "PROPERTY_CONDITION": "do zamieszkania",
    "CONSTRUCTION_YEAR": 2015,
    "AGENT_ID": 12,
    "LOCATION_LABEL": "Gdańsk, Wrzeszcz",
    "IMAGE_COUNT": 5,
    "AGENT_NAME": "Jan",
    "AGENT_SURNAME": "Kowalski",
    "AGENT_EMAIL": "jan.kowalski@example.com",
    "AGENT_PHONE": "600100200",
    "AGENT_LICENSE": "12345",
    "AGENT_REGION": "Pomorskie",
    "AGENT_ROLES": "agent",
    "DESCRIPTION_HTML": "<p>Opis oferty</p>",
}

assert set(DEFAULT_OFFER_VALUES) == set(_OFFER_FIELDS), (
    "DEFAULT_OFFER_VALUES must cover exactly the fields declared on OFFER_IDX "
    "(fails loudly if record_schema.py gains/loses a field)."
)


def make_offer_record(**overrides):
    values = dict(DEFAULT_OFFER_VALUES)
    values.update(overrides)
    record = [None] * (_OFFER_MAX_INDEX + 1)
    for name, value in values.items():
        record[getattr(IDX, name)] = value
    return record


DEFAULT_CATALOG_VALUES = {
    "ID": 777,
    "PROPERTY_TYPE": "Dom",
    "OFFER_TYPE": "sprzedaż",
    "MARKET_TYPE": "pierwotny",
    "COUNTRY": "Polska",
    "CITY": "Warszawa",
    "LOCATION": "Mokotów",
    "PRICE": 1200000,
    "PLOT_AREA_M2": 500,
    "PLOT_TERRAIN": "płaski",
    "PLOT_SHAPE": "prostokąt",
    "AREA_M2": 150,
    "ROOMS": 5,
    "BUILDING_CONDITION": "bardzo dobry",
    "PROPERTY_CONDITION": "do zamieszkania",
    "TITLE": "Dom Warszawa Mokotów",
}

assert set(DEFAULT_CATALOG_VALUES) == set(_CATALOG_FIELDS), (
    "DEFAULT_CATALOG_VALUES must cover exactly the fields declared on "
    "CATALOG_ROW_IDX (fails loudly if record_schema.py gains/loses a field)."
)


def make_catalog_row(**overrides):
    values = dict(DEFAULT_CATALOG_VALUES)
    values.update(overrides)
    row = [None] * (_CATALOG_MAX_INDEX + 1)
    for name, value in values.items():
        row[getattr(CIDX, name)] = value
    return row


# ---------------------------------------------------------------------------
# Filesystem isolation for get_image_path()/list_offer_image_filenames().
# ---------------------------------------------------------------------------

@pytest.fixture(autouse=True)
def isolated_images_dir(tmp_path, monkeypatch):
    """Redirect offer-image storage to a pytest tmp_path and clear lru_caches.

    Storage Path Layer / Phase 2 update: modules/investment/functions.py no
    longer caches a module-level IMAGES_DIR string -- it calls
    storage_paths.offer_dir(record_id) fresh each time, so isolation now
    monkeypatches storage_paths.REPO_ROOT instead (same technique as
    tests/storage/conftest.py's isolated_storage_root fixture).

    Guarantees these tests never read the real static/images/ directory and
    never leak cached results (keyed by record_id) across tests.
    """
    from modules.core import storage_paths

    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    isolated_root = tmp_path / "static" / "images"
    isolated_root.mkdir(parents=True)
    investment_functions.list_offer_image_filenames.cache_clear()
    investment_functions.get_image_path.cache_clear()
    yield isolated_root
    investment_functions.list_offer_image_filenames.cache_clear()
    investment_functions.get_image_path.cache_clear()


def _write_image(tmp_path, record_id, filename):
    offer_dir = tmp_path / str(record_id)
    offer_dir.mkdir(parents=True, exist_ok=True)
    (offer_dir / filename).write_bytes(b"fake-image-bytes")


# ---------------------------------------------------------------------------
# normalize_offer(): unsupported kind
# ---------------------------------------------------------------------------

def test_normalize_offer_unsupported_kind_raises():
    connector = InvestmentConnector()
    with pytest.raises(ValueError, match="Unsupported investment raw offer kind: bogus"):
        connector.normalize_offer({"kind": "bogus"})


# ---------------------------------------------------------------------------
# normalize_offer(): kind == "catalog_row"
# (no app/request context or filesystem needed: image_url comes pre-resolved
# on the raw offer dict)
# ---------------------------------------------------------------------------

class TestNormalizeCatalogRow:
    def _normalize(self, row, image_url="/static/images/777/image_777_url_1.jpg"):
        connector = InvestmentConnector()
        raw_offer = {"kind": "catalog_row", "row": row, "image_url": image_url}
        return connector.normalize_offer(raw_offer)

    def test_full_field_mapping_for_polish_offer(self):
        row = make_catalog_row()
        canonical = self._normalize(row)

        assert canonical["schema_version"] == "1.0"
        assert canonical["source"] == {
            "platform": "investment",
            "external_id": None,
            "external_url": None,
        }
        assert canonical["identity"]["offer_id"] == "777"
        assert canonical["status"] == {
            "lifecycle": "active",
            "labels": [],
            "published_at": None,
            "updated_at": None,
        }
        listing = canonical["listing"]
        assert listing["title"] == "Dom Warszawa Mokotów"
        assert listing["property_type"] == "Dom"
        assert listing["offer_type"] == "sprzedaż"
        assert listing["market_type"] == "pierwotny"
        assert listing["country_code"] == "PL"
        assert listing["location"] == {
            "city": "Warszawa",
            "region": "Mokotów",
            "district": None,
            "address_label": "Dom Warszawa Mokotów",
            "lat": None,
            "lng": None,
        }
        assert canonical["pricing"] == {
            "amount": 1200000,
            "currency": "PLN",
            "period": "total",
            "price_label": None,
        }
        assert canonical["metrics"]["area_m2"] == 150
        assert canonical["metrics"]["plot_area_m2"] == 500
        assert canonical["metrics"]["rooms"] == 5
        assert canonical["technical"]["building_condition"] == "bardzo dobry"
        assert canonical["technical"]["property_condition"] == "do zamieszkania"
        assert canonical["media"] == {
            "cover_image": "/static/images/777/image_777_url_1.jpg",
            "gallery": ["/static/images/777/image_777_url_1.jpg"],
            "video": None,
        }
        assert canonical["seo"]["og_image"] == "/static/images/777/image_777_url_1.jpg"
        assert canonical["raw"]["payload"] == row

    def test_spanish_offer_maps_to_es_eur(self):
        row = make_catalog_row(COUNTRY="Hiszpania")
        canonical = self._normalize(row)
        assert canonical["listing"]["country_code"] == "ES"
        assert canonical["pricing"]["currency"] == "EUR"

    def test_unrecognized_country_maps_to_unknown(self):
        row = make_catalog_row(COUNTRY="Portugalia")
        canonical = self._normalize(row)
        assert canonical["listing"]["country_code"] == "unknown"
        assert canonical["pricing"]["currency"] == "unknown"

    def test_blank_title_falls_back_to_property_and_offer_type(self):
        row = make_catalog_row(TITLE="")
        canonical = self._normalize(row)
        assert canonical["listing"]["title"] == "Dom na sprzedaż"

    def test_none_price_falls_back_to_zero(self):
        row = make_catalog_row(PRICE=None)
        canonical = self._normalize(row)
        assert canonical["pricing"]["amount"] == 0

    def test_missing_image_url_yields_empty_gallery_and_none_cover(self):
        row = make_catalog_row()
        canonical = self._normalize(row, image_url=None)
        assert canonical["media"]["cover_image"] is None
        assert canonical["media"]["gallery"] == []
        assert canonical["seo"]["og_image"] is None

    def test_empty_string_image_url_is_kept_as_cover_but_gallery_stays_empty(self):
        # Documents current behaviour: the falsy-but-not-None empty string
        # is still assigned to cover_image/og_image verbatim, while the
        # `if raw_offer["image_url"]` guard on gallery treats it as absent.
        row = make_catalog_row()
        canonical = self._normalize(row, image_url="")
        assert canonical["media"]["cover_image"] == ""
        assert canonical["media"]["gallery"] == []
        assert canonical["seo"]["og_image"] == ""


# ---------------------------------------------------------------------------
# normalize_offer(): kind == "offer_row"
# (needs request context for url_for(); IMAGES_DIR isolated via fixture)
# ---------------------------------------------------------------------------

class TestNormalizeOfferRow:
    def _normalize(self, record, video_exists=False):
        connector = InvestmentConnector()
        raw_offer = {"kind": "offer_row", "record": record, "video_exists": video_exists}
        return connector.normalize_offer(raw_offer)

    def test_full_field_mapping_with_no_images_on_disk(self, request_context):
        record = make_offer_record()
        canonical = self._normalize(record, video_exists=False)

        assert canonical["schema_version"] == "1.0"
        assert canonical["source"] == {
            "platform": "investment",
            "external_id": None,
            "external_url": None,
        }
        assert canonical["identity"]["offer_id"] == "555"

        listing = canonical["listing"]
        assert listing["title"] == "Gdańsk, Wrzeszcz"
        assert listing["property_type"] == "Mieszkanie"
        assert listing["offer_type"] == "sprzedaż"
        assert listing["market_type"] == "wtórny"
        assert listing["country_code"] == "PL"
        assert listing["description_html"] == "<p>Opis oferty</p>"
        assert listing["location"]["city"] == "Gdańsk"
        assert listing["location"]["region"] == "pomorskie"
        assert listing["location"]["address_label"] == "Gdańsk, Wrzeszcz"

        assert canonical["pricing"]["amount"] == 450000
        assert canonical["pricing"]["currency"] == "PLN"

        metrics = canonical["metrics"]
        assert metrics["area_m2"] == 62.5
        assert metrics["usable_area_m2"] == 58.0
        assert metrics["rooms"] == 3
        assert metrics["floor"] == 2
        assert metrics["floors_total"] == 4

        technical = canonical["technical"]
        assert technical["building_condition"] == "dobry"
        assert technical["property_condition"] == "do zamieszkania"
        assert technical["construction_year"] == 2015
        assert technical["heating"] == "gazowe"
        assert technical["parking"] == "tak"
        assert technical["utilities"] == {"electricity": "tak", "gas": "tak", "sewage": "miejska"}

        assert canonical["financials"]["admin_fee"] == 450

        # No files exist for id 555 under the isolated IMAGES_DIR -> fallback image.
        assert canonical["media"]["cover_image"].endswith("/static/images/no_image.svg")
        assert canonical["media"]["gallery"] == []
        assert canonical["media"]["video"] is None
        assert canonical["seo"]["og_image"] == canonical["media"]["cover_image"]

        agent = canonical["agent"]
        assert agent["agent_id"] == "12"
        assert agent["name"] == "Jan Kowalski"
        assert agent["email"] == "jan.kowalski@example.com"
        assert agent["phone"] == "600100200"
        assert agent["license"] == "12345"
        assert agent["branch"] == "Pomorskie"

        raw_payload = canonical["raw"]["payload"]
        assert raw_payload["record"] == record
        assert raw_payload["offer_dict"]["id"] == 555

    def test_spanish_offer_maps_to_es_eur(self, request_context):
        record = make_offer_record(COUNTRY="Hiszpania")
        canonical = self._normalize(record)
        assert canonical["listing"]["country_code"] == "ES"
        assert canonical["pricing"]["currency"] == "EUR"

    def test_unrecognized_country_maps_to_unknown(self, request_context):
        record = make_offer_record(COUNTRY="Portugalia")
        canonical = self._normalize(record)
        assert canonical["listing"]["country_code"] == "unknown"
        assert canonical["pricing"]["currency"] == "unknown"

    def test_video_exists_true_sets_local_video(self, request_context):
        record = make_offer_record()
        canonical = self._normalize(record, video_exists=True)
        assert canonical["media"]["video"] == "local"

    def test_blank_location_label_falls_back_to_bare_property_type(self, request_context):
        # Documents current behaviour: unlike catalog_row's fallback
        # (f"{property_type} na {offer_type}"), offer_row's fallback title
        # is just the bare property_type with no offer_type suffix.
        record = make_offer_record(LOCATION_LABEL="")
        canonical = self._normalize(record)
        assert canonical["listing"]["title"] == "Mieszkanie"

    def test_price_and_area_as_comma_decimal_strings_are_converted(self, request_context):
        record = make_offer_record(PRICE="450000,55", AREA_M2="62,5")
        canonical = self._normalize(record)
        assert canonical["pricing"]["amount"] == 450000.55
        assert canonical["metrics"]["area_m2"] == 62.5

    def test_missing_agent_contact_fields_get_default_fallbacks(self, request_context):
        record = make_offer_record(
            AGENT_NAME="", AGENT_SURNAME="", AGENT_PHONE="", AGENT_EMAIL="",
        )
        canonical = self._normalize(record)
        agent = canonical["agent"]
        assert agent["name"] == "Zespół Investment"
        assert agent["phone"] == "500 793 294"
        assert agent["email"] == "sebastian.szymoniak.investment@gmail.com"

    def test_zero_agent_id_is_treated_as_missing(self, request_context):
        # offer.get("agent_id") is falsy for 0, so agent_id/agent name is
        # serialized as None rather than "0".
        record = make_offer_record(AGENT_ID=0)
        canonical = self._normalize(record)
        assert canonical["agent"]["agent_id"] is None

    def test_cover_image_picks_lowest_url_index_when_multiple_images_exist(
        self, request_context, isolated_images_dir
    ):
        record = make_offer_record(ID=999)
        _write_image(isolated_images_dir, 999, "image_999_url_2.jpg")
        _write_image(isolated_images_dir, 999, "image_999_url_1.png")
        _write_image(isolated_images_dir, 999, "image_999_url_10.jpg")

        canonical = self._normalize(record)
        assert canonical["media"]["cover_image"].endswith("/static/images/999/image_999_url_1.png")

    def test_cover_image_ignores_files_not_matching_naming_convention(
        self, request_context, isolated_images_dir
    ):
        record = make_offer_record(ID=888)
        offer_dir = isolated_images_dir / "888"
        offer_dir.mkdir(parents=True, exist_ok=True)
        (offer_dir / "random_unrelated_file.jpg").write_bytes(b"noise")
        (offer_dir / "description_888.md").write_text("not an image")

        canonical = self._normalize(record)
        # No file matches the "image_888_url_<n>.<ext>" convention -> fallback.
        assert canonical["media"]["cover_image"].endswith("/static/images/no_image.svg")

    def test_cover_image_ignores_disallowed_extension(
        self, request_context, isolated_images_dir
    ):
        record = make_offer_record(ID=444)
        _write_image(isolated_images_dir, 444, "image_444_url_1.gif")

        canonical = self._normalize(record)
        assert canonical["media"]["cover_image"].endswith("/static/images/no_image.svg")
