from __future__ import annotations

from InvestmentWebsite.services.catalog import get_estate_offer, get_estates_catalog, get_image_path
from InvestmentWebsite.services.offer_helpers import (
    apply_offer_contact_fallbacks,
    build_offer_dict,
    normalize_offer_record,
)
from InvestmentWebsite.offers.record_schema import CATALOG_ROW_IDX as CIDX


class InvestmentConnector:
    source_name = "investment"

    def fetch_catalog(self, filters: dict, page: int, per_page: int) -> tuple[list[dict], dict]:
        records, total_records = get_estates_catalog(
            page=page,
            per_page=per_page,
            **filters,
        )

        raw_items = []
        for row in records:
            raw_items.append(
                {
                    "kind": "catalog_row",
                    "row": row,
                    "image_url": get_image_path(row[CIDX.ID]),
                }
            )

        total_pages = -(-total_records // per_page)
        meta = {
            "total_records": total_records,
            "current_page": page,
            "per_page": per_page,
            "total_pages": total_pages,
        }
        return raw_items, meta

    def fetch_offer(self, identifier: dict) -> dict | None:
        estate_id = identifier.get("id")
        result = get_estate_offer(estate_id)
        if not result:
            return None

        raw_record, video_exists_flag = result
        return {
            "kind": "offer_row",
            "record": raw_record,
            "video_exists": bool(video_exists_flag),
        }

    def normalize_offer(self, raw_offer: dict) -> dict:
        kind = raw_offer.get("kind")
        if kind == "catalog_row":
            return self._normalize_catalog_row(raw_offer)
        if kind == "offer_row":
            return self._normalize_offer_row(raw_offer)
        raise ValueError(f"Unsupported investment raw offer kind: {kind}")

    def _normalize_catalog_row(self, raw_offer: dict) -> dict:
        row = raw_offer["row"]
        location_label = (row[CIDX.TITLE] or "").strip()
        city = (row[CIDX.CITY] or "").strip()
        region = (row[CIDX.LOCATION] or "").strip()
        country = (row[CIDX.COUNTRY] or "").strip()
        property_type = (row[CIDX.PROPERTY_TYPE] or "").strip()
        offer_type = (row[CIDX.OFFER_TYPE] or "").strip()
        market_type = (row[CIDX.MARKET_TYPE] or "").strip()

        price = row[CIDX.PRICE] or 0
        area_m2 = row[CIDX.AREA_M2]
        plot_area_m2 = row[CIDX.PLOT_AREA_M2]
        rooms = row[CIDX.ROOMS]

        country_code = "PL" if country == "Polska" else "ES" if country == "Hiszpania" else "unknown"
        currency = "PLN" if country == "Polska" else "EUR" if country == "Hiszpania" else "unknown"

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "investment",
                "external_id": None,
                "external_url": None,
            },
            "identity": {
                "offer_id": str(row[CIDX.ID]),
                "reference": None,
                "slug": None,
            },
            "status": {
                "lifecycle": "active",
                "labels": [],
                "published_at": None,
                "updated_at": None,
            },
            "listing": {
                "title": location_label or f"{property_type} na {offer_type}".strip(),
                "subtitle": None,
                "description_text": None,
                "description_html": None,
                "property_type": property_type,
                "offer_type": offer_type,
                "market_type": market_type,
                "country_code": country_code,
                "location": {
                    "city": city or None,
                    "region": region or None,
                    "district": None,
                    "address_label": location_label or None,
                    "lat": None,
                    "lng": None,
                },
            },
            "pricing": {
                "amount": price,
                "currency": currency,
                "period": "total",
                "price_label": None,
            },
            "metrics": {
                "area_m2": area_m2,
                "usable_area_m2": None,
                "plot_area_m2": plot_area_m2,
                "rooms": rooms,
                "bedrooms": None,
                "bathrooms": None,
                "floor": None,
                "floors_total": None,
            },
            "technical": {
                "building_condition": row[CIDX.BUILDING_CONDITION],
                "property_condition": row[CIDX.PROPERTY_CONDITION],
                "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": raw_offer["image_url"],
                "gallery": [raw_offer["image_url"]] if raw_offer["image_url"] else [],
                "video": None,
            },
            "agent": {
                "agent_id": None,
                "name": None,
                "email": None,
                "phone": None,
                "license": None,
                "branch": None,
            },
            "seo": {
                "canonical_url": None,
                "robots": None,
                "og_image": raw_offer["image_url"],
            },
            "raw": {"payload": row},
        }

    def _normalize_offer_row(self, raw_offer: dict) -> dict:
        record = normalize_offer_record(raw_offer["record"])
        offer = apply_offer_contact_fallbacks(build_offer_dict(record))
        country = (offer.get("country") or "").strip()

        country_code = "PL" if country == "Polska" else "ES" if country == "Hiszpania" else "unknown"
        currency = "PLN" if country == "Polska" else "EUR" if country == "Hiszpania" else "unknown"

        return {
            "schema_version": "1.0",
            "source": {
                "platform": "investment",
                "external_id": None,
                "external_url": None,
            },
            "identity": {
                "offer_id": str(offer["id"]),
                "reference": None,
                "slug": None,
            },
            "status": {
                "lifecycle": "active",
                "labels": [],
                "published_at": None,
                "updated_at": None,
            },
            "listing": {
                "title": (offer.get("location_label") or "").strip() or f"{offer.get('property_type') or 'Nieruchomość'}",
                "subtitle": None,
                "description_text": None,
                "description_html": offer.get("description_html"),
                "property_type": offer.get("property_type"),
                "offer_type": offer.get("offer_type"),
                "market_type": offer.get("market_type"),
                "country_code": country_code,
                "location": {
                    "city": offer.get("city"),
                    "region": offer.get("region"),
                    "district": None,
                    "address_label": offer.get("location_label"),
                    "lat": None,
                    "lng": None,
                },
            },
            "pricing": {
                "amount": offer.get("price"),
                "currency": currency,
                "period": "total",
                "price_label": None,
            },
            "metrics": {
                "area_m2": offer.get("area_m2"),
                "usable_area_m2": offer.get("usable_area_m2"),
                "plot_area_m2": offer.get("plot_area_m2"),
                "rooms": offer.get("rooms"),
                "bedrooms": None,
                "bathrooms": None,
                "floor": offer.get("floor"),
                "floors_total": offer.get("floors_count"),
            },
            "technical": {
                "building_condition": offer.get("building_condition"),
                "property_condition": offer.get("property_condition"),
                "construction_year": offer.get("construction_year"),
                "heating": offer.get("heating"),
                "parking": offer.get("parking"),
                "windows_type": offer.get("windows_type"),
                "kitchen_type": offer.get("kitchen_type"),
                "furnishing": offer.get("furnishing"),
                "utilities": {
                    "electricity": offer.get("electricity"),
                    "gas": offer.get("gas"),
                    "sewage": offer.get("sewage"),
                },
            },
            "financials": {
                "admin_fee": offer.get("admin_fee"),
                "payment_plan": [],
            },
            "media": {
                "cover_image": get_image_path(offer["id"]),
                "gallery": [],
                "video": "local" if raw_offer["video_exists"] else None,
            },
            "agent": {
                "agent_id": str(offer["agent_id"]) if offer.get("agent_id") else None,
                "name": " ".join(
                    x for x in [offer["agent"].get("name"), offer["agent"].get("surname")] if x
                ) or None,
                "email": offer["agent"].get("email"),
                "phone": offer["agent"].get("phone"),
                "license": offer["agent"].get("license"),
                "branch": offer["agent"].get("region"),
            },
            "seo": {
                "canonical_url": None,
                "robots": None,
                "og_image": get_image_path(offer["id"]),
            },
            "raw": {"payload": {"offer_dict": offer, "record": record}},
        }
