"""Characterisation tests for the pure normalize_offer() paths of the
tripinvest/avarten/lanzarote connectors.

Scope: only `normalize_offer()` (and its private `_normalize_*` /
`_parse_number` / `_normalize_currency*` helpers) is covered here, because
those are pure functions over already-fetched dicts. `fetch_catalog()` and
`fetch_offer()` on these connectors perform real HTTP/scraping I/O and are
intentionally NOT exercised by this test layer.

The InvestmentConnector is excluded from this file: its normalize_offer()
depends on modules.investment.functions.get_image_path(), which needs an
application/request context (url_for) and touches the local filesystem
(static/images/<id>). That is a reasonable next-step target, not a "pure"
connector element.
"""
import pytest

from integrations.avarten.connector import AvartenConnector
from integrations.avarten.connector import _parse_number as avarten_parse_number
from integrations.avarten.connector import _normalize_currency as avarten_normalize_currency
from InvestmentWebsite.offers.connectors.lanzarote_connector import LanzaroteConnector
from InvestmentWebsite.offers.connectors.lanzarote_connector import _parse_number as lanzarote_parse_number
from InvestmentWebsite.offers.connectors.lanzarote_connector import (
    _normalize_currency_from_price as lanzarote_normalize_currency_from_price,
)
from integrations.tripinvest.connector import TripinvestConnector
from integrations.tripinvest.connector import _parse_number as tripinvest_parse_number
from integrations.tripinvest.connector import (
    _infer_property_type as tripinvest_infer_property_type,
)
from integrations.tripinvest.connector import (
    _normalize_currency as tripinvest_normalize_currency,
)


# ---------------------------------------------------------------------------
# _parse_number: identical implementation duplicated across the three
# connectors. Tested per-module to document each independently (in case they
# drift apart later).
# ---------------------------------------------------------------------------

@pytest.mark.parametrize(
    "parse_number",
    [avarten_parse_number, tripinvest_parse_number, lanzarote_parse_number],
)
class TestParseNumberSharedBehaviour:
    def test_none_returns_none(self, parse_number):
        assert parse_number(None) is None

    def test_empty_string_returns_none(self, parse_number):
        assert parse_number("") is None
        assert parse_number("   ") is None

    def test_int_passthrough(self, parse_number):
        assert parse_number(120) == 120

    def test_float_passthrough(self, parse_number):
        assert parse_number(120.5) == 120.5

    def test_plain_digit_string(self, parse_number):
        assert parse_number("450000") == 450000

    def test_thousands_separator_space(self, parse_number):
        assert parse_number("450 000") == 450000

    def test_decimal_comma_only(self, parse_number):
        assert parse_number("120,5") == 120.5

    def test_mixed_dot_and_comma_strips_comma_only(self, parse_number):
        # Documented current (likely buggy) behaviour: when both "." and ","
        # are present, only "," is stripped and "." is kept as-is. For a
        # European-style thousands-dot + decimal-comma input like
        # "450.000,50" this does NOT yield 450000.5 as one might expect;
        # it yields 450.0005 because "." is treated as the decimal point.
        # See recon notes handed back to the user for details.
        assert parse_number("450.000,50") == 450.0005

    def test_currency_symbol_is_stripped(self, parse_number):
        assert parse_number("450 000 EUR") == 450000

    def test_non_numeric_returns_none(self, parse_number):
        assert parse_number("brak danych") is None


# ---------------------------------------------------------------------------
# Currency normalization helpers (three distinct implementations).
# ---------------------------------------------------------------------------

class TestAvartenNormalizeCurrency:
    @pytest.mark.parametrize("raw,expected", [
        ("AED", "AED"), ("eur", "EUR"), ("€", "EUR"),
        ("PLN", "PLN"), ("zl", "PLN"), ("ZŁ", "PLN"),
        ("USD", "unknown"), (None, "unknown"), ("", "unknown"),
    ])
    def test_values(self, raw, expected):
        assert avarten_normalize_currency(raw) == expected


class TestTripinvestNormalizeCurrency:
    @pytest.mark.parametrize("raw,expected", [
        ("EUR", "EUR"), ("€", "EUR"),
        ("PLN", "PLN"), ("zl", "PLN"), ("ZŁ", "PLN"),
        ("AED", "AED"),
        ("USD", "unknown"), (None, "unknown"),
    ])
    def test_values(self, raw, expected):
        assert tripinvest_normalize_currency(raw) == expected


class TestLanzaroteNormalizeCurrencyFromPrice:
    @pytest.mark.parametrize("raw,expected", [
        ("120 000 EUR", "EUR"),
        ("120 000 €", "EUR"),
        ("120 000 AED", "AED"),
        ("120 000 PLN", "PLN"),
        ("120 000 zl", "PLN"),
        ("120 000 USD", "unknown"),
        (None, "unknown"),
    ])
    def test_values(self, raw, expected):
        assert lanzarote_normalize_currency_from_price(raw) == expected


# ---------------------------------------------------------------------------
# Tripinvest-specific: _infer_property_type
# ---------------------------------------------------------------------------

class TestTripinvestInferPropertyType:
    def test_explicit_known_value_is_kept(self):
        assert tripinvest_infer_property_type("villa", title="anything") == "villa"

    def test_unknown_value_falls_back_to_title_apartment(self):
        assert tripinvest_infer_property_type("unknown", title="Piękny Apartament w centrum") == "apartament"

    def test_unknown_value_falls_back_to_title_house(self):
        assert tripinvest_infer_property_type(None, title="Nowoczesna Villa nad morzem") == "dom"

    def test_unknown_value_falls_back_to_title_plot(self):
        assert tripinvest_infer_property_type(None, title="Działka budowlana") == "działka"

    def test_unknown_value_falls_back_to_title_commercial(self):
        assert tripinvest_infer_property_type(None, title="Lokal biurowy w centrum") == "komercyjne"

    def test_no_match_returns_unknown(self):
        assert tripinvest_infer_property_type(None, title="Coś zupełnie innego") == "unknown"


# ---------------------------------------------------------------------------
# normalize_offer(): full canonical-shape assertions on a couple of
# representative fields per connector/kind, using hand-built raw dicts
# (no network I/O involved).
# ---------------------------------------------------------------------------

class TestTripinvestNormalizeOffer:
    def setup_method(self):
        self.connector = TripinvestConnector()

    def test_catalog_offer(self):
        raw = {
            "kind": "catalog_offer",
            "offer": {
                "title": "Apartament z widokiem na morze",
                "url": "https://tripinvest.example/offer/1",
                "ref": "REF-1",
                "price": "250 000 EUR",
                "area_m2": "85",
                "images": ["https://img.example/1.jpg"],
                "location": "Torrevieja",
                "bedrooms": "2",
                "bathrooms": "1",
            },
        }
        canonical = self.connector.normalize_offer(raw)
        assert canonical["source"]["platform"] == "tripinvest"
        assert canonical["identity"]["offer_id"] == "https://tripinvest.example/offer/1"
        assert canonical["listing"]["title"] == "Apartament z widokiem na morze"
        assert canonical["listing"]["country_code"] == "ES"
        assert canonical["pricing"]["amount"] == 250000
        assert canonical["pricing"]["currency"] == "EUR"
        assert canonical["metrics"]["area_m2"] == 85
        assert canonical["metrics"]["bedrooms"] == 2
        assert canonical["media"]["cover_image"] == "https://img.example/1.jpg"

    def test_catalog_offer_missing_title_and_ref_falls_back(self):
        raw = {"kind": "catalog_offer", "offer": {}}
        canonical = self.connector.normalize_offer(raw)
        assert canonical["listing"]["title"] == "Nieruchomość"
        assert canonical["identity"]["offer_id"] == "tripinvest-unknown"
        assert canonical["media"]["gallery"] == []
        assert canonical["media"]["cover_image"] is None

    def test_offer_details_uses_explicit_currency_field(self):
        raw = {
            "kind": "offer_details",
            "offer": {
                "title": "Willa premium",
                "price": "1 200 000",
                "currency": "PLN",
                "description": "Opis oferty",
            },
            "url": "https://tripinvest.example/offer/2",
        }
        canonical = self.connector.normalize_offer(raw)
        assert canonical["pricing"]["currency"] == "PLN"
        assert canonical["pricing"]["amount"] == 1200000
        assert canonical["listing"]["description_text"] == "Opis oferty"
        assert canonical["seo"]["canonical_url"] == "https://tripinvest.example/offer/2"

    def test_unsupported_kind_raises(self):
        with pytest.raises(ValueError, match="Unsupported tripinvest raw offer kind"):
            self.connector.normalize_offer({"kind": "something_else"})


class TestAvartenNormalizeOffer:
    def setup_method(self):
        self.connector = AvartenConnector()

    def test_catalog_offer(self):
        raw = {
            "kind": "catalog_offer",
            "offer": {
                "title": "Penthouse Dubai Marina",
                "url": "https://avarten.example/offer/9",
                "offer_id": "9",
                "price_from": "2 500 000 AED",
                "currency": "AED",
                "images": [{"image": "https://img.example/9.jpg"}],
                "location": "Dubai Marina",
                "beds_raw": "3",
                "baths_raw": "2",
            },
        }
        canonical = self.connector.normalize_offer(raw)
        assert canonical["source"]["platform"] == "avarten"
        assert canonical["listing"]["country_code"] == "AE"
        assert canonical["pricing"]["currency"] == "AED"
        assert canonical["pricing"]["amount"] == 2500000
        assert canonical["metrics"]["bedrooms"] == 3
        assert canonical["media"]["gallery"] == ["https://img.example/9.jpg"]

    def test_catalog_offer_missing_images_yields_empty_gallery(self):
        raw = {"kind": "catalog_offer", "offer": {}}
        canonical = self.connector.normalize_offer(raw)
        assert canonical["media"]["gallery"] == []
        assert canonical["media"]["cover_image"] is None
        assert canonical["identity"]["offer_id"] == "avarten-unknown"

    def test_offer_details_builds_payment_plan_items_from_dict(self):
        raw = {
            "kind": "offer_details",
            "offer": {
                "title": "Villa Dubai Hills",
                "price_from": "5 000 000",
                "currency": "AED",
                "location": {"Miejscowość": "Dubai Hills", "Województwo": None},
                "payment_plan": {"downpayment": "20%", "handover": "80%"},
                "gallery": ["https://img.example/10.jpg"],
            },
            "url": "https://avarten.example/offer/10",
        }
        canonical = self.connector.normalize_offer(raw)
        assert canonical["financials"]["payment_plan"] == [
            {"stage": "downpayment", "value": "20%"},
            {"stage": "handover", "value": "80%"},
        ]
        assert canonical["listing"]["location"]["city"] == "Dubai Hills"

    def test_unsupported_kind_raises(self):
        with pytest.raises(ValueError, match="Unsupported avarten raw offer kind"):
            self.connector.normalize_offer({"kind": "nope"})


class TestLanzaroteNormalizeOffer:
    def setup_method(self):
        self.connector = LanzaroteConnector()

    def test_catalog_offer(self):
        raw = {
            "kind": "catalog_offer",
            "offer": {
                "title": "Chalet en Playa Blanca",
                "url": "https://homelanzarote.example/offer/5",
                "ref": "HL-5",
                "price": "350 000 EUR",
                "image": "https://img.example/5.jpg",
                "location": "Playa Blanca",
                "size": "120",
                "bedrooms": "3",
                "bathrooms": "2",
                "label": "new",
            },
        }
        canonical = self.connector.normalize_offer(raw)
        assert canonical["source"]["platform"] == "lanzarote"
        assert canonical["pricing"]["currency"] == "EUR"
        assert canonical["pricing"]["amount"] == 350000
        assert canonical["metrics"]["area_m2"] == 120
        assert canonical["status"]["labels"] == ["new"]
        assert canonical["media"]["gallery"] == ["https://img.example/5.jpg"]

    def test_catalog_offer_missing_fields_falls_back(self):
        raw = {"kind": "catalog_offer", "offer": {}}
        canonical = self.connector.normalize_offer(raw)
        assert canonical["listing"]["title"] == "Nieruchomość"
        assert canonical["identity"]["offer_id"] == "lanzarote-unknown"
        assert canonical["status"]["labels"] == []
        assert canonical["media"]["gallery"] == []

    def test_offer_details_reads_features_and_details_dicts(self):
        raw = {
            "kind": "offer_details",
            "offer": {
                "title": "Villa con piscina",
                "price": "600 000 EUR",
                "image": "https://img.example/6.jpg",
                "location": "Puerto del Carmen",
                "features": {"size": "200", "bedrooms": "4", "bathrooms": "3"},
                "details": {"Rok budowy": "2015"},
                "description": "Opis szczegolowy",
            },
            "url": "https://homelanzarote.example/offer/6",
        }
        canonical = self.connector.normalize_offer(raw)
        assert canonical["metrics"]["area_m2"] == 200
        assert canonical["metrics"]["bedrooms"] == 4
        assert canonical["technical"]["construction_year"] == 2015
        assert canonical["listing"]["description_text"] == "Opis szczegolowy"

    def test_unsupported_kind_raises(self):
        with pytest.raises(ValueError, match="Unsupported lanzarote raw offer kind"):
            self.connector.normalize_offer({"kind": "whatever"})
