from flask import request, url_for

from InvestmentWebsite.services.catalog import get_image_path, list_offer_image_filenames
from InvestmentWebsite.offers.record_schema import OFFER_IDX as IDX
from InvestmentWebsite.seo import build_breadcrumb_json_ld


def to_float(value):
    if isinstance(value, (int, float)):
        return value
    try:
        return float(str(value).replace(",", "."))
    except Exception:
        return 0


def normalize_offer_record(record):
    normalized = list(record)
    normalized[IDX.PRICE] = to_float(normalized[IDX.PRICE])
    normalized[IDX.AREA_M2] = to_float(normalized[IDX.AREA_M2])
    return normalized


def build_offer_dict(record):
    return {
        "id": record[IDX.ID],
        "property_type": (record[IDX.PROPERTY_TYPE] or "").strip(),
        "offer_type": (record[IDX.OFFER_TYPE] or "").strip(),
        "market_type": (record[IDX.MARKET_TYPE] or "").strip(),
        "country": (record[IDX.COUNTRY] or "").strip(),
        "city": (record[IDX.CITY] or "").strip(),
        "region": (record[IDX.REGION] or "").strip(),
        "price": record[IDX.PRICE] or 0,
        "plot_area_m2": record[IDX.PLOT_AREA_M2],
        "plot_shape": record[IDX.PLOT_SHAPE],
        "plot_terrain": record[IDX.PLOT_TERRAIN],
        "building_type": record[IDX.BUILDING_TYPE],
        "house_type": record[IDX.HOUSE_TYPE],
        "roof_type": record[IDX.ROOF_TYPE],
        "parking": record[IDX.PARKING],
        "floors_count": record[IDX.FLOORS_COUNT],
        "floor": record[IDX.FLOOR],
        "area_m2": record[IDX.AREA_M2],
        "usable_area_m2": record[IDX.USABLE_AREA_M2],
        "rooms": record[IDX.ROOMS],
        "furnishing": record[IDX.FURNISHING],
        "windows_type": record[IDX.WINDOWS_TYPE],
        "kitchen_type": record[IDX.KITCHEN_TYPE],
        "sewage": record[IDX.SEWAGE],
        "heating": record[IDX.HEATING],
        "electricity": record[IDX.ELECTRICITY],
        "gas": record[IDX.GAS],
        "admin_fee": record[IDX.ADMIN_FEE],
        "land_use": record[IDX.LAND_USE],
        "building_condition": record[IDX.BUILDING_CONDITION],
        "purpose": record[IDX.PURPOSE],
        "property_condition": record[IDX.PROPERTY_CONDITION],
        "construction_year": record[IDX.CONSTRUCTION_YEAR],
        "agent_id": record[IDX.AGENT_ID],
        "location_label": (record[IDX.LOCATION_LABEL] or "").strip(),
        "image_count": int(record[IDX.IMAGE_COUNT] or 0),
        "agent": {
            "name": (record[IDX.AGENT_NAME] or "").strip(),
            "surname": (record[IDX.AGENT_SURNAME] or "").strip(),
            "email": (record[IDX.AGENT_EMAIL] or "").strip(),
            "phone": (record[IDX.AGENT_PHONE] or "").strip(),
            "license": (record[IDX.AGENT_LICENSE] or "").strip(),
            "region": (record[IDX.AGENT_REGION] or "").strip(),
            "branch": (record[IDX.AGENT_REGION] or "").strip(),
            "roles": (record[IDX.AGENT_ROLES] or "").strip(),
        },
        "description_html": record[IDX.DESCRIPTION_HTML] or "",
    }


def apply_offer_contact_fallbacks(offer):
    if not offer["agent"]["name"] and not offer["agent"]["surname"]:
        offer["agent"]["name"] = "Zespół"
        offer["agent"]["surname"] = "Investment"
    if not offer["agent"]["phone"]:
        offer["agent"]["phone"] = "500 793 294"
    if not offer["agent"]["email"]:
        offer["agent"]["email"] = "sebastian.szymoniak.investment@gmail.com"
    return offer


def build_offer_detail_items(record, details_config):
    items = []
    for field in details_config:
        label = field[0]
        idx = field[1]
        unit = field[2] if len(field) > 2 else ""
        value = record[idx]
        if value:
            items.append(
                {
                    "label": label,
                    "value": value,
                    "unit": unit,
                }
            )
    return items


def extract_offer_payload_from_canonical(canonical):
    raw_payload = (canonical.get("raw") or {}).get("payload") or {}
    offer = raw_payload.get("offer_dict")
    record = raw_payload.get("record")
    video_exists_flag = bool((canonical.get("media") or {}).get("video"))
    return offer, record, video_exists_flag


def build_offer_gallery_images(offer_id, image_count):
    return [
        url_for("static", filename=f"images/{offer_id}/{filename}")
        for filename in list_offer_image_filenames(offer_id)
    ]


def build_offer_meta(offer, canonical_url=None):
    country = (offer.get("country") or "").strip()
    city = (offer.get("city") or "").strip()
    offer_title = (offer.get("location_label") or "").strip()
    offer_type = (offer.get("property_type") or "Nieruchomość").strip()
    offer_mode = (offer.get("offer_type") or "").strip().lower()
    surface_m2 = int(offer["area_m2"]) if offer.get("area_m2") else None

    if not offer_title:
        offer_title = f"{offer_type} na {offer.get('offer_type', '')}".strip()

    page_title = f"{offer_title} | Investment Nieruchomości"
    currency = "EUR" if country == "Hiszpania" else "PLN"
    price_value = int(offer["price"]) if offer.get("price") else None

    offer_label = "oferty"
    if offer_mode == "sprzedaż":
        offer_label = "na sprzedaż"
    elif offer_mode == "wynajem":
        offer_label = "na wynajem"

    location_part = city if city else country
    description_parts = [f"{offer_type} {offer_label}".strip()]
    if location_part:
        description_parts.append(f"w {location_part}")
    if surface_m2:
        description_parts.append(f"o powierzchni {surface_m2} m2")
    if price_value:
        description_parts.append(
            f"w cenie {'{:,}'.format(price_value).replace(',', ' ')} {currency}"
        )
    description_parts.append("Sprawdź zdjęcia, szczegóły i kontakt do opiekuna oferty.")

    image_path = get_image_path(offer["id"])
    og_image = (
        f"{request.url_root.rstrip('/')}{image_path}"
        if image_path.startswith("/")
        else image_path
    )

    item_type = "Apartment" if offer_type in {"Mieszkanie", "Apartament", "Lokal"} else "House"

    resolved_canonical_url = canonical_url or request.base_url

    offer_schema = {
        "@context": "https://schema.org",
        "@type": "Offer",
        "url": resolved_canonical_url,
        "priceCurrency": currency,
        "availability": "https://schema.org/InStock",
        "itemOffered": {
            "@type": item_type,
            "name": offer_title,
            "image": og_image,
            "address": {
                "@type": "PostalAddress",
                "addressLocality": city,
                "addressCountry": "PL" if country == "Polska" else country,
            },
        },
    }
    if price_value:
        offer_schema["price"] = price_value
    if surface_m2:
        offer_schema["itemOffered"]["floorSize"] = {
            "@type": "QuantitativeValue",
            "value": surface_m2,
            "unitCode": "MTK",
        }

    breadcrumb_schema = build_breadcrumb_json_ld(
        [
            ("Strona główna", f"{request.url_root.rstrip('/')}/"),
            ("Katalog nieruchomości", f"{request.url_root.rstrip('/')}/nieruchomosci"),
            (offer_title, resolved_canonical_url),
        ]
    )

    return {
        "page_title": page_title,
        "meta_description": " ".join(description_parts),
        "og_image": og_image,
        "breadcrumb_schema": breadcrumb_schema,
        "offer_schema": offer_schema,
    }
