from __future__ import annotations

import re

from integrations.tripinvest.details_crawler import collect_offer_details
from integrations.tripinvest.listing_crawler import collect_offers


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(value):
    text = str(value or "").strip().upper()
    if text in {"EUR", "€"}:
        return "EUR"
    if text in {"PLN", "ZL", "ZŁ"}:
        return "PLN"
    if text == "AED":
        return "AED"
    return "unknown"


def _infer_property_type(value, title=None):
    text = str(value or "").strip()
    if text and text.lower() != "unknown":
        return text

    normalized_title = str(title or "").strip().lower()
    if any(token in normalized_title for token in ("apartament", "mieszkanie", "apartment", "penthouse", "studio")):
        return "apartament"
    if any(token in normalized_title for token in ("dom", "willa", "villa", "house", "bungalow", "szeregowiec")):
        return "dom"
    if any(token in normalized_title for token in ("działka", "dzialka", "grunt", "plot")):
        return "działka"
    if any(token in normalized_title for token in ("lokal", "commercial", "biznes", "office", "hotel")):
        return "komercyjne"
    return "unknown"


class TripinvestConnector:
    source_name = "tripinvest"

    def fetch_catalog(self, filters: dict, page: int, per_page: int) -> tuple[list[dict], dict]:
        # per_page is ignored because upstream pagination is external.
        result = collect_offers(
            region=filters.get("region", "hiszpania"),
            area=filters.get("area"),
            filter_name=filters.get("filter"),
            sorting=filters.get("sorting"),
            offer_flag=filters.get("offer_flag") or [],
            market=filters.get("market") or [],
            price_min=filters.get("price_min"),
            price_max=filters.get("price_max"),
            area_min=filters.get("area_min"),
            area_max=filters.get("area_max"),
            land_area_min=filters.get("land_area_min"),
            land_area_max=filters.get("land_area_max"),
            query=filters.get("query"),
            bedrooms_min=filters.get("bedrooms_min"),
            bedrooms_max=filters.get("bedrooms_max"),
            bathrooms_min=filters.get("bathrooms_min"),
            bathrooms_max=filters.get("bathrooms_max"),
            sea_distance=filters.get("sea_distance") or [],
            features=filters.get("features") or [],
            pages=[page],
        )

        raw_offers = result.get("offers") or []
        pagination = result.get("pagination") or {}
        raw_items = [{"kind": "catalog_offer", "offer": offer} for offer in raw_offers]

        current_page = pagination.get("current_page") or page
        total_pages = pagination.get("total_pages") or current_page
        meta = {
            "total_records": len(raw_offers),
            "current_page": current_page,
            "per_page": per_page,
            "total_pages": total_pages,
        }
        return raw_items, meta

    def fetch_offer(self, identifier: dict) -> dict | None:
        url = identifier.get("url")
        if not url:
            return None
        results = collect_offer_details([url])
        if not results:
            return None
        return {"kind": "offer_details", "offer": results[0], "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 tripinvest raw offer kind: {kind}")

    def _normalize_catalog_offer(self, offer: dict) -> dict:
        images = offer.get("images") or []
        price_value = _parse_number(offer.get("price"))
        area_m2 = _parse_number(offer.get("area_m2"))
        plot_area_m2 = _parse_number(offer.get("plot_area_m2"))
        bedrooms = _parse_number(offer.get("bedrooms"))
        bathrooms = _parse_number(offer.get("bathrooms"))

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

    def _normalize_offer_details(self, offer: dict, url: str | None) -> dict:
        images = offer.get("images") or []
        price_value = _parse_number(offer.get("price"))
        area_m2 = _parse_number(offer.get("area_m2"))
        bedrooms = _parse_number(offer.get("bedrooms"))
        bathrooms = _parse_number(offer.get("bathrooms"))

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "tripinvest",
                "external_id": offer.get("ref"),
                "external_url": url,
            },
            "identity": {
                "offer_id": url or offer.get("ref") or "tripinvest-unknown",
                "reference": offer.get("ref"),
                "slug": None,
            },
            "status": {
                "lifecycle": "active",
                "labels": offer.get("labels") or [],
                "published_at": None,
                "updated_at": None,
            },
            "listing": {
                "title": offer.get("title") or "Nieruchomość",
                "subtitle": None,
                "description_text": offer.get("description"),
                "description_html": offer.get("description"),
                "property_type": _infer_property_type(offer.get("property_type"), offer.get("title")),
                "offer_type": "sale",
                "market_type": offer.get("market") or "unknown",
                "country_code": "ES",
                "location": {
                    "city": offer.get("location"),
                    "region": None,
                    "district": None,
                    "address_label": offer.get("location"),
                    "lat": None,
                    "lng": None,
                },
            },
            "pricing": {
                "amount": price_value,
                "currency": _normalize_currency(offer.get("currency") or "EUR"),
                "period": "total",
                "price_label": offer.get("price"),
            },
            "metrics": {
                "area_m2": area_m2,
                "usable_area_m2": None,
                "plot_area_m2": _parse_number(offer.get("plot_area_m2")),
                "rooms": None,
                "bedrooms": bedrooms,
                "bathrooms": bathrooms,
                "floor": offer.get("floor"),
                "floors_total": None,
            },
            "technical": {
                "building_condition": None,
                "property_condition": None,
                "construction_year": None,
                "heating": None,
                "parking": None,
                "windows_type": None,
                "kitchen_type": None,
                "furnishing": None,
                "utilities": {
                    "electricity": None,
                    "gas": None,
                    "sewage": None,
                },
            },
            "financials": {
                "admin_fee": None,
                "payment_plan": [],
            },
            "media": {
                "cover_image": images[0] if images else None,
                "gallery": images,
                "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": images[0] if images else None,
            },
            "raw": {"payload": offer},
        }
