from __future__ import annotations

import re

from integrations.homelanzarote.scraper import scrape_category, scrape_offer_details


def _parse_number(value):
    if value is None:
        return None
    if isinstance(value, (int, float)):
        return value
    text = str(value).strip()
    if not text:
        return None
    cleaned = re.sub(r"[^\d,.\-]", "", text).replace(" ", "")
    if cleaned.count(",") > 0 and cleaned.count(".") > 0:
        cleaned = cleaned.replace(",", "")
    else:
        cleaned = cleaned.replace(",", ".")
    try:
        parsed = float(cleaned)
        return int(parsed) if parsed.is_integer() else parsed
    except ValueError:
        return None


def _normalize_currency_from_price(price_value):
    text = str(price_value or "").upper()
    if "EUR" in text or "€" in text:
        return "EUR"
    if "AED" in text:
        return "AED"
    if "PLN" in text or "ZL" in text or "ZŁ" in text:
        return "PLN"
    return "unknown"


class LanzaroteConnector:
    source_name = "lanzarote"

    def fetch_catalog(self, filters: dict, page: int, per_page: int) -> tuple[list[dict], dict]:
        category = filters.get("category")
        lang = filters.get("lang", "en")

        if not category:
            return [], {
                "total_records": 0,
                "current_page": 1,
                "per_page": per_page,
                "total_pages": 1,
            }

        offers = scrape_category(
            category_name=category,
            all_pages=True,
            lang=lang,
        )
        raw_items = [{"kind": "catalog_offer", "offer": offer, "lang": lang} for offer in offers]
        meta = {
            "total_records": len(offers),
            "current_page": 1,
            "per_page": len(offers) if offers else per_page,
            "total_pages": 1,
        }
        return raw_items, meta

    def fetch_offer(self, identifier: dict) -> dict | None:
        url = identifier.get("url")
        if not url:
            return None
        lang = identifier.get("lang", "en")
        details = scrape_offer_details(url, lang=lang)
        return {"kind": "offer_details", "offer": details, "lang": lang, "url": url}

    def normalize_offer(self, raw_offer: dict) -> dict:
        kind = raw_offer.get("kind")
        if kind == "catalog_offer":
            return self._normalize_catalog_offer(raw_offer["offer"])
        if kind == "offer_details":
            return self._normalize_offer_details(raw_offer["offer"], raw_offer.get("url"))
        raise ValueError(f"Unsupported lanzarote raw offer kind: {kind}")

    def _normalize_catalog_offer(self, offer: dict) -> dict:
        price_raw = offer.get("price")
        price_amount = _parse_number(price_raw)
        currency = _normalize_currency_from_price(price_raw)
        image = offer.get("image")
        location = offer.get("location")
        external_url = offer.get("url")
        reference = offer.get("ref")

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "lanzarote",
                "external_id": reference,
                "external_url": external_url,
            },
            "identity": {
                "offer_id": external_url or str(reference or "lanzarote-unknown"),
                "reference": reference,
                "slug": None,
            },
            "status": {
                "lifecycle": "active",
                "labels": [offer.get("label")] if offer.get("label") else [],
                "published_at": None,
                "updated_at": None,
            },
            "listing": {
                "title": offer.get("title") or "Nieruchomość",
                "subtitle": offer.get("short_title"),
                "description_text": None,
                "description_html": None,
                "property_type": "unknown",
                "offer_type": "sale",
                "market_type": "unknown",
                "country_code": "ES",
                "location": {
                    "city": location,
                    "region": None,
                    "district": None,
                    "address_label": location,
                    "lat": None,
                    "lng": None,
                },
            },
            "pricing": {
                "amount": price_amount,
                "currency": currency,
                "period": "total",
                "price_label": price_raw,
            },
            "metrics": {
                "area_m2": _parse_number(offer.get("size")),
                "usable_area_m2": None,
                "plot_area_m2": None,
                "rooms": None,
                "bedrooms": _parse_number(offer.get("bedrooms")),
                "bathrooms": _parse_number(offer.get("bathrooms")),
                "floor": None,
                "floors_total": None,
            },
            "technical": {
                "building_condition": None,
                "property_condition": None,
                "construction_year": None,
                "heating": None,
                "parking": offer.get("garage"),
                "windows_type": None,
                "kitchen_type": None,
                "furnishing": None,
                "utilities": {
                    "electricity": None,
                    "gas": None,
                    "sewage": None,
                },
            },
            "financials": {
                "admin_fee": None,
                "payment_plan": [],
            },
            "media": {
                "cover_image": image,
                "gallery": [image] if image else [],
                "video": None,
            },
            "agent": {
                "agent_id": None,
                "name": None,
                "email": None,
                "phone": None,
                "license": None,
                "branch": None,
            },
            "seo": {
                "canonical_url": external_url,
                "robots": "noindex,follow",
                "og_image": image,
            },
            "raw": {"payload": offer},
        }

    def _normalize_offer_details(self, offer: dict, url: str | None) -> dict:
        features = offer.get("features") or {}
        details = offer.get("details") or {}
        price_raw = offer.get("price")
        price_amount = _parse_number(price_raw)
        currency = _normalize_currency_from_price(price_raw)
        image = offer.get("image")
        location = offer.get("location")
        reference = offer.get("ref")

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "lanzarote",
                "external_id": reference,
                "external_url": url,
            },
            "identity": {
                "offer_id": url or str(reference or "lanzarote-unknown"),
                "reference": reference,
                "slug": None,
            },
            "status": {
                "lifecycle": "active",
                "labels": [offer.get("label")] if offer.get("label") else [],
                "published_at": None,
                "updated_at": None,
            },
            "listing": {
                "title": offer.get("title") or "Nieruchomość",
                "subtitle": offer.get("short_title"),
                "description_text": offer.get("description"),
                "description_html": offer.get("description"),
                "property_type": "unknown",
                "offer_type": "sale",
                "market_type": "unknown",
                "country_code": "ES",
                "location": {
                    "city": location,
                    "region": None,
                    "district": None,
                    "address_label": location,
                    "lat": None,
                    "lng": None,
                },
            },
            "pricing": {
                "amount": price_amount,
                "currency": currency,
                "period": "total",
                "price_label": price_raw,
            },
            "metrics": {
                "area_m2": _parse_number(features.get("size") or details.get("Powierzchnia")),
                "usable_area_m2": None,
                "plot_area_m2": None,
                "rooms": None,
                "bedrooms": _parse_number(features.get("bedrooms")),
                "bathrooms": _parse_number(features.get("bathrooms")),
                "floor": None,
                "floors_total": None,
            },
            "technical": {
                "building_condition": None,
                "property_condition": None,
                "construction_year": _parse_number(details.get("Año construcción") or details.get("Rok budowy")),
                "heating": None,
                "parking": features.get("garage"),
                "windows_type": None,
                "kitchen_type": None,
                "furnishing": None,
                "utilities": {
                    "electricity": None,
                    "gas": None,
                    "sewage": None,
                },
            },
            "financials": {
                "admin_fee": None,
                "payment_plan": [],
            },
            "media": {
                "cover_image": image,
                "gallery": [image] if image else [],
                "video": None,
            },
            "agent": {
                "agent_id": None,
                "name": None,
                "email": None,
                "phone": None,
                "license": None,
                "branch": None,
            },
            "seo": {
                "canonical_url": url,
                "robots": "noindex,follow",
                "og_image": image,
            },
            "raw": {"payload": offer},
        }
